babylon.max.js 4.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266
  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. /**
  7459. * Generates an image screenshot from the specified camera.
  7460. *
  7461. * @param engine The engine to use for rendering
  7462. * @param camera The camera to use for rendering
  7463. * @param size This parameter can be set to a single number or to an object with the
  7464. * following (optional) properties: precision, width, height. If a single number is passed,
  7465. * it will be used for both width and height. If an object is passed, the screenshot size
  7466. * will be derived from the parameters. The precision property is a multiplier allowing
  7467. * rendering at a higher or lower resolution.
  7468. * @param successCallback The callback receives a single parameter which contains the
  7469. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7470. * src parameter of an <img> to display it.
  7471. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7472. * Check your browser for supported MIME types.
  7473. * @param samples Texture samples (default: 1)
  7474. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7475. * @param fileName A name for for the downloaded file.
  7476. * @constructor
  7477. */
  7478. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7479. if (mimeType === void 0) { mimeType = "image/png"; }
  7480. if (samples === void 0) { samples = 1; }
  7481. if (antialiasing === void 0) { antialiasing = false; }
  7482. var width;
  7483. var height;
  7484. //If a precision value is specified
  7485. if (size.precision) {
  7486. width = Math.round(engine.getRenderWidth() * size.precision);
  7487. height = Math.round(width / engine.getAspectRatio(camera));
  7488. size = { width: width, height: height };
  7489. }
  7490. else if (size.width && size.height) {
  7491. width = size.width;
  7492. height = size.height;
  7493. }
  7494. else if (size.width && !size.height) {
  7495. width = size.width;
  7496. height = Math.round(width / engine.getAspectRatio(camera));
  7497. size = { width: width, height: height };
  7498. }
  7499. else if (size.height && !size.width) {
  7500. height = size.height;
  7501. width = Math.round(height * engine.getAspectRatio(camera));
  7502. size = { width: width, height: height };
  7503. }
  7504. else if (!isNaN(size)) {
  7505. height = size;
  7506. width = size;
  7507. }
  7508. else {
  7509. Tools.Error("Invalid 'size' parameter !");
  7510. return;
  7511. }
  7512. var scene = camera.getScene();
  7513. var previousCamera = null;
  7514. if (scene.activeCamera !== camera) {
  7515. previousCamera = scene.activeCamera;
  7516. scene.activeCamera = camera;
  7517. }
  7518. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7519. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7520. texture.renderList = null;
  7521. texture.samples = samples;
  7522. if (antialiasing) {
  7523. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7524. }
  7525. texture.onAfterRenderObservable.add(function () {
  7526. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7527. });
  7528. scene.incrementRenderId();
  7529. scene.resetCachedMaterial();
  7530. texture.render(true);
  7531. texture.dispose();
  7532. if (previousCamera) {
  7533. scene.activeCamera = previousCamera;
  7534. }
  7535. camera.getProjectionMatrix(true); // Force cache refresh;
  7536. };
  7537. // XHR response validator for local file scenario
  7538. Tools.ValidateXHRData = function (xhr, dataType) {
  7539. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7540. if (dataType === void 0) { dataType = 7; }
  7541. try {
  7542. if (dataType & 1) {
  7543. if (xhr.responseText && xhr.responseText.length > 0) {
  7544. return true;
  7545. }
  7546. else if (dataType === 1) {
  7547. return false;
  7548. }
  7549. }
  7550. if (dataType & 2) {
  7551. // Check header width and height since there is no "TGA" magic number
  7552. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7553. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7554. return true;
  7555. }
  7556. else if (dataType === 2) {
  7557. return false;
  7558. }
  7559. }
  7560. if (dataType & 4) {
  7561. // Check for the "DDS" magic number
  7562. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7563. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7564. return true;
  7565. }
  7566. else {
  7567. return false;
  7568. }
  7569. }
  7570. }
  7571. catch (e) {
  7572. // Global protection
  7573. }
  7574. return false;
  7575. };
  7576. /**
  7577. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7578. * Be aware Math.random() could cause collisions, but:
  7579. * "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"
  7580. */
  7581. Tools.RandomId = function () {
  7582. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7583. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7584. return v.toString(16);
  7585. });
  7586. };
  7587. Object.defineProperty(Tools, "NoneLogLevel", {
  7588. get: function () {
  7589. return Tools._NoneLogLevel;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Tools, "MessageLogLevel", {
  7595. get: function () {
  7596. return Tools._MessageLogLevel;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Tools, "WarningLogLevel", {
  7602. get: function () {
  7603. return Tools._WarningLogLevel;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Tools, "ErrorLogLevel", {
  7609. get: function () {
  7610. return Tools._ErrorLogLevel;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Tools, "AllLogLevel", {
  7616. get: function () {
  7617. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Tools._AddLogEntry = function (entry) {
  7623. Tools._LogCache = entry + Tools._LogCache;
  7624. if (Tools.OnNewCacheEntry) {
  7625. Tools.OnNewCacheEntry(entry);
  7626. }
  7627. };
  7628. Tools._FormatMessage = function (message) {
  7629. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7630. var date = new Date();
  7631. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7632. };
  7633. Tools._LogDisabled = function (message) {
  7634. // nothing to do
  7635. };
  7636. Tools._LogEnabled = function (message) {
  7637. var formattedMessage = Tools._FormatMessage(message);
  7638. console.log("BJS - " + formattedMessage);
  7639. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7640. Tools._AddLogEntry(entry);
  7641. };
  7642. Tools._WarnDisabled = function (message) {
  7643. // nothing to do
  7644. };
  7645. Tools._WarnEnabled = function (message) {
  7646. var formattedMessage = Tools._FormatMessage(message);
  7647. console.warn("BJS - " + formattedMessage);
  7648. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7649. Tools._AddLogEntry(entry);
  7650. };
  7651. Tools._ErrorDisabled = function (message) {
  7652. // nothing to do
  7653. };
  7654. Tools._ErrorEnabled = function (message) {
  7655. Tools.errorsCount++;
  7656. var formattedMessage = Tools._FormatMessage(message);
  7657. console.error("BJS - " + formattedMessage);
  7658. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7659. Tools._AddLogEntry(entry);
  7660. };
  7661. Object.defineProperty(Tools, "LogCache", {
  7662. get: function () {
  7663. return Tools._LogCache;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. Tools.ClearLogCache = function () {
  7669. Tools._LogCache = "";
  7670. Tools.errorsCount = 0;
  7671. };
  7672. Object.defineProperty(Tools, "LogLevels", {
  7673. set: function (level) {
  7674. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7675. Tools.Log = Tools._LogEnabled;
  7676. }
  7677. else {
  7678. Tools.Log = Tools._LogDisabled;
  7679. }
  7680. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7681. Tools.Warn = Tools._WarnEnabled;
  7682. }
  7683. else {
  7684. Tools.Warn = Tools._WarnDisabled;
  7685. }
  7686. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7687. Tools.Error = Tools._ErrorEnabled;
  7688. }
  7689. else {
  7690. Tools.Error = Tools._ErrorDisabled;
  7691. }
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. Tools.IsWindowObjectExist = function () {
  7697. return (typeof window) !== "undefined";
  7698. };
  7699. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7700. get: function () {
  7701. return Tools._PerformanceNoneLogLevel;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7707. get: function () {
  7708. return Tools._PerformanceUserMarkLogLevel;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7714. get: function () {
  7715. return Tools._PerformanceConsoleLogLevel;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7721. set: function (level) {
  7722. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7723. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7724. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7725. return;
  7726. }
  7727. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7728. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7729. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7730. return;
  7731. }
  7732. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7733. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7739. };
  7740. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7741. };
  7742. Tools._StartUserMark = function (counterName, condition) {
  7743. if (condition === void 0) { condition = true; }
  7744. if (!Tools._performance) {
  7745. if (!Tools.IsWindowObjectExist()) {
  7746. return;
  7747. }
  7748. Tools._performance = window.performance;
  7749. }
  7750. if (!condition || !Tools._performance.mark) {
  7751. return;
  7752. }
  7753. Tools._performance.mark(counterName + "-Begin");
  7754. };
  7755. Tools._EndUserMark = function (counterName, condition) {
  7756. if (condition === void 0) { condition = true; }
  7757. if (!condition || !Tools._performance.mark) {
  7758. return;
  7759. }
  7760. Tools._performance.mark(counterName + "-End");
  7761. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7762. };
  7763. Tools._StartPerformanceConsole = function (counterName, condition) {
  7764. if (condition === void 0) { condition = true; }
  7765. if (!condition) {
  7766. return;
  7767. }
  7768. Tools._StartUserMark(counterName, condition);
  7769. if (console.time) {
  7770. console.time(counterName);
  7771. }
  7772. };
  7773. Tools._EndPerformanceConsole = function (counterName, condition) {
  7774. if (condition === void 0) { condition = true; }
  7775. if (!condition) {
  7776. return;
  7777. }
  7778. Tools._EndUserMark(counterName, condition);
  7779. if (console.time) {
  7780. console.timeEnd(counterName);
  7781. }
  7782. };
  7783. Object.defineProperty(Tools, "Now", {
  7784. get: function () {
  7785. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7786. return window.performance.now();
  7787. }
  7788. return new Date().getTime();
  7789. },
  7790. enumerable: true,
  7791. configurable: true
  7792. });
  7793. /**
  7794. * This method will return the name of the class used to create the instance of the given object.
  7795. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7796. * @param object the object to get the class name from
  7797. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7798. */
  7799. Tools.GetClassName = function (object, isType) {
  7800. if (isType === void 0) { isType = false; }
  7801. var name = null;
  7802. if (!isType && object.getClassName) {
  7803. name = object.getClassName();
  7804. }
  7805. else {
  7806. if (object instanceof Object) {
  7807. var classObj = isType ? object : Object.getPrototypeOf(object);
  7808. name = classObj.constructor["__bjsclassName__"];
  7809. }
  7810. if (!name) {
  7811. name = typeof object;
  7812. }
  7813. }
  7814. return name;
  7815. };
  7816. Tools.First = function (array, predicate) {
  7817. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7818. var el = array_1[_i];
  7819. if (predicate(el)) {
  7820. return el;
  7821. }
  7822. }
  7823. return null;
  7824. };
  7825. /**
  7826. * This method will return the name of the full name of the class, including its owning module (if any).
  7827. * 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).
  7828. * @param object the object to get the class name from
  7829. * @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.
  7830. */
  7831. Tools.getFullClassName = function (object, isType) {
  7832. if (isType === void 0) { isType = false; }
  7833. var className = null;
  7834. var moduleName = null;
  7835. if (!isType && object.getClassName) {
  7836. className = object.getClassName();
  7837. }
  7838. else {
  7839. if (object instanceof Object) {
  7840. var classObj = isType ? object : Object.getPrototypeOf(object);
  7841. className = classObj.constructor["__bjsclassName__"];
  7842. moduleName = classObj.constructor["__bjsmoduleName__"];
  7843. }
  7844. if (!className) {
  7845. className = typeof object;
  7846. }
  7847. }
  7848. if (!className) {
  7849. return null;
  7850. }
  7851. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7852. };
  7853. /**
  7854. * 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.
  7855. * @param array
  7856. */
  7857. Tools.arrayOrStringFeeder = function (array) {
  7858. return function (index) {
  7859. if (index >= array.length) {
  7860. return null;
  7861. }
  7862. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7863. if (val && val.getHashCode) {
  7864. val = val.getHashCode();
  7865. }
  7866. if (typeof val === "string") {
  7867. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7868. }
  7869. return val;
  7870. };
  7871. };
  7872. /**
  7873. * Compute the hashCode of a stream of number
  7874. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7875. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7876. * @return the hash code computed
  7877. */
  7878. Tools.hashCodeFromStream = function (feeder) {
  7879. // Based from here: http://stackoverflow.com/a/7616484/802124
  7880. var hash = 0;
  7881. var index = 0;
  7882. var chr = feeder(index++);
  7883. while (chr != null) {
  7884. hash = ((hash << 5) - hash) + chr;
  7885. hash |= 0; // Convert to 32bit integer
  7886. chr = feeder(index++);
  7887. }
  7888. return hash;
  7889. };
  7890. Tools.BaseUrl = "";
  7891. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7892. /**
  7893. * Default behaviour for cors in the application.
  7894. * It can be a string if the expected behavior is identical in the entire app.
  7895. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7896. */
  7897. Tools.CorsBehavior = "anonymous";
  7898. Tools.UseFallbackTexture = true;
  7899. /**
  7900. * Use this object to register external classes like custom textures or material
  7901. * to allow the laoders to instantiate them
  7902. */
  7903. Tools.RegisteredExternalClasses = {};
  7904. // Used in case of a texture loading problem
  7905. 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";
  7906. Tools.PreprocessUrl = function (url) {
  7907. return url;
  7908. };
  7909. // Logs
  7910. Tools._NoneLogLevel = 0;
  7911. Tools._MessageLogLevel = 1;
  7912. Tools._WarningLogLevel = 2;
  7913. Tools._ErrorLogLevel = 4;
  7914. Tools._LogCache = "";
  7915. Tools.errorsCount = 0;
  7916. Tools.Log = Tools._LogEnabled;
  7917. Tools.Warn = Tools._WarnEnabled;
  7918. Tools.Error = Tools._ErrorEnabled;
  7919. // Performances
  7920. Tools._PerformanceNoneLogLevel = 0;
  7921. Tools._PerformanceUserMarkLogLevel = 1;
  7922. Tools._PerformanceConsoleLogLevel = 2;
  7923. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7924. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7925. return Tools;
  7926. }());
  7927. BABYLON.Tools = Tools;
  7928. /**
  7929. * This class is used to track a performance counter which is number based.
  7930. * The user has access to many properties which give statistics of different nature
  7931. *
  7932. * The implementer can track two kinds of Performance Counter: time and count
  7933. * 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.
  7934. * 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.
  7935. */
  7936. var PerfCounter = /** @class */ (function () {
  7937. function PerfCounter() {
  7938. this._startMonitoringTime = 0;
  7939. this._min = 0;
  7940. this._max = 0;
  7941. this._average = 0;
  7942. this._lastSecAverage = 0;
  7943. this._current = 0;
  7944. this._totalValueCount = 0;
  7945. this._totalAccumulated = 0;
  7946. this._lastSecAccumulated = 0;
  7947. this._lastSecTime = 0;
  7948. this._lastSecValueCount = 0;
  7949. }
  7950. Object.defineProperty(PerfCounter.prototype, "min", {
  7951. /**
  7952. * Returns the smallest value ever
  7953. */
  7954. get: function () {
  7955. return this._min;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(PerfCounter.prototype, "max", {
  7961. /**
  7962. * Returns the biggest value ever
  7963. */
  7964. get: function () {
  7965. return this._max;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(PerfCounter.prototype, "average", {
  7971. /**
  7972. * Returns the average value since the performance counter is running
  7973. */
  7974. get: function () {
  7975. return this._average;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7981. /**
  7982. * Returns the average value of the last second the counter was monitored
  7983. */
  7984. get: function () {
  7985. return this._lastSecAverage;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(PerfCounter.prototype, "current", {
  7991. /**
  7992. * Returns the current value
  7993. */
  7994. get: function () {
  7995. return this._current;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(PerfCounter.prototype, "total", {
  8001. get: function () {
  8002. return this._totalAccumulated;
  8003. },
  8004. enumerable: true,
  8005. configurable: true
  8006. });
  8007. Object.defineProperty(PerfCounter.prototype, "count", {
  8008. get: function () {
  8009. return this._totalValueCount;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. /**
  8015. * Call this method to start monitoring a new frame.
  8016. * 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.
  8017. */
  8018. PerfCounter.prototype.fetchNewFrame = function () {
  8019. this._totalValueCount++;
  8020. this._current = 0;
  8021. this._lastSecValueCount++;
  8022. };
  8023. /**
  8024. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8025. * @param newCount the count value to add to the monitored count
  8026. * @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.
  8027. */
  8028. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8029. if (!PerfCounter.Enabled) {
  8030. return;
  8031. }
  8032. this._current += newCount;
  8033. if (fetchResult) {
  8034. this._fetchResult();
  8035. }
  8036. };
  8037. /**
  8038. * Start monitoring this performance counter
  8039. */
  8040. PerfCounter.prototype.beginMonitoring = function () {
  8041. if (!PerfCounter.Enabled) {
  8042. return;
  8043. }
  8044. this._startMonitoringTime = Tools.Now;
  8045. };
  8046. /**
  8047. * Compute the time lapsed since the previous beginMonitoring() call.
  8048. * @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
  8049. */
  8050. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8051. if (newFrame === void 0) { newFrame = true; }
  8052. if (!PerfCounter.Enabled) {
  8053. return;
  8054. }
  8055. if (newFrame) {
  8056. this.fetchNewFrame();
  8057. }
  8058. var currentTime = Tools.Now;
  8059. this._current = currentTime - this._startMonitoringTime;
  8060. if (newFrame) {
  8061. this._fetchResult();
  8062. }
  8063. };
  8064. PerfCounter.prototype._fetchResult = function () {
  8065. this._totalAccumulated += this._current;
  8066. this._lastSecAccumulated += this._current;
  8067. // Min/Max update
  8068. this._min = Math.min(this._min, this._current);
  8069. this._max = Math.max(this._max, this._current);
  8070. this._average = this._totalAccumulated / this._totalValueCount;
  8071. // Reset last sec?
  8072. var now = Tools.Now;
  8073. if ((now - this._lastSecTime) > 1000) {
  8074. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8075. this._lastSecTime = now;
  8076. this._lastSecAccumulated = 0;
  8077. this._lastSecValueCount = 0;
  8078. }
  8079. };
  8080. PerfCounter.Enabled = true;
  8081. return PerfCounter;
  8082. }());
  8083. BABYLON.PerfCounter = PerfCounter;
  8084. /**
  8085. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8086. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8087. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8088. * @param name The name of the class, case should be preserved
  8089. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8090. */
  8091. function className(name, module) {
  8092. return function (target) {
  8093. target["__bjsclassName__"] = name;
  8094. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8095. };
  8096. }
  8097. BABYLON.className = className;
  8098. /**
  8099. * An implementation of a loop for asynchronous functions.
  8100. */
  8101. var AsyncLoop = /** @class */ (function () {
  8102. /**
  8103. * Constroctor.
  8104. * @param iterations the number of iterations.
  8105. * @param _fn the function to run each iteration
  8106. * @param _successCallback the callback that will be called upon succesful execution
  8107. * @param offset starting offset.
  8108. */
  8109. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8110. if (offset === void 0) { offset = 0; }
  8111. this.iterations = iterations;
  8112. this._fn = _fn;
  8113. this._successCallback = _successCallback;
  8114. this.index = offset - 1;
  8115. this._done = false;
  8116. }
  8117. /**
  8118. * Execute the next iteration. Must be called after the last iteration was finished.
  8119. */
  8120. AsyncLoop.prototype.executeNext = function () {
  8121. if (!this._done) {
  8122. if (this.index + 1 < this.iterations) {
  8123. ++this.index;
  8124. this._fn(this);
  8125. }
  8126. else {
  8127. this.breakLoop();
  8128. }
  8129. }
  8130. };
  8131. /**
  8132. * Break the loop and run the success callback.
  8133. */
  8134. AsyncLoop.prototype.breakLoop = function () {
  8135. this._done = true;
  8136. this._successCallback();
  8137. };
  8138. /**
  8139. * Helper function
  8140. */
  8141. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8142. if (offset === void 0) { offset = 0; }
  8143. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8144. loop.executeNext();
  8145. return loop;
  8146. };
  8147. /**
  8148. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8149. * @param iterations total number of iterations
  8150. * @param syncedIterations number of synchronous iterations in each async iteration.
  8151. * @param fn the function to call each iteration.
  8152. * @param callback a success call back that will be called when iterating stops.
  8153. * @param breakFunction a break condition (optional)
  8154. * @param timeout timeout settings for the setTimeout function. default - 0.
  8155. * @constructor
  8156. */
  8157. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8158. if (timeout === void 0) { timeout = 0; }
  8159. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8160. if (breakFunction && breakFunction())
  8161. loop.breakLoop();
  8162. else {
  8163. setTimeout(function () {
  8164. for (var i = 0; i < syncedIterations; ++i) {
  8165. var iteration = (loop.index * syncedIterations) + i;
  8166. if (iteration >= iterations)
  8167. break;
  8168. fn(iteration);
  8169. if (breakFunction && breakFunction()) {
  8170. loop.breakLoop();
  8171. break;
  8172. }
  8173. }
  8174. loop.executeNext();
  8175. }, timeout);
  8176. }
  8177. }, callback);
  8178. };
  8179. return AsyncLoop;
  8180. }());
  8181. BABYLON.AsyncLoop = AsyncLoop;
  8182. })(BABYLON || (BABYLON = {}));
  8183. //# sourceMappingURL=babylon.tools.js.map
  8184. var BABYLON;
  8185. (function (BABYLON) {
  8186. var _AlphaState = /** @class */ (function () {
  8187. /**
  8188. * Initializes the state.
  8189. */
  8190. function _AlphaState() {
  8191. this._isAlphaBlendDirty = false;
  8192. this._isBlendFunctionParametersDirty = false;
  8193. this._isBlendEquationParametersDirty = false;
  8194. this._isBlendConstantsDirty = false;
  8195. this._alphaBlend = false;
  8196. this._blendFunctionParameters = new Array(4);
  8197. this._blendEquationParameters = new Array(2);
  8198. this._blendConstants = new Array(4);
  8199. this.reset();
  8200. }
  8201. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8202. get: function () {
  8203. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8209. get: function () {
  8210. return this._alphaBlend;
  8211. },
  8212. set: function (value) {
  8213. if (this._alphaBlend === value) {
  8214. return;
  8215. }
  8216. this._alphaBlend = value;
  8217. this._isAlphaBlendDirty = true;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8223. if (this._blendConstants[0] === r &&
  8224. this._blendConstants[1] === g &&
  8225. this._blendConstants[2] === b &&
  8226. this._blendConstants[3] === a) {
  8227. return;
  8228. }
  8229. this._blendConstants[0] = r;
  8230. this._blendConstants[1] = g;
  8231. this._blendConstants[2] = b;
  8232. this._blendConstants[3] = a;
  8233. this._isBlendConstantsDirty = true;
  8234. };
  8235. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8236. if (this._blendFunctionParameters[0] === value0 &&
  8237. this._blendFunctionParameters[1] === value1 &&
  8238. this._blendFunctionParameters[2] === value2 &&
  8239. this._blendFunctionParameters[3] === value3) {
  8240. return;
  8241. }
  8242. this._blendFunctionParameters[0] = value0;
  8243. this._blendFunctionParameters[1] = value1;
  8244. this._blendFunctionParameters[2] = value2;
  8245. this._blendFunctionParameters[3] = value3;
  8246. this._isBlendFunctionParametersDirty = true;
  8247. };
  8248. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8249. if (this._blendEquationParameters[0] === rgb &&
  8250. this._blendEquationParameters[1] === alpha) {
  8251. return;
  8252. }
  8253. this._blendEquationParameters[0] = rgb;
  8254. this._blendEquationParameters[1] = alpha;
  8255. this._isBlendEquationParametersDirty = true;
  8256. };
  8257. _AlphaState.prototype.reset = function () {
  8258. this._alphaBlend = false;
  8259. this._blendFunctionParameters[0] = null;
  8260. this._blendFunctionParameters[1] = null;
  8261. this._blendFunctionParameters[2] = null;
  8262. this._blendFunctionParameters[3] = null;
  8263. this._blendEquationParameters[0] = null;
  8264. this._blendEquationParameters[1] = null;
  8265. this._blendConstants[0] = null;
  8266. this._blendConstants[1] = null;
  8267. this._blendConstants[2] = null;
  8268. this._blendConstants[3] = null;
  8269. this._isAlphaBlendDirty = true;
  8270. this._isBlendFunctionParametersDirty = false;
  8271. this._isBlendEquationParametersDirty = false;
  8272. this._isBlendConstantsDirty = false;
  8273. };
  8274. _AlphaState.prototype.apply = function (gl) {
  8275. if (!this.isDirty) {
  8276. return;
  8277. }
  8278. // Alpha blend
  8279. if (this._isAlphaBlendDirty) {
  8280. if (this._alphaBlend) {
  8281. gl.enable(gl.BLEND);
  8282. }
  8283. else {
  8284. gl.disable(gl.BLEND);
  8285. }
  8286. this._isAlphaBlendDirty = false;
  8287. }
  8288. // Alpha function
  8289. if (this._isBlendFunctionParametersDirty) {
  8290. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8291. this._isBlendFunctionParametersDirty = false;
  8292. }
  8293. // Alpha equation
  8294. if (this._isBlendEquationParametersDirty) {
  8295. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8296. this._isBlendEquationParametersDirty = false;
  8297. }
  8298. // Constants
  8299. if (this._isBlendConstantsDirty) {
  8300. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8301. this._isBlendConstantsDirty = false;
  8302. }
  8303. };
  8304. return _AlphaState;
  8305. }());
  8306. BABYLON._AlphaState = _AlphaState;
  8307. })(BABYLON || (BABYLON = {}));
  8308. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8309. var BABYLON;
  8310. (function (BABYLON) {
  8311. var _DepthCullingState = /** @class */ (function () {
  8312. /**
  8313. * Initializes the state.
  8314. */
  8315. function _DepthCullingState() {
  8316. this._isDepthTestDirty = false;
  8317. this._isDepthMaskDirty = false;
  8318. this._isDepthFuncDirty = false;
  8319. this._isCullFaceDirty = false;
  8320. this._isCullDirty = false;
  8321. this._isZOffsetDirty = false;
  8322. this._isFrontFaceDirty = false;
  8323. this.reset();
  8324. }
  8325. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8326. get: function () {
  8327. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8333. get: function () {
  8334. return this._zOffset;
  8335. },
  8336. set: function (value) {
  8337. if (this._zOffset === value) {
  8338. return;
  8339. }
  8340. this._zOffset = value;
  8341. this._isZOffsetDirty = true;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8347. get: function () {
  8348. return this._cullFace;
  8349. },
  8350. set: function (value) {
  8351. if (this._cullFace === value) {
  8352. return;
  8353. }
  8354. this._cullFace = value;
  8355. this._isCullFaceDirty = true;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8361. get: function () {
  8362. return this._cull;
  8363. },
  8364. set: function (value) {
  8365. if (this._cull === value) {
  8366. return;
  8367. }
  8368. this._cull = value;
  8369. this._isCullDirty = true;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8375. get: function () {
  8376. return this._depthFunc;
  8377. },
  8378. set: function (value) {
  8379. if (this._depthFunc === value) {
  8380. return;
  8381. }
  8382. this._depthFunc = value;
  8383. this._isDepthFuncDirty = true;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8389. get: function () {
  8390. return this._depthMask;
  8391. },
  8392. set: function (value) {
  8393. if (this._depthMask === value) {
  8394. return;
  8395. }
  8396. this._depthMask = value;
  8397. this._isDepthMaskDirty = true;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8403. get: function () {
  8404. return this._depthTest;
  8405. },
  8406. set: function (value) {
  8407. if (this._depthTest === value) {
  8408. return;
  8409. }
  8410. this._depthTest = value;
  8411. this._isDepthTestDirty = true;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8417. get: function () {
  8418. return this._frontFace;
  8419. },
  8420. set: function (value) {
  8421. if (this._frontFace === value) {
  8422. return;
  8423. }
  8424. this._frontFace = value;
  8425. this._isFrontFaceDirty = true;
  8426. },
  8427. enumerable: true,
  8428. configurable: true
  8429. });
  8430. _DepthCullingState.prototype.reset = function () {
  8431. this._depthMask = true;
  8432. this._depthTest = true;
  8433. this._depthFunc = null;
  8434. this._cullFace = null;
  8435. this._cull = null;
  8436. this._zOffset = 0;
  8437. this._frontFace = null;
  8438. this._isDepthTestDirty = true;
  8439. this._isDepthMaskDirty = true;
  8440. this._isDepthFuncDirty = false;
  8441. this._isCullFaceDirty = false;
  8442. this._isCullDirty = false;
  8443. this._isZOffsetDirty = false;
  8444. this._isFrontFaceDirty = false;
  8445. };
  8446. _DepthCullingState.prototype.apply = function (gl) {
  8447. if (!this.isDirty) {
  8448. return;
  8449. }
  8450. // Cull
  8451. if (this._isCullDirty) {
  8452. if (this.cull) {
  8453. gl.enable(gl.CULL_FACE);
  8454. }
  8455. else {
  8456. gl.disable(gl.CULL_FACE);
  8457. }
  8458. this._isCullDirty = false;
  8459. }
  8460. // Cull face
  8461. if (this._isCullFaceDirty) {
  8462. gl.cullFace(this.cullFace);
  8463. this._isCullFaceDirty = false;
  8464. }
  8465. // Depth mask
  8466. if (this._isDepthMaskDirty) {
  8467. gl.depthMask(this.depthMask);
  8468. this._isDepthMaskDirty = false;
  8469. }
  8470. // Depth test
  8471. if (this._isDepthTestDirty) {
  8472. if (this.depthTest) {
  8473. gl.enable(gl.DEPTH_TEST);
  8474. }
  8475. else {
  8476. gl.disable(gl.DEPTH_TEST);
  8477. }
  8478. this._isDepthTestDirty = false;
  8479. }
  8480. // Depth func
  8481. if (this._isDepthFuncDirty) {
  8482. gl.depthFunc(this.depthFunc);
  8483. this._isDepthFuncDirty = false;
  8484. }
  8485. // zOffset
  8486. if (this._isZOffsetDirty) {
  8487. if (this.zOffset) {
  8488. gl.enable(gl.POLYGON_OFFSET_FILL);
  8489. gl.polygonOffset(this.zOffset, 0);
  8490. }
  8491. else {
  8492. gl.disable(gl.POLYGON_OFFSET_FILL);
  8493. }
  8494. this._isZOffsetDirty = false;
  8495. }
  8496. // Front face
  8497. if (this._isFrontFaceDirty) {
  8498. gl.frontFace(this.frontFace);
  8499. this._isFrontFaceDirty = false;
  8500. }
  8501. };
  8502. return _DepthCullingState;
  8503. }());
  8504. BABYLON._DepthCullingState = _DepthCullingState;
  8505. })(BABYLON || (BABYLON = {}));
  8506. //# sourceMappingURL=babylon.depthCullingState.js.map
  8507. var BABYLON;
  8508. (function (BABYLON) {
  8509. var _StencilState = /** @class */ (function () {
  8510. function _StencilState() {
  8511. this._isStencilTestDirty = false;
  8512. this._isStencilMaskDirty = false;
  8513. this._isStencilFuncDirty = false;
  8514. this._isStencilOpDirty = false;
  8515. this.reset();
  8516. }
  8517. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8518. get: function () {
  8519. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8525. get: function () {
  8526. return this._stencilFunc;
  8527. },
  8528. set: function (value) {
  8529. if (this._stencilFunc === value) {
  8530. return;
  8531. }
  8532. this._stencilFunc = value;
  8533. this._isStencilFuncDirty = true;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8539. get: function () {
  8540. return this._stencilFuncRef;
  8541. },
  8542. set: function (value) {
  8543. if (this._stencilFuncRef === value) {
  8544. return;
  8545. }
  8546. this._stencilFuncRef = value;
  8547. this._isStencilFuncDirty = true;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8553. get: function () {
  8554. return this._stencilFuncMask;
  8555. },
  8556. set: function (value) {
  8557. if (this._stencilFuncMask === value) {
  8558. return;
  8559. }
  8560. this._stencilFuncMask = value;
  8561. this._isStencilFuncDirty = true;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8567. get: function () {
  8568. return this._stencilOpStencilFail;
  8569. },
  8570. set: function (value) {
  8571. if (this._stencilOpStencilFail === value) {
  8572. return;
  8573. }
  8574. this._stencilOpStencilFail = value;
  8575. this._isStencilOpDirty = true;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8581. get: function () {
  8582. return this._stencilOpDepthFail;
  8583. },
  8584. set: function (value) {
  8585. if (this._stencilOpDepthFail === value) {
  8586. return;
  8587. }
  8588. this._stencilOpDepthFail = value;
  8589. this._isStencilOpDirty = true;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8595. get: function () {
  8596. return this._stencilOpStencilDepthPass;
  8597. },
  8598. set: function (value) {
  8599. if (this._stencilOpStencilDepthPass === value) {
  8600. return;
  8601. }
  8602. this._stencilOpStencilDepthPass = value;
  8603. this._isStencilOpDirty = true;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8609. get: function () {
  8610. return this._stencilMask;
  8611. },
  8612. set: function (value) {
  8613. if (this._stencilMask === value) {
  8614. return;
  8615. }
  8616. this._stencilMask = value;
  8617. this._isStencilMaskDirty = true;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8623. get: function () {
  8624. return this._stencilTest;
  8625. },
  8626. set: function (value) {
  8627. if (this._stencilTest === value) {
  8628. return;
  8629. }
  8630. this._stencilTest = value;
  8631. this._isStencilTestDirty = true;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. _StencilState.prototype.reset = function () {
  8637. this._stencilTest = false;
  8638. this._stencilMask = 0xFF;
  8639. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8640. this._stencilFuncRef = 1;
  8641. this._stencilFuncMask = 0xFF;
  8642. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8643. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8644. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8645. this._isStencilTestDirty = true;
  8646. this._isStencilMaskDirty = true;
  8647. this._isStencilFuncDirty = true;
  8648. this._isStencilOpDirty = true;
  8649. };
  8650. _StencilState.prototype.apply = function (gl) {
  8651. if (!this.isDirty) {
  8652. return;
  8653. }
  8654. // Stencil test
  8655. if (this._isStencilTestDirty) {
  8656. if (this.stencilTest) {
  8657. gl.enable(gl.STENCIL_TEST);
  8658. }
  8659. else {
  8660. gl.disable(gl.STENCIL_TEST);
  8661. }
  8662. this._isStencilTestDirty = false;
  8663. }
  8664. // Stencil mask
  8665. if (this._isStencilMaskDirty) {
  8666. gl.stencilMask(this.stencilMask);
  8667. this._isStencilMaskDirty = false;
  8668. }
  8669. // Stencil func
  8670. if (this._isStencilFuncDirty) {
  8671. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8672. this._isStencilFuncDirty = false;
  8673. }
  8674. // Stencil op
  8675. if (this._isStencilOpDirty) {
  8676. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8677. this._isStencilOpDirty = false;
  8678. }
  8679. };
  8680. return _StencilState;
  8681. }());
  8682. BABYLON._StencilState = _StencilState;
  8683. })(BABYLON || (BABYLON = {}));
  8684. //# sourceMappingURL=babylon.stencilState.js.map
  8685. var BABYLON;
  8686. (function (BABYLON) {
  8687. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8688. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8689. };
  8690. var compileRawShader = function (gl, source, type) {
  8691. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8692. gl.shaderSource(shader, source);
  8693. gl.compileShader(shader);
  8694. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8695. var log = gl.getShaderInfoLog(shader);
  8696. if (log) {
  8697. throw new Error(log);
  8698. }
  8699. }
  8700. if (!shader) {
  8701. throw new Error("Something went wrong while compile the shader.");
  8702. }
  8703. return shader;
  8704. };
  8705. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8706. var magFilter = gl.NEAREST;
  8707. var minFilter = gl.NEAREST;
  8708. switch (samplingMode) {
  8709. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8710. magFilter = gl.LINEAR;
  8711. if (generateMipMaps) {
  8712. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8713. }
  8714. else {
  8715. minFilter = gl.LINEAR;
  8716. }
  8717. break;
  8718. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8719. magFilter = gl.LINEAR;
  8720. if (generateMipMaps) {
  8721. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8722. }
  8723. else {
  8724. minFilter = gl.LINEAR;
  8725. }
  8726. break;
  8727. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8728. magFilter = gl.NEAREST;
  8729. if (generateMipMaps) {
  8730. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8731. }
  8732. else {
  8733. minFilter = gl.NEAREST;
  8734. }
  8735. break;
  8736. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8737. magFilter = gl.NEAREST;
  8738. if (generateMipMaps) {
  8739. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8740. }
  8741. else {
  8742. minFilter = gl.NEAREST;
  8743. }
  8744. break;
  8745. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8746. magFilter = gl.NEAREST;
  8747. if (generateMipMaps) {
  8748. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8749. }
  8750. else {
  8751. minFilter = gl.LINEAR;
  8752. }
  8753. break;
  8754. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8755. magFilter = gl.NEAREST;
  8756. if (generateMipMaps) {
  8757. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8758. }
  8759. else {
  8760. minFilter = gl.LINEAR;
  8761. }
  8762. break;
  8763. case BABYLON.Texture.NEAREST_LINEAR:
  8764. magFilter = gl.NEAREST;
  8765. minFilter = gl.LINEAR;
  8766. break;
  8767. case BABYLON.Texture.NEAREST_NEAREST:
  8768. magFilter = gl.NEAREST;
  8769. minFilter = gl.NEAREST;
  8770. break;
  8771. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8772. magFilter = gl.LINEAR;
  8773. if (generateMipMaps) {
  8774. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8775. }
  8776. else {
  8777. minFilter = gl.NEAREST;
  8778. }
  8779. break;
  8780. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8781. magFilter = gl.LINEAR;
  8782. if (generateMipMaps) {
  8783. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8784. }
  8785. else {
  8786. minFilter = gl.NEAREST;
  8787. }
  8788. break;
  8789. case BABYLON.Texture.LINEAR_LINEAR:
  8790. magFilter = gl.LINEAR;
  8791. minFilter = gl.LINEAR;
  8792. break;
  8793. case BABYLON.Texture.LINEAR_NEAREST:
  8794. magFilter = gl.LINEAR;
  8795. minFilter = gl.NEAREST;
  8796. break;
  8797. }
  8798. return {
  8799. min: minFilter,
  8800. mag: magFilter
  8801. };
  8802. };
  8803. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8804. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8805. var img;
  8806. var onload = function () {
  8807. loadedImages[index] = img;
  8808. loadedImages._internalCount++;
  8809. if (scene) {
  8810. scene._removePendingData(img);
  8811. }
  8812. if (loadedImages._internalCount === 6) {
  8813. onfinish(loadedImages);
  8814. }
  8815. };
  8816. var onerror = function (message, exception) {
  8817. if (scene) {
  8818. scene._removePendingData(img);
  8819. }
  8820. if (onErrorCallBack) {
  8821. onErrorCallBack(message, exception);
  8822. }
  8823. };
  8824. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8825. if (scene) {
  8826. scene._addPendingData(img);
  8827. }
  8828. };
  8829. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8830. if (onError === void 0) { onError = null; }
  8831. var loadedImages = [];
  8832. loadedImages._internalCount = 0;
  8833. for (var index = 0; index < 6; index++) {
  8834. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8835. }
  8836. };
  8837. var BufferPointer = /** @class */ (function () {
  8838. function BufferPointer() {
  8839. }
  8840. return BufferPointer;
  8841. }());
  8842. var InstancingAttributeInfo = /** @class */ (function () {
  8843. function InstancingAttributeInfo() {
  8844. }
  8845. return InstancingAttributeInfo;
  8846. }());
  8847. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8848. /**
  8849. * Define options used to create a render target texture
  8850. */
  8851. var RenderTargetCreationOptions = /** @class */ (function () {
  8852. function RenderTargetCreationOptions() {
  8853. }
  8854. return RenderTargetCreationOptions;
  8855. }());
  8856. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8857. /**
  8858. * Regroup several parameters relative to the browser in use
  8859. */
  8860. var EngineCapabilities = /** @class */ (function () {
  8861. function EngineCapabilities() {
  8862. }
  8863. return EngineCapabilities;
  8864. }());
  8865. BABYLON.EngineCapabilities = EngineCapabilities;
  8866. /**
  8867. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8868. */
  8869. var Engine = /** @class */ (function () {
  8870. /**
  8871. * @constructor
  8872. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8873. * @param antialias defines enable antialiasing (default: false)
  8874. * @param options defines further options to be sent to the getContext() function
  8875. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8876. */
  8877. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8878. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8879. var _this = this;
  8880. // Public members
  8881. this.forcePOTTextures = false;
  8882. this.isFullscreen = false;
  8883. this.isPointerLock = false;
  8884. this.cullBackFaces = true;
  8885. this.renderEvenInBackground = true;
  8886. this.preventCacheWipeBetweenFrames = false;
  8887. // To enable/disable IDB support and avoid XHR on .manifest
  8888. this.enableOfflineSupport = false;
  8889. this.scenes = new Array();
  8890. this.postProcesses = new Array();
  8891. // Observables
  8892. /**
  8893. * Observable event triggered each time the rendering canvas is resized
  8894. */
  8895. this.onResizeObservable = new BABYLON.Observable();
  8896. /**
  8897. * Observable event triggered each time the canvas loses focus
  8898. */
  8899. this.onCanvasBlurObservable = new BABYLON.Observable();
  8900. /**
  8901. * Observable event triggered each time the canvas gains focus
  8902. */
  8903. this.onCanvasFocusObservable = new BABYLON.Observable();
  8904. /**
  8905. * Observable event triggered each time the canvas receives pointerout event
  8906. */
  8907. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8908. /**
  8909. * Observable event triggered before each texture is initialized
  8910. */
  8911. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8912. //WebVR
  8913. this._vrDisplay = undefined;
  8914. this._vrSupported = false;
  8915. this._vrExclusivePointerMode = false;
  8916. // Uniform buffers list
  8917. this.disableUniformBuffers = false;
  8918. this._uniformBuffers = new Array();
  8919. // Observables
  8920. /**
  8921. * Observable raised when the engine begins a new frame
  8922. */
  8923. this.onBeginFrameObservable = new BABYLON.Observable();
  8924. /**
  8925. * Observable raised when the engine ends the current frame
  8926. */
  8927. this.onEndFrameObservable = new BABYLON.Observable();
  8928. /**
  8929. * Observable raised when the engine is about to compile a shader
  8930. */
  8931. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8932. /**
  8933. * Observable raised when the engine has jsut compiled a shader
  8934. */
  8935. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8936. this._windowIsBackground = false;
  8937. this._webGLVersion = 1.0;
  8938. this._badOS = false;
  8939. this._badDesktopOS = false;
  8940. /**
  8941. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8942. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8943. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8944. */
  8945. this.disableTextureBindingOptimization = false;
  8946. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8947. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8948. this.onVRRequestPresentStart = new BABYLON.Observable();
  8949. this._colorWrite = true;
  8950. this._drawCalls = new BABYLON.PerfCounter();
  8951. this._textureCollisions = new BABYLON.PerfCounter();
  8952. this._renderingQueueLaunched = false;
  8953. this._activeRenderLoops = new Array();
  8954. // Deterministic lockstepMaxSteps
  8955. this._deterministicLockstep = false;
  8956. this._lockstepMaxSteps = 4;
  8957. // Lost context
  8958. this.onContextLostObservable = new BABYLON.Observable();
  8959. this.onContextRestoredObservable = new BABYLON.Observable();
  8960. this._contextWasLost = false;
  8961. this._doNotHandleContextLost = false;
  8962. // FPS
  8963. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8964. this._fps = 60;
  8965. this._deltaTime = 0;
  8966. /**
  8967. * Turn this value on if you want to pause FPS computation when in background
  8968. */
  8969. this.disablePerformanceMonitorInBackground = false;
  8970. // States
  8971. this._depthCullingState = new BABYLON._DepthCullingState();
  8972. this._stencilState = new BABYLON._StencilState();
  8973. this._alphaState = new BABYLON._AlphaState();
  8974. this._alphaMode = Engine.ALPHA_DISABLE;
  8975. // Cache
  8976. this._internalTexturesCache = new Array();
  8977. this._activeChannel = 0;
  8978. this._currentTextureChannel = -1;
  8979. this._boundTexturesCache = {};
  8980. this._compiledEffects = {};
  8981. this._vertexAttribArraysEnabled = [];
  8982. this._uintIndicesCurrentlySet = false;
  8983. this._currentBoundBuffer = new Array();
  8984. this._currentBufferPointers = new Array();
  8985. this._currentInstanceLocations = new Array();
  8986. this._currentInstanceBuffers = new Array();
  8987. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  8988. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  8989. this._vaoRecordInProgress = false;
  8990. this._mustWipeVertexAttributes = false;
  8991. this._nextFreeTextureSlots = new Array();
  8992. this._maxSimultaneousTextures = 0;
  8993. this._activeRequests = new Array();
  8994. // Hardware supported Compressed Textures
  8995. this._texturesSupported = new Array();
  8996. this._onVRFullScreenTriggered = function () {
  8997. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8998. //get the old size before we change
  8999. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9000. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9001. //get the width and height, change the render size
  9002. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9003. _this.setHardwareScalingLevel(1);
  9004. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9005. }
  9006. else {
  9007. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9008. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9009. }
  9010. };
  9011. this._boundUniforms = {};
  9012. var canvas = null;
  9013. Engine.Instances.push(this);
  9014. if (!canvasOrContext) {
  9015. return;
  9016. }
  9017. options = options || {};
  9018. if (canvasOrContext.getContext) {
  9019. canvas = canvasOrContext;
  9020. this._renderingCanvas = canvas;
  9021. if (antialias != null) {
  9022. options.antialias = antialias;
  9023. }
  9024. if (options.deterministicLockstep === undefined) {
  9025. options.deterministicLockstep = false;
  9026. }
  9027. if (options.lockstepMaxSteps === undefined) {
  9028. options.lockstepMaxSteps = 4;
  9029. }
  9030. if (options.preserveDrawingBuffer === undefined) {
  9031. options.preserveDrawingBuffer = false;
  9032. }
  9033. if (options.audioEngine === undefined) {
  9034. options.audioEngine = true;
  9035. }
  9036. if (options.stencil === undefined) {
  9037. options.stencil = true;
  9038. }
  9039. this._deterministicLockstep = options.deterministicLockstep;
  9040. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9041. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9042. // Exceptions
  9043. if (navigator && navigator.userAgent) {
  9044. var ua = navigator.userAgent;
  9045. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9046. var exception = _a[_i];
  9047. var key = exception.key;
  9048. var targets = exception.targets;
  9049. if (ua.indexOf(key) > -1) {
  9050. if (exception.capture && exception.captureConstraint) {
  9051. var capture = exception.capture;
  9052. var constraint = exception.captureConstraint;
  9053. var regex = new RegExp(capture);
  9054. var matches = regex.exec(ua);
  9055. if (matches && matches.length > 0) {
  9056. var capturedValue = parseInt(matches[matches.length - 1]);
  9057. if (capturedValue >= constraint) {
  9058. continue;
  9059. }
  9060. }
  9061. }
  9062. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9063. var target = targets_1[_b];
  9064. switch (target) {
  9065. case "uniformBuffer":
  9066. this.disableUniformBuffers = true;
  9067. break;
  9068. case "textureBindingOptimization":
  9069. this.disableTextureBindingOptimization = true;
  9070. break;
  9071. }
  9072. }
  9073. break;
  9074. }
  9075. }
  9076. }
  9077. // GL
  9078. if (!options.disableWebGL2Support) {
  9079. try {
  9080. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9081. if (this._gl) {
  9082. this._webGLVersion = 2.0;
  9083. }
  9084. }
  9085. catch (e) {
  9086. // Do nothing
  9087. }
  9088. }
  9089. if (!this._gl) {
  9090. if (!canvas) {
  9091. throw new Error("The provided canvas is null or undefined.");
  9092. }
  9093. try {
  9094. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9095. }
  9096. catch (e) {
  9097. throw new Error("WebGL not supported");
  9098. }
  9099. }
  9100. if (!this._gl) {
  9101. throw new Error("WebGL not supported");
  9102. }
  9103. this._onCanvasFocus = function () {
  9104. _this.onCanvasFocusObservable.notifyObservers(_this);
  9105. };
  9106. this._onCanvasBlur = function () {
  9107. _this.onCanvasBlurObservable.notifyObservers(_this);
  9108. };
  9109. canvas.addEventListener("focus", this._onCanvasFocus);
  9110. canvas.addEventListener("blur", this._onCanvasBlur);
  9111. this._onBlur = function () {
  9112. if (_this.disablePerformanceMonitorInBackground) {
  9113. _this._performanceMonitor.disable();
  9114. }
  9115. _this._windowIsBackground = true;
  9116. };
  9117. this._onFocus = function () {
  9118. if (_this.disablePerformanceMonitorInBackground) {
  9119. _this._performanceMonitor.enable();
  9120. }
  9121. _this._windowIsBackground = false;
  9122. };
  9123. this._onCanvasPointerOut = function () {
  9124. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9125. };
  9126. window.addEventListener("blur", this._onBlur);
  9127. window.addEventListener("focus", this._onFocus);
  9128. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9129. // Context lost
  9130. if (!this._doNotHandleContextLost) {
  9131. this._onContextLost = function (evt) {
  9132. evt.preventDefault();
  9133. _this._contextWasLost = true;
  9134. BABYLON.Tools.Warn("WebGL context lost.");
  9135. _this.onContextLostObservable.notifyObservers(_this);
  9136. };
  9137. this._onContextRestored = function (evt) {
  9138. // Adding a timeout to avoid race condition at browser level
  9139. setTimeout(function () {
  9140. // Rebuild gl context
  9141. _this._initGLContext();
  9142. // Rebuild effects
  9143. _this._rebuildEffects();
  9144. // Rebuild textures
  9145. _this._rebuildInternalTextures();
  9146. // Rebuild buffers
  9147. _this._rebuildBuffers();
  9148. // Cache
  9149. _this.wipeCaches(true);
  9150. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9151. _this.onContextRestoredObservable.notifyObservers(_this);
  9152. _this._contextWasLost = false;
  9153. }, 0);
  9154. };
  9155. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9156. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9157. }
  9158. }
  9159. else {
  9160. this._gl = canvasOrContext;
  9161. this._renderingCanvas = this._gl.canvas;
  9162. if (this._gl.renderbufferStorageMultisample) {
  9163. this._webGLVersion = 2.0;
  9164. }
  9165. options.stencil = this._gl.getContextAttributes().stencil;
  9166. }
  9167. // Viewport
  9168. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9169. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9170. this.resize();
  9171. this._isStencilEnable = options.stencil ? true : false;
  9172. this._initGLContext();
  9173. if (canvas) {
  9174. // Fullscreen
  9175. this._onFullscreenChange = function () {
  9176. if (document.fullscreen !== undefined) {
  9177. _this.isFullscreen = document.fullscreen;
  9178. }
  9179. else if (document.mozFullScreen !== undefined) {
  9180. _this.isFullscreen = document.mozFullScreen;
  9181. }
  9182. else if (document.webkitIsFullScreen !== undefined) {
  9183. _this.isFullscreen = document.webkitIsFullScreen;
  9184. }
  9185. else if (document.msIsFullScreen !== undefined) {
  9186. _this.isFullscreen = document.msIsFullScreen;
  9187. }
  9188. // Pointer lock
  9189. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9190. canvas.requestPointerLock = canvas.requestPointerLock ||
  9191. canvas.msRequestPointerLock ||
  9192. canvas.mozRequestPointerLock ||
  9193. canvas.webkitRequestPointerLock;
  9194. if (canvas.requestPointerLock) {
  9195. canvas.requestPointerLock();
  9196. }
  9197. }
  9198. };
  9199. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9200. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9201. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9202. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9203. // Pointer lock
  9204. this._onPointerLockChange = function () {
  9205. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9206. document.webkitPointerLockElement === canvas ||
  9207. document.msPointerLockElement === canvas ||
  9208. document.pointerLockElement === canvas);
  9209. };
  9210. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9211. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9212. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9213. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9214. this._onVRDisplayPointerRestricted = function () {
  9215. if (canvas) {
  9216. canvas.requestPointerLock();
  9217. }
  9218. };
  9219. this._onVRDisplayPointerUnrestricted = function () {
  9220. document.exitPointerLock();
  9221. };
  9222. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9223. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9224. }
  9225. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9226. Engine.audioEngine = new BABYLON.AudioEngine();
  9227. }
  9228. // Prepare buffer pointers
  9229. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9230. this._currentBufferPointers[i] = new BufferPointer();
  9231. }
  9232. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9233. // Load WebVR Devices
  9234. if (options.autoEnableWebVR) {
  9235. this.initWebVR();
  9236. }
  9237. // Detect if we are running on a faulty buggy OS.
  9238. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9239. // Detect if we are running on a faulty buggy desktop OS.
  9240. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9241. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9242. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9243. }
  9244. Object.defineProperty(Engine, "LastCreatedEngine", {
  9245. get: function () {
  9246. if (Engine.Instances.length === 0) {
  9247. return null;
  9248. }
  9249. return Engine.Instances[Engine.Instances.length - 1];
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Object.defineProperty(Engine, "LastCreatedScene", {
  9255. get: function () {
  9256. var lastCreatedEngine = Engine.LastCreatedEngine;
  9257. if (!lastCreatedEngine) {
  9258. return null;
  9259. }
  9260. if (lastCreatedEngine.scenes.length === 0) {
  9261. return null;
  9262. }
  9263. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9264. },
  9265. enumerable: true,
  9266. configurable: true
  9267. });
  9268. /**
  9269. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9270. */
  9271. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9272. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9273. var engine = Engine.Instances[engineIndex];
  9274. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9275. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9276. }
  9277. }
  9278. };
  9279. Object.defineProperty(Engine, "NEVER", {
  9280. get: function () {
  9281. return Engine._NEVER;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(Engine, "ALWAYS", {
  9287. get: function () {
  9288. return Engine._ALWAYS;
  9289. },
  9290. enumerable: true,
  9291. configurable: true
  9292. });
  9293. Object.defineProperty(Engine, "LESS", {
  9294. get: function () {
  9295. return Engine._LESS;
  9296. },
  9297. enumerable: true,
  9298. configurable: true
  9299. });
  9300. Object.defineProperty(Engine, "EQUAL", {
  9301. get: function () {
  9302. return Engine._EQUAL;
  9303. },
  9304. enumerable: true,
  9305. configurable: true
  9306. });
  9307. Object.defineProperty(Engine, "LEQUAL", {
  9308. get: function () {
  9309. return Engine._LEQUAL;
  9310. },
  9311. enumerable: true,
  9312. configurable: true
  9313. });
  9314. Object.defineProperty(Engine, "GREATER", {
  9315. get: function () {
  9316. return Engine._GREATER;
  9317. },
  9318. enumerable: true,
  9319. configurable: true
  9320. });
  9321. Object.defineProperty(Engine, "GEQUAL", {
  9322. get: function () {
  9323. return Engine._GEQUAL;
  9324. },
  9325. enumerable: true,
  9326. configurable: true
  9327. });
  9328. Object.defineProperty(Engine, "NOTEQUAL", {
  9329. get: function () {
  9330. return Engine._NOTEQUAL;
  9331. },
  9332. enumerable: true,
  9333. configurable: true
  9334. });
  9335. Object.defineProperty(Engine, "KEEP", {
  9336. get: function () {
  9337. return Engine._KEEP;
  9338. },
  9339. enumerable: true,
  9340. configurable: true
  9341. });
  9342. Object.defineProperty(Engine, "REPLACE", {
  9343. get: function () {
  9344. return Engine._REPLACE;
  9345. },
  9346. enumerable: true,
  9347. configurable: true
  9348. });
  9349. Object.defineProperty(Engine, "INCR", {
  9350. get: function () {
  9351. return Engine._INCR;
  9352. },
  9353. enumerable: true,
  9354. configurable: true
  9355. });
  9356. Object.defineProperty(Engine, "DECR", {
  9357. get: function () {
  9358. return Engine._DECR;
  9359. },
  9360. enumerable: true,
  9361. configurable: true
  9362. });
  9363. Object.defineProperty(Engine, "INVERT", {
  9364. get: function () {
  9365. return Engine._INVERT;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. Object.defineProperty(Engine, "INCR_WRAP", {
  9371. get: function () {
  9372. return Engine._INCR_WRAP;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(Engine, "DECR_WRAP", {
  9378. get: function () {
  9379. return Engine._DECR_WRAP;
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9385. get: function () {
  9386. return Engine._ALPHA_DISABLE;
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9392. get: function () {
  9393. return Engine._ALPHA_ONEONE;
  9394. },
  9395. enumerable: true,
  9396. configurable: true
  9397. });
  9398. Object.defineProperty(Engine, "ALPHA_ADD", {
  9399. get: function () {
  9400. return Engine._ALPHA_ADD;
  9401. },
  9402. enumerable: true,
  9403. configurable: true
  9404. });
  9405. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9406. get: function () {
  9407. return Engine._ALPHA_COMBINE;
  9408. },
  9409. enumerable: true,
  9410. configurable: true
  9411. });
  9412. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9413. get: function () {
  9414. return Engine._ALPHA_SUBTRACT;
  9415. },
  9416. enumerable: true,
  9417. configurable: true
  9418. });
  9419. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9420. get: function () {
  9421. return Engine._ALPHA_MULTIPLY;
  9422. },
  9423. enumerable: true,
  9424. configurable: true
  9425. });
  9426. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9427. get: function () {
  9428. return Engine._ALPHA_MAXIMIZED;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9434. get: function () {
  9435. return Engine._ALPHA_PREMULTIPLIED;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9441. get: function () {
  9442. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9448. get: function () {
  9449. return Engine._ALPHA_INTERPOLATE;
  9450. },
  9451. enumerable: true,
  9452. configurable: true
  9453. });
  9454. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9455. get: function () {
  9456. return Engine._ALPHA_SCREENMODE;
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9462. get: function () {
  9463. return Engine._DELAYLOADSTATE_NONE;
  9464. },
  9465. enumerable: true,
  9466. configurable: true
  9467. });
  9468. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9469. get: function () {
  9470. return Engine._DELAYLOADSTATE_LOADED;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9476. get: function () {
  9477. return Engine._DELAYLOADSTATE_LOADING;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9483. get: function () {
  9484. return Engine._DELAYLOADSTATE_NOTLOADED;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9490. get: function () {
  9491. return Engine._TEXTUREFORMAT_ALPHA;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9497. get: function () {
  9498. return Engine._TEXTUREFORMAT_LUMINANCE;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9504. get: function () {
  9505. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9506. },
  9507. enumerable: true,
  9508. configurable: true
  9509. });
  9510. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9511. get: function () {
  9512. return Engine._TEXTUREFORMAT_RGB;
  9513. },
  9514. enumerable: true,
  9515. configurable: true
  9516. });
  9517. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9518. get: function () {
  9519. return Engine._TEXTUREFORMAT_RGBA;
  9520. },
  9521. enumerable: true,
  9522. configurable: true
  9523. });
  9524. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9525. get: function () {
  9526. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9532. get: function () {
  9533. return Engine._TEXTURETYPE_FLOAT;
  9534. },
  9535. enumerable: true,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9539. get: function () {
  9540. return Engine._TEXTURETYPE_HALF_FLOAT;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9546. get: function () {
  9547. return Engine._SCALEMODE_FLOOR;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9553. get: function () {
  9554. return Engine._SCALEMODE_NEAREST;
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9560. get: function () {
  9561. return Engine._SCALEMODE_CEILING;
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(Engine, "Version", {
  9567. get: function () {
  9568. return "3.2.0-alpha5";
  9569. },
  9570. enumerable: true,
  9571. configurable: true
  9572. });
  9573. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9574. get: function () {
  9575. return this._vrExclusivePointerMode;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9581. get: function () {
  9582. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9588. get: function () {
  9589. return this._webGLVersion < 2 || this.forcePOTTextures;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Engine.prototype, "badOS", {
  9595. get: function () {
  9596. return this._badOS;
  9597. },
  9598. enumerable: true,
  9599. configurable: true
  9600. });
  9601. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9602. get: function () {
  9603. return this._badDesktopOS;
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9609. get: function () {
  9610. return this._performanceMonitor;
  9611. },
  9612. enumerable: true,
  9613. configurable: true
  9614. });
  9615. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9616. get: function () {
  9617. return this._texturesSupported;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9623. get: function () {
  9624. return this._textureFormatInUse;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(Engine.prototype, "currentViewport", {
  9630. get: function () {
  9631. return this._cachedViewport;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9637. // Empty texture
  9638. get: function () {
  9639. if (!this._emptyTexture) {
  9640. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9641. }
  9642. return this._emptyTexture;
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9648. get: function () {
  9649. if (!this._emptyTexture3D) {
  9650. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9651. }
  9652. return this._emptyTexture3D;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9658. get: function () {
  9659. if (!this._emptyCubeTexture) {
  9660. var faceData = new Uint8Array(4);
  9661. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9662. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9663. }
  9664. return this._emptyCubeTexture;
  9665. },
  9666. enumerable: true,
  9667. configurable: true
  9668. });
  9669. Engine.prototype._rebuildInternalTextures = function () {
  9670. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9671. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9672. var internalTexture = currentState_1[_i];
  9673. internalTexture._rebuild();
  9674. }
  9675. };
  9676. Engine.prototype._rebuildEffects = function () {
  9677. for (var key in this._compiledEffects) {
  9678. var effect = this._compiledEffects[key];
  9679. effect._prepareEffect();
  9680. }
  9681. BABYLON.Effect.ResetCache();
  9682. };
  9683. Engine.prototype._rebuildBuffers = function () {
  9684. // Index / Vertex
  9685. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9686. var scene = _a[_i];
  9687. scene.resetCachedMaterial();
  9688. scene._rebuildGeometries();
  9689. scene._rebuildTextures();
  9690. }
  9691. // Uniforms
  9692. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9693. var uniformBuffer = _c[_b];
  9694. uniformBuffer._rebuild();
  9695. }
  9696. };
  9697. Engine.prototype._initGLContext = function () {
  9698. // Caps
  9699. this._caps = new EngineCapabilities();
  9700. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9701. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9702. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9703. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9704. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9705. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9706. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9707. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9708. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9709. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9710. // Infos
  9711. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9712. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9713. if (rendererInfo != null) {
  9714. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9715. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9716. }
  9717. if (!this._glVendor) {
  9718. this._glVendor = "Unknown vendor";
  9719. }
  9720. if (!this._glRenderer) {
  9721. this._glRenderer = "Unknown renderer";
  9722. }
  9723. // Constants
  9724. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9725. if (this._gl.RGBA16F !== 0x881A) {
  9726. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9727. }
  9728. if (this._gl.RGBA32F !== 0x8814) {
  9729. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9730. }
  9731. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9732. this._gl.DEPTH24_STENCIL8 = 35056;
  9733. }
  9734. // Extensions
  9735. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9736. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9737. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9738. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9739. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9740. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9741. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9742. 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');
  9743. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9744. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9745. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9746. this._caps.highPrecisionShaderSupported = true;
  9747. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9748. if (this._caps.timerQuery) {
  9749. if (this._webGLVersion === 1) {
  9750. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9751. }
  9752. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9753. }
  9754. // Checks if some of the format renders first to allow the use of webgl inspector.
  9755. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9756. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9757. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9758. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9759. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9760. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9761. if (this._webGLVersion > 1) {
  9762. this._gl.HALF_FLOAT_OES = 0x140B;
  9763. }
  9764. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9765. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9766. // Draw buffers
  9767. if (this._webGLVersion > 1) {
  9768. this._caps.drawBuffersExtension = true;
  9769. }
  9770. else {
  9771. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9772. if (drawBuffersExtension !== null) {
  9773. this._caps.drawBuffersExtension = true;
  9774. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9775. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9776. for (var i = 0; i < 16; i++) {
  9777. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9778. }
  9779. }
  9780. else {
  9781. this._caps.drawBuffersExtension = false;
  9782. }
  9783. }
  9784. // Depth Texture
  9785. if (this._webGLVersion > 1) {
  9786. this._caps.depthTextureExtension = true;
  9787. }
  9788. else {
  9789. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9790. if (depthTextureExtension != null) {
  9791. this._caps.depthTextureExtension = true;
  9792. }
  9793. }
  9794. // Vertex array object
  9795. if (this._webGLVersion > 1) {
  9796. this._caps.vertexArrayObject = true;
  9797. }
  9798. else {
  9799. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9800. if (vertexArrayObjectExtension != null) {
  9801. this._caps.vertexArrayObject = true;
  9802. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9803. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9804. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9805. }
  9806. else {
  9807. this._caps.vertexArrayObject = false;
  9808. }
  9809. }
  9810. // Instances count
  9811. if (this._webGLVersion > 1) {
  9812. this._caps.instancedArrays = true;
  9813. }
  9814. else {
  9815. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9816. if (instanceExtension != null) {
  9817. this._caps.instancedArrays = true;
  9818. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9819. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9820. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9821. }
  9822. else {
  9823. this._caps.instancedArrays = false;
  9824. }
  9825. }
  9826. // Intelligently add supported compressed formats in order to check for.
  9827. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9828. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9829. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9830. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9831. if (this._caps.astc)
  9832. this.texturesSupported.push('-astc.ktx');
  9833. if (this._caps.s3tc)
  9834. this.texturesSupported.push('-dxt.ktx');
  9835. if (this._caps.pvrtc)
  9836. this.texturesSupported.push('-pvrtc.ktx');
  9837. if (this._caps.etc2)
  9838. this.texturesSupported.push('-etc2.ktx');
  9839. if (this._caps.etc1)
  9840. this.texturesSupported.push('-etc1.ktx');
  9841. if (this._gl.getShaderPrecisionFormat) {
  9842. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9843. if (highp) {
  9844. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9845. }
  9846. }
  9847. // Depth buffer
  9848. this.setDepthBuffer(true);
  9849. this.setDepthFunctionToLessOrEqual();
  9850. this.setDepthWrite(true);
  9851. // Texture maps
  9852. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9853. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9854. this._nextFreeTextureSlots.push(slot);
  9855. }
  9856. };
  9857. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9858. get: function () {
  9859. return this._webGLVersion;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9865. /**
  9866. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9867. */
  9868. get: function () {
  9869. return this._isStencilEnable;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Engine.prototype._prepareWorkingCanvas = function () {
  9875. if (this._workingCanvas) {
  9876. return;
  9877. }
  9878. this._workingCanvas = document.createElement("canvas");
  9879. var context = this._workingCanvas.getContext("2d");
  9880. if (context) {
  9881. this._workingContext = context;
  9882. }
  9883. };
  9884. Engine.prototype.resetTextureCache = function () {
  9885. for (var key in this._boundTexturesCache) {
  9886. var boundTexture = this._boundTexturesCache[key];
  9887. if (boundTexture) {
  9888. this._removeDesignatedSlot(boundTexture);
  9889. }
  9890. this._boundTexturesCache[key] = null;
  9891. }
  9892. this._nextFreeTextureSlots = [];
  9893. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9894. this._nextFreeTextureSlots.push(slot);
  9895. }
  9896. this._currentTextureChannel = -1;
  9897. };
  9898. Engine.prototype.isDeterministicLockStep = function () {
  9899. return this._deterministicLockstep;
  9900. };
  9901. Engine.prototype.getLockstepMaxSteps = function () {
  9902. return this._lockstepMaxSteps;
  9903. };
  9904. Engine.prototype.getGlInfo = function () {
  9905. return {
  9906. vendor: this._glVendor,
  9907. renderer: this._glRenderer,
  9908. version: this._glVersion
  9909. };
  9910. };
  9911. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9912. if (useScreen === void 0) { useScreen = false; }
  9913. var viewport = camera.viewport;
  9914. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9915. };
  9916. Engine.prototype.getRenderWidth = function (useScreen) {
  9917. if (useScreen === void 0) { useScreen = false; }
  9918. if (!useScreen && this._currentRenderTarget) {
  9919. return this._currentRenderTarget.width;
  9920. }
  9921. return this._gl.drawingBufferWidth;
  9922. };
  9923. Engine.prototype.getRenderHeight = function (useScreen) {
  9924. if (useScreen === void 0) { useScreen = false; }
  9925. if (!useScreen && this._currentRenderTarget) {
  9926. return this._currentRenderTarget.height;
  9927. }
  9928. return this._gl.drawingBufferHeight;
  9929. };
  9930. Engine.prototype.getRenderingCanvas = function () {
  9931. return this._renderingCanvas;
  9932. };
  9933. Engine.prototype.getRenderingCanvasClientRect = function () {
  9934. if (!this._renderingCanvas) {
  9935. return null;
  9936. }
  9937. return this._renderingCanvas.getBoundingClientRect();
  9938. };
  9939. Engine.prototype.setHardwareScalingLevel = function (level) {
  9940. this._hardwareScalingLevel = level;
  9941. this.resize();
  9942. };
  9943. Engine.prototype.getHardwareScalingLevel = function () {
  9944. return this._hardwareScalingLevel;
  9945. };
  9946. Engine.prototype.getLoadedTexturesCache = function () {
  9947. return this._internalTexturesCache;
  9948. };
  9949. Engine.prototype.getCaps = function () {
  9950. return this._caps;
  9951. };
  9952. Object.defineProperty(Engine.prototype, "drawCalls", {
  9953. /** The number of draw calls submitted last frame */
  9954. get: function () {
  9955. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9956. return 0;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9962. get: function () {
  9963. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9964. return null;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Engine.prototype.getDepthFunction = function () {
  9970. return this._depthCullingState.depthFunc;
  9971. };
  9972. Engine.prototype.setDepthFunction = function (depthFunc) {
  9973. this._depthCullingState.depthFunc = depthFunc;
  9974. };
  9975. Engine.prototype.setDepthFunctionToGreater = function () {
  9976. this._depthCullingState.depthFunc = this._gl.GREATER;
  9977. };
  9978. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9979. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9980. };
  9981. Engine.prototype.setDepthFunctionToLess = function () {
  9982. this._depthCullingState.depthFunc = this._gl.LESS;
  9983. };
  9984. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9985. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9986. };
  9987. Engine.prototype.getStencilBuffer = function () {
  9988. return this._stencilState.stencilTest;
  9989. };
  9990. Engine.prototype.setStencilBuffer = function (enable) {
  9991. this._stencilState.stencilTest = enable;
  9992. };
  9993. Engine.prototype.getStencilMask = function () {
  9994. return this._stencilState.stencilMask;
  9995. };
  9996. Engine.prototype.setStencilMask = function (mask) {
  9997. this._stencilState.stencilMask = mask;
  9998. };
  9999. Engine.prototype.getStencilFunction = function () {
  10000. return this._stencilState.stencilFunc;
  10001. };
  10002. Engine.prototype.getStencilFunctionReference = function () {
  10003. return this._stencilState.stencilFuncRef;
  10004. };
  10005. Engine.prototype.getStencilFunctionMask = function () {
  10006. return this._stencilState.stencilFuncMask;
  10007. };
  10008. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10009. this._stencilState.stencilFunc = stencilFunc;
  10010. };
  10011. Engine.prototype.setStencilFunctionReference = function (reference) {
  10012. this._stencilState.stencilFuncRef = reference;
  10013. };
  10014. Engine.prototype.setStencilFunctionMask = function (mask) {
  10015. this._stencilState.stencilFuncMask = mask;
  10016. };
  10017. Engine.prototype.getStencilOperationFail = function () {
  10018. return this._stencilState.stencilOpStencilFail;
  10019. };
  10020. Engine.prototype.getStencilOperationDepthFail = function () {
  10021. return this._stencilState.stencilOpDepthFail;
  10022. };
  10023. Engine.prototype.getStencilOperationPass = function () {
  10024. return this._stencilState.stencilOpStencilDepthPass;
  10025. };
  10026. Engine.prototype.setStencilOperationFail = function (operation) {
  10027. this._stencilState.stencilOpStencilFail = operation;
  10028. };
  10029. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10030. this._stencilState.stencilOpDepthFail = operation;
  10031. };
  10032. Engine.prototype.setStencilOperationPass = function (operation) {
  10033. this._stencilState.stencilOpStencilDepthPass = operation;
  10034. };
  10035. Engine.prototype.setDitheringState = function (value) {
  10036. if (value) {
  10037. this._gl.enable(this._gl.DITHER);
  10038. }
  10039. else {
  10040. this._gl.disable(this._gl.DITHER);
  10041. }
  10042. };
  10043. Engine.prototype.setRasterizerState = function (value) {
  10044. if (value) {
  10045. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10046. }
  10047. else {
  10048. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10049. }
  10050. };
  10051. /**
  10052. * stop executing a render loop function and remove it from the execution array
  10053. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10054. */
  10055. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10056. if (!renderFunction) {
  10057. this._activeRenderLoops = [];
  10058. return;
  10059. }
  10060. var index = this._activeRenderLoops.indexOf(renderFunction);
  10061. if (index >= 0) {
  10062. this._activeRenderLoops.splice(index, 1);
  10063. }
  10064. };
  10065. Engine.prototype._renderLoop = function () {
  10066. if (!this._contextWasLost) {
  10067. var shouldRender = true;
  10068. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10069. shouldRender = false;
  10070. }
  10071. if (shouldRender) {
  10072. // Start new frame
  10073. this.beginFrame();
  10074. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10075. var renderFunction = this._activeRenderLoops[index];
  10076. renderFunction();
  10077. }
  10078. // Present
  10079. this.endFrame();
  10080. }
  10081. }
  10082. if (this._activeRenderLoops.length > 0) {
  10083. // Register new frame
  10084. var requester = null;
  10085. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10086. requester = this._vrDisplay;
  10087. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10088. }
  10089. else {
  10090. this._renderingQueueLaunched = false;
  10091. }
  10092. };
  10093. /**
  10094. * Register and execute a render loop. The engine can have more than one render function.
  10095. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10096. * @example
  10097. * engine.runRenderLoop(function () {
  10098. * scene.render()
  10099. * })
  10100. */
  10101. Engine.prototype.runRenderLoop = function (renderFunction) {
  10102. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10103. return;
  10104. }
  10105. this._activeRenderLoops.push(renderFunction);
  10106. if (!this._renderingQueueLaunched) {
  10107. this._renderingQueueLaunched = true;
  10108. this._bindedRenderFunction = this._renderLoop.bind(this);
  10109. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10110. }
  10111. };
  10112. /**
  10113. * Toggle full screen mode.
  10114. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10115. * @param {any} options - an options object to be sent to the requestFullscreen function
  10116. */
  10117. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10118. if (this.isFullscreen) {
  10119. BABYLON.Tools.ExitFullscreen();
  10120. }
  10121. else {
  10122. this._pointerLockRequested = requestPointerLock;
  10123. if (this._renderingCanvas) {
  10124. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10125. }
  10126. }
  10127. };
  10128. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10129. if (stencil === void 0) { stencil = false; }
  10130. this.applyStates();
  10131. var mode = 0;
  10132. if (backBuffer && color) {
  10133. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10134. mode |= this._gl.COLOR_BUFFER_BIT;
  10135. }
  10136. if (depth) {
  10137. this._gl.clearDepth(1.0);
  10138. mode |= this._gl.DEPTH_BUFFER_BIT;
  10139. }
  10140. if (stencil) {
  10141. this._gl.clearStencil(0);
  10142. mode |= this._gl.STENCIL_BUFFER_BIT;
  10143. }
  10144. this._gl.clear(mode);
  10145. };
  10146. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10147. var gl = this._gl;
  10148. // Save state
  10149. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10150. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10151. // Change state
  10152. gl.enable(gl.SCISSOR_TEST);
  10153. gl.scissor(x, y, width, height);
  10154. // Clear
  10155. this.clear(clearColor, true, true, true);
  10156. // Restore state
  10157. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10158. if (curScissor === true) {
  10159. gl.enable(gl.SCISSOR_TEST);
  10160. }
  10161. else {
  10162. gl.disable(gl.SCISSOR_TEST);
  10163. }
  10164. };
  10165. /**
  10166. * Set the WebGL's viewport
  10167. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10168. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10169. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10170. */
  10171. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10172. var width = requiredWidth || this.getRenderWidth();
  10173. var height = requiredHeight || this.getRenderHeight();
  10174. var x = viewport.x || 0;
  10175. var y = viewport.y || 0;
  10176. this._cachedViewport = viewport;
  10177. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10178. };
  10179. /**
  10180. * Directly set the WebGL Viewport
  10181. * The x, y, width & height are directly passed to the WebGL call
  10182. * @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.
  10183. */
  10184. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10185. var currentViewport = this._cachedViewport;
  10186. this._cachedViewport = null;
  10187. this._gl.viewport(x, y, width, height);
  10188. return currentViewport;
  10189. };
  10190. Engine.prototype.beginFrame = function () {
  10191. this.onBeginFrameObservable.notifyObservers(this);
  10192. this._measureFps();
  10193. };
  10194. Engine.prototype.endFrame = function () {
  10195. //force a flush in case we are using a bad OS.
  10196. if (this._badOS) {
  10197. this.flushFramebuffer();
  10198. }
  10199. //submit frame to the vr device, if enabled
  10200. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10201. // TODO: We should only submit the frame if we read frameData successfully.
  10202. this._vrDisplay.submitFrame();
  10203. }
  10204. this.onEndFrameObservable.notifyObservers(this);
  10205. };
  10206. /**
  10207. * resize the view according to the canvas' size.
  10208. * @example
  10209. * window.addEventListener("resize", function () {
  10210. * engine.resize();
  10211. * });
  10212. */
  10213. Engine.prototype.resize = function () {
  10214. // We're not resizing the size of the canvas while in VR mode & presenting
  10215. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10216. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10217. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10218. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10219. }
  10220. };
  10221. /**
  10222. * force a specific size of the canvas
  10223. * @param {number} width - the new canvas' width
  10224. * @param {number} height - the new canvas' height
  10225. */
  10226. Engine.prototype.setSize = function (width, height) {
  10227. if (!this._renderingCanvas) {
  10228. return;
  10229. }
  10230. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10231. return;
  10232. }
  10233. this._renderingCanvas.width = width;
  10234. this._renderingCanvas.height = height;
  10235. for (var index = 0; index < this.scenes.length; index++) {
  10236. var scene = this.scenes[index];
  10237. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10238. var cam = scene.cameras[camIndex];
  10239. cam._currentRenderId = 0;
  10240. }
  10241. }
  10242. if (this.onResizeObservable.hasObservers) {
  10243. this.onResizeObservable.notifyObservers(this);
  10244. }
  10245. };
  10246. // WebVR functions
  10247. Engine.prototype.isVRDevicePresent = function () {
  10248. return !!this._vrDisplay;
  10249. };
  10250. Engine.prototype.getVRDevice = function () {
  10251. return this._vrDisplay;
  10252. };
  10253. Engine.prototype.initWebVR = function () {
  10254. var _this = this;
  10255. var notifyObservers = function () {
  10256. var eventArgs = {
  10257. vrDisplay: _this._vrDisplay,
  10258. vrSupported: _this._vrSupported
  10259. };
  10260. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10261. };
  10262. if (!this._onVrDisplayConnect) {
  10263. this._onVrDisplayConnect = function (event) {
  10264. _this._vrDisplay = event.display;
  10265. notifyObservers();
  10266. };
  10267. this._onVrDisplayDisconnect = function () {
  10268. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10269. _this._vrDisplay = undefined;
  10270. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10271. notifyObservers();
  10272. };
  10273. this._onVrDisplayPresentChange = function () {
  10274. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10275. };
  10276. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10277. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10278. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10279. }
  10280. this._getVRDisplays(notifyObservers);
  10281. return this.onVRDisplayChangedObservable;
  10282. };
  10283. Engine.prototype.enableVR = function () {
  10284. var _this = this;
  10285. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10286. var onResolved = function () {
  10287. _this.onVRRequestPresentComplete.notifyObservers(true);
  10288. _this._onVRFullScreenTriggered();
  10289. };
  10290. var onRejected = function () {
  10291. _this.onVRRequestPresentComplete.notifyObservers(false);
  10292. };
  10293. this.onVRRequestPresentStart.notifyObservers(this);
  10294. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10295. }
  10296. };
  10297. Engine.prototype.disableVR = function () {
  10298. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10299. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10300. }
  10301. };
  10302. Engine.prototype._getVRDisplays = function (callback) {
  10303. var _this = this;
  10304. var getWebVRDevices = function (devices) {
  10305. _this._vrSupported = true;
  10306. // note that devices may actually be an empty array. This is fine;
  10307. // we expect this._vrDisplay to be undefined in this case.
  10308. return _this._vrDisplay = devices[0];
  10309. };
  10310. if (navigator.getVRDisplays) {
  10311. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10312. // TODO: System CANNOT support WebVR, despite API presence.
  10313. _this._vrSupported = false;
  10314. callback();
  10315. });
  10316. }
  10317. else {
  10318. // TODO: Browser does not support WebVR
  10319. this._vrDisplay = undefined;
  10320. this._vrSupported = false;
  10321. callback();
  10322. }
  10323. };
  10324. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10325. if (this._currentRenderTarget) {
  10326. this.unBindFramebuffer(this._currentRenderTarget);
  10327. }
  10328. this._currentRenderTarget = texture;
  10329. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10330. var gl = this._gl;
  10331. if (texture.isCube) {
  10332. if (faceIndex === undefined) {
  10333. faceIndex = 0;
  10334. }
  10335. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10336. }
  10337. if (this._cachedViewport && !forceFullscreenViewport) {
  10338. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10339. }
  10340. else {
  10341. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10342. }
  10343. this.wipeCaches();
  10344. };
  10345. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10346. if (this._currentFramebuffer !== framebuffer) {
  10347. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10348. this._currentFramebuffer = framebuffer;
  10349. }
  10350. };
  10351. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10352. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10353. this._currentRenderTarget = null;
  10354. // If MSAA, we need to bitblt back to main texture
  10355. var gl = this._gl;
  10356. if (texture._MSAAFramebuffer) {
  10357. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10358. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10359. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10360. }
  10361. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10362. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10363. gl.generateMipmap(gl.TEXTURE_2D);
  10364. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10365. }
  10366. if (onBeforeUnbind) {
  10367. if (texture._MSAAFramebuffer) {
  10368. // Bind the correct framebuffer
  10369. this.bindUnboundFramebuffer(texture._framebuffer);
  10370. }
  10371. onBeforeUnbind();
  10372. }
  10373. this.bindUnboundFramebuffer(null);
  10374. };
  10375. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10376. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10377. this._currentRenderTarget = null;
  10378. // If MSAA, we need to bitblt back to main texture
  10379. var gl = this._gl;
  10380. if (textures[0]._MSAAFramebuffer) {
  10381. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10382. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10383. var attachments = textures[0]._attachments;
  10384. if (!attachments) {
  10385. attachments = new Array(textures.length);
  10386. textures[0]._attachments = attachments;
  10387. }
  10388. for (var i = 0; i < textures.length; i++) {
  10389. var texture = textures[i];
  10390. for (var j = 0; j < attachments.length; j++) {
  10391. attachments[j] = gl.NONE;
  10392. }
  10393. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10394. gl.readBuffer(attachments[i]);
  10395. gl.drawBuffers(attachments);
  10396. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10397. }
  10398. for (var i = 0; i < attachments.length; i++) {
  10399. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10400. }
  10401. gl.drawBuffers(attachments);
  10402. }
  10403. for (var i = 0; i < textures.length; i++) {
  10404. var texture = textures[i];
  10405. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10406. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10407. gl.generateMipmap(gl.TEXTURE_2D);
  10408. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10409. }
  10410. }
  10411. if (onBeforeUnbind) {
  10412. if (textures[0]._MSAAFramebuffer) {
  10413. // Bind the correct framebuffer
  10414. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10415. }
  10416. onBeforeUnbind();
  10417. }
  10418. this.bindUnboundFramebuffer(null);
  10419. };
  10420. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10421. if (texture.generateMipMaps) {
  10422. var gl = this._gl;
  10423. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10424. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10425. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10426. }
  10427. };
  10428. Engine.prototype.flushFramebuffer = function () {
  10429. this._gl.flush();
  10430. };
  10431. Engine.prototype.restoreDefaultFramebuffer = function () {
  10432. if (this._currentRenderTarget) {
  10433. this.unBindFramebuffer(this._currentRenderTarget);
  10434. }
  10435. else {
  10436. this.bindUnboundFramebuffer(null);
  10437. }
  10438. if (this._cachedViewport) {
  10439. this.setViewport(this._cachedViewport);
  10440. }
  10441. this.wipeCaches();
  10442. };
  10443. // UBOs
  10444. Engine.prototype.createUniformBuffer = function (elements) {
  10445. var ubo = this._gl.createBuffer();
  10446. if (!ubo) {
  10447. throw new Error("Unable to create uniform buffer");
  10448. }
  10449. this.bindUniformBuffer(ubo);
  10450. if (elements instanceof Float32Array) {
  10451. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10452. }
  10453. else {
  10454. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10455. }
  10456. this.bindUniformBuffer(null);
  10457. ubo.references = 1;
  10458. return ubo;
  10459. };
  10460. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10461. var ubo = this._gl.createBuffer();
  10462. if (!ubo) {
  10463. throw new Error("Unable to create dynamic uniform buffer");
  10464. }
  10465. this.bindUniformBuffer(ubo);
  10466. if (elements instanceof Float32Array) {
  10467. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10468. }
  10469. else {
  10470. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10471. }
  10472. this.bindUniformBuffer(null);
  10473. ubo.references = 1;
  10474. return ubo;
  10475. };
  10476. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10477. this.bindUniformBuffer(uniformBuffer);
  10478. if (offset === undefined) {
  10479. offset = 0;
  10480. }
  10481. if (count === undefined) {
  10482. if (elements instanceof Float32Array) {
  10483. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10484. }
  10485. else {
  10486. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10487. }
  10488. }
  10489. else {
  10490. if (elements instanceof Float32Array) {
  10491. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10492. }
  10493. else {
  10494. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10495. }
  10496. }
  10497. this.bindUniformBuffer(null);
  10498. };
  10499. // VBOs
  10500. Engine.prototype._resetVertexBufferBinding = function () {
  10501. this.bindArrayBuffer(null);
  10502. this._cachedVertexBuffers = null;
  10503. };
  10504. Engine.prototype.createVertexBuffer = function (vertices) {
  10505. var vbo = this._gl.createBuffer();
  10506. if (!vbo) {
  10507. throw new Error("Unable to create vertex buffer");
  10508. }
  10509. this.bindArrayBuffer(vbo);
  10510. if (vertices instanceof Float32Array) {
  10511. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10512. }
  10513. else {
  10514. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10515. }
  10516. this._resetVertexBufferBinding();
  10517. vbo.references = 1;
  10518. return vbo;
  10519. };
  10520. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10521. var vbo = this._gl.createBuffer();
  10522. if (!vbo) {
  10523. throw new Error("Unable to create dynamic vertex buffer");
  10524. }
  10525. this.bindArrayBuffer(vbo);
  10526. if (vertices instanceof Float32Array) {
  10527. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10528. }
  10529. else {
  10530. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10531. }
  10532. this._resetVertexBufferBinding();
  10533. vbo.references = 1;
  10534. return vbo;
  10535. };
  10536. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10537. if (offset === void 0) { offset = 0; }
  10538. // Force cache update
  10539. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10540. this.bindIndexBuffer(indexBuffer);
  10541. var arrayBuffer;
  10542. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10543. arrayBuffer = indices;
  10544. }
  10545. else {
  10546. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10547. }
  10548. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10549. this._resetIndexBufferBinding();
  10550. };
  10551. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10552. this.bindArrayBuffer(vertexBuffer);
  10553. if (offset === undefined) {
  10554. offset = 0;
  10555. }
  10556. if (count === undefined) {
  10557. if (vertices instanceof Float32Array) {
  10558. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10559. }
  10560. else {
  10561. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10562. }
  10563. }
  10564. else {
  10565. if (vertices instanceof Float32Array) {
  10566. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10567. }
  10568. else {
  10569. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10570. }
  10571. }
  10572. this._resetVertexBufferBinding();
  10573. };
  10574. Engine.prototype._resetIndexBufferBinding = function () {
  10575. this.bindIndexBuffer(null);
  10576. this._cachedIndexBuffer = null;
  10577. };
  10578. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10579. var vbo = this._gl.createBuffer();
  10580. if (!vbo) {
  10581. throw new Error("Unable to create index buffer");
  10582. }
  10583. this.bindIndexBuffer(vbo);
  10584. // Check for 32 bits indices
  10585. var arrayBuffer;
  10586. var need32Bits = false;
  10587. if (indices instanceof Uint16Array) {
  10588. arrayBuffer = indices;
  10589. }
  10590. else {
  10591. //check 32 bit support
  10592. if (this._caps.uintIndices) {
  10593. if (indices instanceof Uint32Array) {
  10594. arrayBuffer = indices;
  10595. need32Bits = true;
  10596. }
  10597. else {
  10598. //number[] or Int32Array, check if 32 bit is necessary
  10599. for (var index = 0; index < indices.length; index++) {
  10600. if (indices[index] > 65535) {
  10601. need32Bits = true;
  10602. break;
  10603. }
  10604. }
  10605. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10606. }
  10607. }
  10608. else {
  10609. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10610. arrayBuffer = new Uint16Array(indices);
  10611. }
  10612. }
  10613. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10614. this._resetIndexBufferBinding();
  10615. vbo.references = 1;
  10616. vbo.is32Bits = need32Bits;
  10617. return vbo;
  10618. };
  10619. Engine.prototype.bindArrayBuffer = function (buffer) {
  10620. if (!this._vaoRecordInProgress) {
  10621. this._unbindVertexArrayObject();
  10622. }
  10623. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10624. };
  10625. Engine.prototype.bindUniformBuffer = function (buffer) {
  10626. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10627. };
  10628. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10629. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10630. };
  10631. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10632. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10633. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10634. };
  10635. ;
  10636. Engine.prototype.bindIndexBuffer = function (buffer) {
  10637. if (!this._vaoRecordInProgress) {
  10638. this._unbindVertexArrayObject();
  10639. }
  10640. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10641. };
  10642. Engine.prototype.bindBuffer = function (buffer, target) {
  10643. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10644. this._gl.bindBuffer(target, buffer);
  10645. this._currentBoundBuffer[target] = buffer;
  10646. }
  10647. };
  10648. Engine.prototype.updateArrayBuffer = function (data) {
  10649. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10650. };
  10651. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10652. var pointer = this._currentBufferPointers[indx];
  10653. var changed = false;
  10654. if (!pointer.active) {
  10655. changed = true;
  10656. pointer.active = true;
  10657. pointer.index = indx;
  10658. pointer.size = size;
  10659. pointer.type = type;
  10660. pointer.normalized = normalized;
  10661. pointer.stride = stride;
  10662. pointer.offset = offset;
  10663. pointer.buffer = buffer;
  10664. }
  10665. else {
  10666. if (pointer.buffer !== buffer) {
  10667. pointer.buffer = buffer;
  10668. changed = true;
  10669. }
  10670. if (pointer.size !== size) {
  10671. pointer.size = size;
  10672. changed = true;
  10673. }
  10674. if (pointer.type !== type) {
  10675. pointer.type = type;
  10676. changed = true;
  10677. }
  10678. if (pointer.normalized !== normalized) {
  10679. pointer.normalized = normalized;
  10680. changed = true;
  10681. }
  10682. if (pointer.stride !== stride) {
  10683. pointer.stride = stride;
  10684. changed = true;
  10685. }
  10686. if (pointer.offset !== offset) {
  10687. pointer.offset = offset;
  10688. changed = true;
  10689. }
  10690. }
  10691. if (changed || this._vaoRecordInProgress) {
  10692. this.bindArrayBuffer(buffer);
  10693. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10694. }
  10695. };
  10696. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10697. if (indexBuffer == null) {
  10698. return;
  10699. }
  10700. if (this._cachedIndexBuffer !== indexBuffer) {
  10701. this._cachedIndexBuffer = indexBuffer;
  10702. this.bindIndexBuffer(indexBuffer);
  10703. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10704. }
  10705. };
  10706. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10707. var attributes = effect.getAttributesNames();
  10708. if (!this._vaoRecordInProgress) {
  10709. this._unbindVertexArrayObject();
  10710. }
  10711. this.unbindAllAttributes();
  10712. for (var index = 0; index < attributes.length; index++) {
  10713. var order = effect.getAttributeLocation(index);
  10714. if (order >= 0) {
  10715. var vertexBuffer = vertexBuffers[attributes[index]];
  10716. if (!vertexBuffer) {
  10717. continue;
  10718. }
  10719. this._gl.enableVertexAttribArray(order);
  10720. if (!this._vaoRecordInProgress) {
  10721. this._vertexAttribArraysEnabled[order] = true;
  10722. }
  10723. var buffer = vertexBuffer.getBuffer();
  10724. if (buffer) {
  10725. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10726. if (vertexBuffer.getIsInstanced()) {
  10727. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10728. if (!this._vaoRecordInProgress) {
  10729. this._currentInstanceLocations.push(order);
  10730. this._currentInstanceBuffers.push(buffer);
  10731. }
  10732. }
  10733. }
  10734. }
  10735. }
  10736. };
  10737. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10738. var vao = this._gl.createVertexArray();
  10739. this._vaoRecordInProgress = true;
  10740. this._gl.bindVertexArray(vao);
  10741. this._mustWipeVertexAttributes = true;
  10742. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10743. this.bindIndexBuffer(indexBuffer);
  10744. this._vaoRecordInProgress = false;
  10745. this._gl.bindVertexArray(null);
  10746. return vao;
  10747. };
  10748. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10749. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10750. this._cachedVertexArrayObject = vertexArrayObject;
  10751. this._gl.bindVertexArray(vertexArrayObject);
  10752. this._cachedVertexBuffers = null;
  10753. this._cachedIndexBuffer = null;
  10754. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10755. this._mustWipeVertexAttributes = true;
  10756. }
  10757. };
  10758. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10759. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10760. this._cachedVertexBuffers = vertexBuffer;
  10761. this._cachedEffectForVertexBuffers = effect;
  10762. var attributesCount = effect.getAttributesCount();
  10763. this._unbindVertexArrayObject();
  10764. this.unbindAllAttributes();
  10765. var offset = 0;
  10766. for (var index = 0; index < attributesCount; index++) {
  10767. if (index < vertexDeclaration.length) {
  10768. var order = effect.getAttributeLocation(index);
  10769. if (order >= 0) {
  10770. this._gl.enableVertexAttribArray(order);
  10771. this._vertexAttribArraysEnabled[order] = true;
  10772. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10773. }
  10774. offset += vertexDeclaration[index] * 4;
  10775. }
  10776. }
  10777. }
  10778. this._bindIndexBufferWithCache(indexBuffer);
  10779. };
  10780. Engine.prototype._unbindVertexArrayObject = function () {
  10781. if (!this._cachedVertexArrayObject) {
  10782. return;
  10783. }
  10784. this._cachedVertexArrayObject = null;
  10785. this._gl.bindVertexArray(null);
  10786. };
  10787. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10788. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10789. this._cachedVertexBuffers = vertexBuffers;
  10790. this._cachedEffectForVertexBuffers = effect;
  10791. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10792. }
  10793. this._bindIndexBufferWithCache(indexBuffer);
  10794. };
  10795. Engine.prototype.unbindInstanceAttributes = function () {
  10796. var boundBuffer;
  10797. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10798. var instancesBuffer = this._currentInstanceBuffers[i];
  10799. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10800. boundBuffer = instancesBuffer;
  10801. this.bindArrayBuffer(instancesBuffer);
  10802. }
  10803. var offsetLocation = this._currentInstanceLocations[i];
  10804. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10805. }
  10806. this._currentInstanceBuffers.length = 0;
  10807. this._currentInstanceLocations.length = 0;
  10808. };
  10809. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10810. this._gl.deleteVertexArray(vao);
  10811. };
  10812. Engine.prototype._releaseBuffer = function (buffer) {
  10813. buffer.references--;
  10814. if (buffer.references === 0) {
  10815. this._gl.deleteBuffer(buffer);
  10816. return true;
  10817. }
  10818. return false;
  10819. };
  10820. Engine.prototype.createInstancesBuffer = function (capacity) {
  10821. var buffer = this._gl.createBuffer();
  10822. if (!buffer) {
  10823. throw new Error("Unable to create instance buffer");
  10824. }
  10825. buffer.capacity = capacity;
  10826. this.bindArrayBuffer(buffer);
  10827. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10828. return buffer;
  10829. };
  10830. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10831. this._gl.deleteBuffer(buffer);
  10832. };
  10833. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10834. this.bindArrayBuffer(instancesBuffer);
  10835. if (data) {
  10836. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10837. }
  10838. if (offsetLocations[0].index !== undefined) {
  10839. var stride = 0;
  10840. for (var i = 0; i < offsetLocations.length; i++) {
  10841. var ai = offsetLocations[i];
  10842. stride += ai.attributeSize * 4;
  10843. }
  10844. for (var i = 0; i < offsetLocations.length; i++) {
  10845. var ai = offsetLocations[i];
  10846. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10847. this._gl.enableVertexAttribArray(ai.index);
  10848. this._vertexAttribArraysEnabled[ai.index] = true;
  10849. }
  10850. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10851. this._gl.vertexAttribDivisor(ai.index, 1);
  10852. this._currentInstanceLocations.push(ai.index);
  10853. this._currentInstanceBuffers.push(instancesBuffer);
  10854. }
  10855. }
  10856. else {
  10857. for (var index = 0; index < 4; index++) {
  10858. var offsetLocation = offsetLocations[index];
  10859. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10860. this._gl.enableVertexAttribArray(offsetLocation);
  10861. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10862. }
  10863. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10864. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10865. this._currentInstanceLocations.push(offsetLocation);
  10866. this._currentInstanceBuffers.push(instancesBuffer);
  10867. }
  10868. }
  10869. };
  10870. Engine.prototype.applyStates = function () {
  10871. this._depthCullingState.apply(this._gl);
  10872. this._stencilState.apply(this._gl);
  10873. this._alphaState.apply(this._gl);
  10874. };
  10875. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10876. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10877. };
  10878. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10879. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10880. };
  10881. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10882. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10883. };
  10884. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10885. // Apply states
  10886. this.applyStates();
  10887. this._drawCalls.addCount(1, false);
  10888. // Render
  10889. var drawMode = this.DrawMode(fillMode);
  10890. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10891. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10892. if (instancesCount) {
  10893. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10894. }
  10895. else {
  10896. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10897. }
  10898. };
  10899. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10900. // Apply states
  10901. this.applyStates();
  10902. this._drawCalls.addCount(1, false);
  10903. var drawMode = this.DrawMode(fillMode);
  10904. if (instancesCount) {
  10905. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10906. }
  10907. else {
  10908. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10909. }
  10910. };
  10911. Engine.prototype.DrawMode = function (fillMode) {
  10912. switch (fillMode) {
  10913. // Triangle views
  10914. case BABYLON.Material.TriangleFillMode:
  10915. return this._gl.TRIANGLES;
  10916. case BABYLON.Material.PointFillMode:
  10917. return this._gl.POINTS;
  10918. case BABYLON.Material.WireFrameFillMode:
  10919. return this._gl.LINES;
  10920. // Draw modes
  10921. case BABYLON.Material.PointListDrawMode:
  10922. return this._gl.POINTS;
  10923. case BABYLON.Material.LineListDrawMode:
  10924. return this._gl.LINES;
  10925. case BABYLON.Material.LineLoopDrawMode:
  10926. return this._gl.LINE_LOOP;
  10927. case BABYLON.Material.LineStripDrawMode:
  10928. return this._gl.LINE_STRIP;
  10929. case BABYLON.Material.TriangleStripDrawMode:
  10930. return this._gl.TRIANGLE_STRIP;
  10931. case BABYLON.Material.TriangleFanDrawMode:
  10932. return this._gl.TRIANGLE_FAN;
  10933. default:
  10934. return this._gl.TRIANGLES;
  10935. }
  10936. };
  10937. // Shaders
  10938. Engine.prototype._releaseEffect = function (effect) {
  10939. if (this._compiledEffects[effect._key]) {
  10940. delete this._compiledEffects[effect._key];
  10941. this._deleteProgram(effect.getProgram());
  10942. }
  10943. };
  10944. Engine.prototype._deleteProgram = function (program) {
  10945. if (program) {
  10946. program.__SPECTOR_rebuildProgram = null;
  10947. if (program.transformFeedback) {
  10948. this.deleteTransformFeedback(program.transformFeedback);
  10949. program.transformFeedback = null;
  10950. }
  10951. this._gl.deleteProgram(program);
  10952. }
  10953. };
  10954. /**
  10955. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10956. * @param samplers An array of string used to represent textures
  10957. */
  10958. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10959. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10960. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10961. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10962. if (this._compiledEffects[name]) {
  10963. var compiledEffect = this._compiledEffects[name];
  10964. if (onCompiled && compiledEffect.isReady()) {
  10965. onCompiled(compiledEffect);
  10966. }
  10967. return compiledEffect;
  10968. }
  10969. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10970. effect._key = name;
  10971. this._compiledEffects[name] = effect;
  10972. return effect;
  10973. };
  10974. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10975. if (uniformsNames === void 0) { uniformsNames = []; }
  10976. if (samplers === void 0) { samplers = []; }
  10977. if (defines === void 0) { defines = ""; }
  10978. return this.createEffect({
  10979. vertex: "particles",
  10980. fragmentElement: fragmentName
  10981. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10982. };
  10983. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10984. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10985. context = context || this._gl;
  10986. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10987. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10988. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10989. };
  10990. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10991. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10992. context = context || this._gl;
  10993. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10994. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10995. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10996. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10997. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10998. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10999. return program;
  11000. };
  11001. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11002. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11003. var shaderProgram = context.createProgram();
  11004. if (!shaderProgram) {
  11005. throw new Error("Unable to create program");
  11006. }
  11007. context.attachShader(shaderProgram, vertexShader);
  11008. context.attachShader(shaderProgram, fragmentShader);
  11009. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11010. var transformFeedback = this.createTransformFeedback();
  11011. this.bindTransformFeedback(transformFeedback);
  11012. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11013. shaderProgram.transformFeedback = transformFeedback;
  11014. }
  11015. context.linkProgram(shaderProgram);
  11016. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11017. this.bindTransformFeedback(null);
  11018. }
  11019. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11020. if (!linked) {
  11021. context.validateProgram(shaderProgram);
  11022. var error = context.getProgramInfoLog(shaderProgram);
  11023. if (error) {
  11024. throw new Error(error);
  11025. }
  11026. }
  11027. context.deleteShader(vertexShader);
  11028. context.deleteShader(fragmentShader);
  11029. return shaderProgram;
  11030. };
  11031. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11032. var results = new Array();
  11033. for (var index = 0; index < uniformsNames.length; index++) {
  11034. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11035. }
  11036. return results;
  11037. };
  11038. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11039. var results = [];
  11040. for (var index = 0; index < attributesNames.length; index++) {
  11041. try {
  11042. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11043. }
  11044. catch (e) {
  11045. results.push(-1);
  11046. }
  11047. }
  11048. return results;
  11049. };
  11050. Engine.prototype.enableEffect = function (effect) {
  11051. if (!effect) {
  11052. return;
  11053. }
  11054. // Use program
  11055. this.bindSamplers(effect);
  11056. this._currentEffect = effect;
  11057. if (effect.onBind) {
  11058. effect.onBind(effect);
  11059. }
  11060. effect.onBindObservable.notifyObservers(effect);
  11061. };
  11062. Engine.prototype.setIntArray = function (uniform, array) {
  11063. if (!uniform)
  11064. return;
  11065. this._gl.uniform1iv(uniform, array);
  11066. };
  11067. Engine.prototype.setIntArray2 = function (uniform, array) {
  11068. if (!uniform || array.length % 2 !== 0)
  11069. return;
  11070. this._gl.uniform2iv(uniform, array);
  11071. };
  11072. Engine.prototype.setIntArray3 = function (uniform, array) {
  11073. if (!uniform || array.length % 3 !== 0)
  11074. return;
  11075. this._gl.uniform3iv(uniform, array);
  11076. };
  11077. Engine.prototype.setIntArray4 = function (uniform, array) {
  11078. if (!uniform || array.length % 4 !== 0)
  11079. return;
  11080. this._gl.uniform4iv(uniform, array);
  11081. };
  11082. Engine.prototype.setFloatArray = function (uniform, array) {
  11083. if (!uniform)
  11084. return;
  11085. this._gl.uniform1fv(uniform, array);
  11086. };
  11087. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11088. if (!uniform || array.length % 2 !== 0)
  11089. return;
  11090. this._gl.uniform2fv(uniform, array);
  11091. };
  11092. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11093. if (!uniform || array.length % 3 !== 0)
  11094. return;
  11095. this._gl.uniform3fv(uniform, array);
  11096. };
  11097. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11098. if (!uniform || array.length % 4 !== 0)
  11099. return;
  11100. this._gl.uniform4fv(uniform, array);
  11101. };
  11102. Engine.prototype.setArray = function (uniform, array) {
  11103. if (!uniform)
  11104. return;
  11105. this._gl.uniform1fv(uniform, array);
  11106. };
  11107. Engine.prototype.setArray2 = function (uniform, array) {
  11108. if (!uniform || array.length % 2 !== 0)
  11109. return;
  11110. this._gl.uniform2fv(uniform, array);
  11111. };
  11112. Engine.prototype.setArray3 = function (uniform, array) {
  11113. if (!uniform || array.length % 3 !== 0)
  11114. return;
  11115. this._gl.uniform3fv(uniform, array);
  11116. };
  11117. Engine.prototype.setArray4 = function (uniform, array) {
  11118. if (!uniform || array.length % 4 !== 0)
  11119. return;
  11120. this._gl.uniform4fv(uniform, array);
  11121. };
  11122. Engine.prototype.setMatrices = function (uniform, matrices) {
  11123. if (!uniform)
  11124. return;
  11125. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11126. };
  11127. Engine.prototype.setMatrix = function (uniform, matrix) {
  11128. if (!uniform)
  11129. return;
  11130. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11131. };
  11132. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11133. if (!uniform)
  11134. return;
  11135. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11136. };
  11137. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11138. if (!uniform)
  11139. return;
  11140. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11141. };
  11142. Engine.prototype.setInt = function (uniform, value) {
  11143. if (!uniform)
  11144. return;
  11145. this._gl.uniform1i(uniform, value);
  11146. };
  11147. Engine.prototype.setFloat = function (uniform, value) {
  11148. if (!uniform)
  11149. return;
  11150. this._gl.uniform1f(uniform, value);
  11151. };
  11152. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11153. if (!uniform)
  11154. return;
  11155. this._gl.uniform2f(uniform, x, y);
  11156. };
  11157. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11158. if (!uniform)
  11159. return;
  11160. this._gl.uniform3f(uniform, x, y, z);
  11161. };
  11162. Engine.prototype.setBool = function (uniform, bool) {
  11163. if (!uniform)
  11164. return;
  11165. this._gl.uniform1i(uniform, bool);
  11166. };
  11167. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11168. if (!uniform)
  11169. return;
  11170. this._gl.uniform4f(uniform, x, y, z, w);
  11171. };
  11172. Engine.prototype.setColor3 = function (uniform, color3) {
  11173. if (!uniform)
  11174. return;
  11175. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11176. };
  11177. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11178. if (!uniform)
  11179. return;
  11180. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11181. };
  11182. // States
  11183. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11184. if (zOffset === void 0) { zOffset = 0; }
  11185. if (reverseSide === void 0) { reverseSide = false; }
  11186. // Culling
  11187. if (this._depthCullingState.cull !== culling || force) {
  11188. this._depthCullingState.cull = culling;
  11189. }
  11190. // Cull face
  11191. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11192. if (this._depthCullingState.cullFace !== cullFace || force) {
  11193. this._depthCullingState.cullFace = cullFace;
  11194. }
  11195. // Z offset
  11196. this.setZOffset(zOffset);
  11197. // Front face
  11198. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11199. if (this._depthCullingState.frontFace !== frontFace || force) {
  11200. this._depthCullingState.frontFace = frontFace;
  11201. }
  11202. };
  11203. Engine.prototype.setZOffset = function (value) {
  11204. this._depthCullingState.zOffset = value;
  11205. };
  11206. Engine.prototype.getZOffset = function () {
  11207. return this._depthCullingState.zOffset;
  11208. };
  11209. Engine.prototype.setDepthBuffer = function (enable) {
  11210. this._depthCullingState.depthTest = enable;
  11211. };
  11212. Engine.prototype.getDepthWrite = function () {
  11213. return this._depthCullingState.depthMask;
  11214. };
  11215. Engine.prototype.setDepthWrite = function (enable) {
  11216. this._depthCullingState.depthMask = enable;
  11217. };
  11218. Engine.prototype.setColorWrite = function (enable) {
  11219. this._gl.colorMask(enable, enable, enable, enable);
  11220. this._colorWrite = enable;
  11221. };
  11222. Engine.prototype.getColorWrite = function () {
  11223. return this._colorWrite;
  11224. };
  11225. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11226. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11227. };
  11228. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11229. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11230. if (this._alphaMode === mode) {
  11231. return;
  11232. }
  11233. switch (mode) {
  11234. case Engine.ALPHA_DISABLE:
  11235. this._alphaState.alphaBlend = false;
  11236. break;
  11237. case Engine.ALPHA_PREMULTIPLIED:
  11238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11239. this._alphaState.alphaBlend = true;
  11240. break;
  11241. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11243. this._alphaState.alphaBlend = true;
  11244. break;
  11245. case Engine.ALPHA_COMBINE:
  11246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11247. this._alphaState.alphaBlend = true;
  11248. break;
  11249. case Engine.ALPHA_ONEONE:
  11250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11251. this._alphaState.alphaBlend = true;
  11252. break;
  11253. case Engine.ALPHA_ADD:
  11254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11255. this._alphaState.alphaBlend = true;
  11256. break;
  11257. case Engine.ALPHA_SUBTRACT:
  11258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11259. this._alphaState.alphaBlend = true;
  11260. break;
  11261. case Engine.ALPHA_MULTIPLY:
  11262. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11263. this._alphaState.alphaBlend = true;
  11264. break;
  11265. case Engine.ALPHA_MAXIMIZED:
  11266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11267. this._alphaState.alphaBlend = true;
  11268. break;
  11269. case Engine.ALPHA_INTERPOLATE:
  11270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11271. this._alphaState.alphaBlend = true;
  11272. break;
  11273. case Engine.ALPHA_SCREENMODE:
  11274. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11275. this._alphaState.alphaBlend = true;
  11276. break;
  11277. }
  11278. if (!noDepthWriteChange) {
  11279. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11280. }
  11281. this._alphaMode = mode;
  11282. };
  11283. Engine.prototype.getAlphaMode = function () {
  11284. return this._alphaMode;
  11285. };
  11286. // Textures
  11287. Engine.prototype.wipeCaches = function (bruteForce) {
  11288. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11289. return;
  11290. }
  11291. this._currentEffect = null;
  11292. // 6/8/2017: deltakosh: Should not be required anymore.
  11293. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11294. if (bruteForce) {
  11295. this.resetTextureCache();
  11296. this._currentProgram = null;
  11297. this._stencilState.reset();
  11298. this._depthCullingState.reset();
  11299. this.setDepthFunctionToLessOrEqual();
  11300. this._alphaState.reset();
  11301. }
  11302. this._resetVertexBufferBinding();
  11303. this._cachedIndexBuffer = null;
  11304. this._cachedEffectForVertexBuffers = null;
  11305. this._unbindVertexArrayObject();
  11306. this.bindIndexBuffer(null);
  11307. };
  11308. /**
  11309. * Set the compressed texture format to use, based on the formats you have, and the formats
  11310. * supported by the hardware / browser.
  11311. *
  11312. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11313. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11314. * to API arguments needed to compressed textures. This puts the burden on the container
  11315. * generator to house the arcane code for determining these for current & future formats.
  11316. *
  11317. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11318. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11319. *
  11320. * Note: The result of this call is not taken into account when a texture is base64.
  11321. *
  11322. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11323. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11324. *
  11325. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11326. * @returns The extension selected.
  11327. */
  11328. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11329. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11330. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11331. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11332. return this._textureFormatInUse = this._texturesSupported[i];
  11333. }
  11334. }
  11335. }
  11336. // actively set format to nothing, to allow this to be called more than once
  11337. // and possibly fail the 2nd time
  11338. this._textureFormatInUse = null;
  11339. return null;
  11340. };
  11341. Engine.prototype._createTexture = function () {
  11342. var texture = this._gl.createTexture();
  11343. if (!texture) {
  11344. throw new Error("Unable to create texture");
  11345. }
  11346. return texture;
  11347. };
  11348. /**
  11349. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11350. * @param {string} urlArg- This contains one of the following:
  11351. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11352. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11353. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11354. *
  11355. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11356. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11357. * @param {Scene} scene- Needed for loading to the correct scene.
  11358. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11359. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11360. * @param {callback} onError- Optional callback to be called upon failure.
  11361. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11362. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11363. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11364. *
  11365. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11366. */
  11367. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11368. var _this = this;
  11369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11370. if (onLoad === void 0) { onLoad = null; }
  11371. if (onError === void 0) { onError = null; }
  11372. if (buffer === void 0) { buffer = null; }
  11373. if (fallBack === void 0) { fallBack = null; }
  11374. if (format === void 0) { format = null; }
  11375. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11376. var fromData = url.substr(0, 5) === "data:";
  11377. var fromBlob = url.substr(0, 5) === "blob:";
  11378. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11379. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11380. // establish the file extension, if possible
  11381. var lastDot = url.lastIndexOf('.');
  11382. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11383. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11384. var isTGA = (extension === ".tga");
  11385. // determine if a ktx file should be substituted
  11386. var isKTX = false;
  11387. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11388. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11389. isKTX = true;
  11390. }
  11391. if (scene) {
  11392. scene._addPendingData(texture);
  11393. }
  11394. texture.url = url;
  11395. texture.generateMipMaps = !noMipmap;
  11396. texture.samplingMode = samplingMode;
  11397. texture.invertY = invertY;
  11398. if (!this._doNotHandleContextLost) {
  11399. // Keep a link to the buffer only if we plan to handle context lost
  11400. texture._buffer = buffer;
  11401. }
  11402. var onLoadObserver = null;
  11403. if (onLoad && !fallBack) {
  11404. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11405. }
  11406. if (!fallBack)
  11407. this._internalTexturesCache.push(texture);
  11408. var onerror = function (message, exception) {
  11409. if (scene) {
  11410. scene._removePendingData(texture);
  11411. }
  11412. if (onLoadObserver) {
  11413. texture.onLoadedObservable.remove(onLoadObserver);
  11414. }
  11415. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11416. if (isKTX) {
  11417. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11418. }
  11419. else if (BABYLON.Tools.UseFallbackTexture) {
  11420. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11421. }
  11422. if (onError) {
  11423. onError(message || "Unknown error", exception);
  11424. }
  11425. };
  11426. var callback = null;
  11427. // processing for non-image formats
  11428. if (isKTX || isTGA || isDDS) {
  11429. if (isKTX) {
  11430. callback = function (data) {
  11431. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11432. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11433. ktx.uploadLevels(_this._gl, !noMipmap);
  11434. return false;
  11435. }, samplingMode);
  11436. };
  11437. }
  11438. else if (isTGA) {
  11439. callback = function (arrayBuffer) {
  11440. var data = new Uint8Array(arrayBuffer);
  11441. var header = BABYLON.TGATools.GetTGAHeader(data);
  11442. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11443. BABYLON.TGATools.UploadContent(_this._gl, data);
  11444. return false;
  11445. }, samplingMode);
  11446. };
  11447. }
  11448. else if (isDDS) {
  11449. callback = function (data) {
  11450. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11451. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11452. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11453. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11454. return false;
  11455. }, samplingMode);
  11456. };
  11457. }
  11458. if (!buffer) {
  11459. this._loadFile(url, function (data) {
  11460. if (callback) {
  11461. callback(data);
  11462. }
  11463. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11464. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11465. });
  11466. }
  11467. else {
  11468. if (callback) {
  11469. callback(buffer);
  11470. }
  11471. }
  11472. // image format processing
  11473. }
  11474. else {
  11475. var onload = function (img) {
  11476. if (fromBlob && !_this._doNotHandleContextLost) {
  11477. // We need to store the image if we need to rebuild the texture
  11478. // in case of a webgl context lost
  11479. texture._buffer = img;
  11480. }
  11481. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11482. var gl = _this._gl;
  11483. var isPot = (img.width === potWidth && img.height === potHeight);
  11484. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11485. if (isPot) {
  11486. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11487. return false;
  11488. }
  11489. // Using shaders to rescale because canvas.drawImage is lossy
  11490. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11491. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11492. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11496. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11497. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11498. _this._releaseTexture(source);
  11499. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11500. continuationCallback();
  11501. });
  11502. return true;
  11503. }, samplingMode);
  11504. };
  11505. if (!fromData || isBase64)
  11506. if (buffer instanceof HTMLImageElement) {
  11507. onload(buffer);
  11508. }
  11509. else {
  11510. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11511. }
  11512. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11513. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11514. else
  11515. onload(buffer);
  11516. }
  11517. return texture;
  11518. };
  11519. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11520. var _this = this;
  11521. var rtt = this.createRenderTargetTexture({
  11522. width: destination.width,
  11523. height: destination.height,
  11524. }, {
  11525. generateMipMaps: false,
  11526. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11527. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11528. generateDepthBuffer: false,
  11529. generateStencilBuffer: false
  11530. });
  11531. if (!this._rescalePostProcess) {
  11532. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11533. }
  11534. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11535. _this._rescalePostProcess.onApply = function (effect) {
  11536. effect._bindTexture("textureSampler", source);
  11537. };
  11538. var hostingScene = scene;
  11539. if (!hostingScene) {
  11540. hostingScene = _this.scenes[_this.scenes.length - 1];
  11541. }
  11542. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11543. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11544. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11545. _this.unBindFramebuffer(rtt);
  11546. _this._releaseTexture(rtt);
  11547. if (onComplete) {
  11548. onComplete();
  11549. }
  11550. });
  11551. };
  11552. Engine.prototype._getInternalFormat = function (format) {
  11553. var internalFormat = this._gl.RGBA;
  11554. switch (format) {
  11555. case Engine.TEXTUREFORMAT_ALPHA:
  11556. internalFormat = this._gl.ALPHA;
  11557. break;
  11558. case Engine.TEXTUREFORMAT_LUMINANCE:
  11559. internalFormat = this._gl.LUMINANCE;
  11560. break;
  11561. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11562. internalFormat = this._gl.LUMINANCE_ALPHA;
  11563. break;
  11564. case Engine.TEXTUREFORMAT_RGB:
  11565. internalFormat = this._gl.RGB;
  11566. break;
  11567. case Engine.TEXTUREFORMAT_RGBA:
  11568. internalFormat = this._gl.RGBA;
  11569. break;
  11570. }
  11571. return internalFormat;
  11572. };
  11573. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11574. if (compression === void 0) { compression = null; }
  11575. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11576. if (!texture) {
  11577. return;
  11578. }
  11579. var internalFormat = this._getInternalFormat(format);
  11580. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11581. var textureType = this._getWebGLTextureType(type);
  11582. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11583. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11584. if (!this._doNotHandleContextLost) {
  11585. texture._bufferView = data;
  11586. texture.format = format;
  11587. texture.type = type;
  11588. texture.invertY = invertY;
  11589. texture._compression = compression;
  11590. }
  11591. if (texture.width % 4 !== 0) {
  11592. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11593. }
  11594. if (compression && data) {
  11595. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11596. }
  11597. else {
  11598. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11599. }
  11600. if (texture.generateMipMaps) {
  11601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11602. }
  11603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11604. // this.resetTextureCache();
  11605. texture.isReady = true;
  11606. };
  11607. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11608. if (compression === void 0) { compression = null; }
  11609. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11611. texture.baseWidth = width;
  11612. texture.baseHeight = height;
  11613. texture.width = width;
  11614. texture.height = height;
  11615. texture.format = format;
  11616. texture.generateMipMaps = generateMipMaps;
  11617. texture.samplingMode = samplingMode;
  11618. texture.invertY = invertY;
  11619. texture._compression = compression;
  11620. texture.type = type;
  11621. if (!this._doNotHandleContextLost) {
  11622. texture._bufferView = data;
  11623. }
  11624. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11625. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11626. // Filters
  11627. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11630. if (generateMipMaps) {
  11631. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11632. }
  11633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11634. this._internalTexturesCache.push(texture);
  11635. return texture;
  11636. };
  11637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11639. texture.baseWidth = width;
  11640. texture.baseHeight = height;
  11641. if (generateMipMaps) {
  11642. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11643. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11644. }
  11645. // this.resetTextureCache();
  11646. texture.width = width;
  11647. texture.height = height;
  11648. texture.isReady = false;
  11649. texture.generateMipMaps = generateMipMaps;
  11650. texture.samplingMode = samplingMode;
  11651. this.updateTextureSamplingMode(samplingMode, texture);
  11652. this._internalTexturesCache.push(texture);
  11653. return texture;
  11654. };
  11655. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11656. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11657. if (texture.isCube) {
  11658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11659. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11662. }
  11663. else if (texture.is3D) {
  11664. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11665. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11666. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11667. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11668. }
  11669. else {
  11670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11674. }
  11675. texture.samplingMode = samplingMode;
  11676. };
  11677. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11678. if (premulAlpha === void 0) { premulAlpha = false; }
  11679. if (!texture) {
  11680. return;
  11681. }
  11682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11683. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11684. if (premulAlpha) {
  11685. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11686. }
  11687. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11689. if (texture.generateMipMaps) {
  11690. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11691. }
  11692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11693. if (premulAlpha) {
  11694. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11695. }
  11696. texture.isReady = true;
  11697. };
  11698. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11699. if (!texture || texture._isDisabled) {
  11700. return;
  11701. }
  11702. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11703. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11704. try {
  11705. // Testing video texture support
  11706. if (this._videoTextureSupported === undefined) {
  11707. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11708. if (this._gl.getError() !== 0) {
  11709. this._videoTextureSupported = false;
  11710. }
  11711. else {
  11712. this._videoTextureSupported = true;
  11713. }
  11714. }
  11715. // Copy video through the current working canvas if video texture is not supported
  11716. if (!this._videoTextureSupported) {
  11717. if (!texture._workingCanvas) {
  11718. texture._workingCanvas = document.createElement("canvas");
  11719. var context = texture._workingCanvas.getContext("2d");
  11720. if (!context) {
  11721. throw new Error("Unable to get 2d context");
  11722. }
  11723. texture._workingContext = context;
  11724. texture._workingCanvas.width = texture.width;
  11725. texture._workingCanvas.height = texture.height;
  11726. }
  11727. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11728. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11729. }
  11730. else {
  11731. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11732. }
  11733. if (texture.generateMipMaps) {
  11734. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11735. }
  11736. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11737. // this.resetTextureCache();
  11738. texture.isReady = true;
  11739. }
  11740. catch (ex) {
  11741. // Something unexpected
  11742. // Let's disable the texture
  11743. texture._isDisabled = true;
  11744. }
  11745. };
  11746. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11747. var fullOptions = new RenderTargetCreationOptions();
  11748. if (options !== undefined && typeof options === "object") {
  11749. fullOptions.generateMipMaps = options.generateMipMaps;
  11750. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11751. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11752. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11753. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11754. }
  11755. else {
  11756. fullOptions.generateMipMaps = options;
  11757. fullOptions.generateDepthBuffer = true;
  11758. fullOptions.generateStencilBuffer = false;
  11759. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11760. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11761. }
  11762. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11763. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11764. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11765. }
  11766. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11767. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11768. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11769. }
  11770. var gl = this._gl;
  11771. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11772. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11773. var width = size.width || size;
  11774. var height = size.height || size;
  11775. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11776. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11777. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11778. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11779. }
  11780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11784. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11785. // Create the framebuffer
  11786. var framebuffer = gl.createFramebuffer();
  11787. this.bindUnboundFramebuffer(framebuffer);
  11788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11789. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11790. if (fullOptions.generateMipMaps) {
  11791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11792. }
  11793. // Unbind
  11794. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11795. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11796. this.bindUnboundFramebuffer(null);
  11797. texture._framebuffer = framebuffer;
  11798. texture.baseWidth = width;
  11799. texture.baseHeight = height;
  11800. texture.width = width;
  11801. texture.height = height;
  11802. texture.isReady = true;
  11803. texture.samples = 1;
  11804. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11805. texture.samplingMode = fullOptions.samplingMode;
  11806. texture.type = fullOptions.type;
  11807. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11808. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11809. // this.resetTextureCache();
  11810. this._internalTexturesCache.push(texture);
  11811. return texture;
  11812. };
  11813. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11814. var generateMipMaps = false;
  11815. var generateDepthBuffer = true;
  11816. var generateStencilBuffer = false;
  11817. var generateDepthTexture = false;
  11818. var textureCount = 1;
  11819. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11820. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11821. var types = [], samplingModes = [];
  11822. if (options !== undefined) {
  11823. generateMipMaps = options.generateMipMaps;
  11824. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11825. generateStencilBuffer = options.generateStencilBuffer;
  11826. generateDepthTexture = options.generateDepthTexture;
  11827. textureCount = options.textureCount || 1;
  11828. if (options.types) {
  11829. types = options.types;
  11830. }
  11831. if (options.samplingModes) {
  11832. samplingModes = options.samplingModes;
  11833. }
  11834. }
  11835. var gl = this._gl;
  11836. // Create the framebuffer
  11837. var framebuffer = gl.createFramebuffer();
  11838. this.bindUnboundFramebuffer(framebuffer);
  11839. var width = size.width || size;
  11840. var height = size.height || size;
  11841. var textures = [];
  11842. var attachments = [];
  11843. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11844. for (var i = 0; i < textureCount; i++) {
  11845. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11846. var type = types[i] || defaultType;
  11847. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11848. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11849. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11850. }
  11851. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11852. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11853. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11854. }
  11855. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11856. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11857. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11858. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11859. }
  11860. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11861. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11862. textures.push(texture);
  11863. attachments.push(attachment);
  11864. gl.activeTexture(gl["TEXTURE" + i]);
  11865. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11870. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11871. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11872. if (generateMipMaps) {
  11873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11874. }
  11875. // Unbind
  11876. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11877. texture._framebuffer = framebuffer;
  11878. texture._depthStencilBuffer = depthStencilBuffer;
  11879. texture.baseWidth = width;
  11880. texture.baseHeight = height;
  11881. texture.width = width;
  11882. texture.height = height;
  11883. texture.isReady = true;
  11884. texture.samples = 1;
  11885. texture.generateMipMaps = generateMipMaps;
  11886. texture.samplingMode = samplingMode;
  11887. texture.type = type;
  11888. texture._generateDepthBuffer = generateDepthBuffer;
  11889. texture._generateStencilBuffer = generateStencilBuffer;
  11890. texture._attachments = attachments;
  11891. this._internalTexturesCache.push(texture);
  11892. }
  11893. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11894. // Depth texture
  11895. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11896. gl.activeTexture(gl.TEXTURE0);
  11897. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11902. 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);
  11903. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11904. depthTexture._framebuffer = framebuffer;
  11905. depthTexture.baseWidth = width;
  11906. depthTexture.baseHeight = height;
  11907. depthTexture.width = width;
  11908. depthTexture.height = height;
  11909. depthTexture.isReady = true;
  11910. depthTexture.samples = 1;
  11911. depthTexture.generateMipMaps = generateMipMaps;
  11912. depthTexture.samplingMode = gl.NEAREST;
  11913. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11914. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11915. textures.push(depthTexture);
  11916. this._internalTexturesCache.push(depthTexture);
  11917. }
  11918. gl.drawBuffers(attachments);
  11919. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11920. this.bindUnboundFramebuffer(null);
  11921. this.resetTextureCache();
  11922. return textures;
  11923. };
  11924. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11925. if (samples === void 0) { samples = 1; }
  11926. var depthStencilBuffer = null;
  11927. var gl = this._gl;
  11928. // Create the depth/stencil buffer
  11929. if (generateStencilBuffer) {
  11930. depthStencilBuffer = gl.createRenderbuffer();
  11931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11932. if (samples > 1) {
  11933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11934. }
  11935. else {
  11936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11937. }
  11938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11939. }
  11940. else if (generateDepthBuffer) {
  11941. depthStencilBuffer = gl.createRenderbuffer();
  11942. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11943. if (samples > 1) {
  11944. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11945. }
  11946. else {
  11947. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11948. }
  11949. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11950. }
  11951. return depthStencilBuffer;
  11952. };
  11953. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11954. if (this.webGLVersion < 2 || !texture) {
  11955. return 1;
  11956. }
  11957. if (texture.samples === samples) {
  11958. return samples;
  11959. }
  11960. var gl = this._gl;
  11961. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11962. // Dispose previous render buffers
  11963. if (texture._depthStencilBuffer) {
  11964. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11965. texture._depthStencilBuffer = null;
  11966. }
  11967. if (texture._MSAAFramebuffer) {
  11968. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11969. texture._MSAAFramebuffer = null;
  11970. }
  11971. if (texture._MSAARenderBuffer) {
  11972. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11973. texture._MSAARenderBuffer = null;
  11974. }
  11975. if (samples > 1) {
  11976. var framebuffer = gl.createFramebuffer();
  11977. if (!framebuffer) {
  11978. throw new Error("Unable to create multi sampled framebuffer");
  11979. }
  11980. texture._MSAAFramebuffer = framebuffer;
  11981. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11982. var colorRenderbuffer = gl.createRenderbuffer();
  11983. if (!colorRenderbuffer) {
  11984. throw new Error("Unable to create multi sampled framebuffer");
  11985. }
  11986. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11987. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11988. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11989. texture._MSAARenderBuffer = colorRenderbuffer;
  11990. }
  11991. else {
  11992. this.bindUnboundFramebuffer(texture._framebuffer);
  11993. }
  11994. texture.samples = samples;
  11995. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11996. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11997. this.bindUnboundFramebuffer(null);
  11998. return samples;
  11999. };
  12000. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12001. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12002. return 1;
  12003. }
  12004. if (textures[0].samples === samples) {
  12005. return samples;
  12006. }
  12007. var gl = this._gl;
  12008. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12009. // Dispose previous render buffers
  12010. if (textures[0]._depthStencilBuffer) {
  12011. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12012. textures[0]._depthStencilBuffer = null;
  12013. }
  12014. if (textures[0]._MSAAFramebuffer) {
  12015. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12016. textures[0]._MSAAFramebuffer = null;
  12017. }
  12018. for (var i = 0; i < textures.length; i++) {
  12019. if (textures[i]._MSAARenderBuffer) {
  12020. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12021. textures[i]._MSAARenderBuffer = null;
  12022. }
  12023. }
  12024. if (samples > 1) {
  12025. var framebuffer = gl.createFramebuffer();
  12026. if (!framebuffer) {
  12027. throw new Error("Unable to create multi sampled framebuffer");
  12028. }
  12029. this.bindUnboundFramebuffer(framebuffer);
  12030. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12031. var attachments = [];
  12032. for (var i = 0; i < textures.length; i++) {
  12033. var texture = textures[i];
  12034. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12035. var colorRenderbuffer = gl.createRenderbuffer();
  12036. if (!colorRenderbuffer) {
  12037. throw new Error("Unable to create multi sampled framebuffer");
  12038. }
  12039. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12040. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12041. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12042. texture._MSAAFramebuffer = framebuffer;
  12043. texture._MSAARenderBuffer = colorRenderbuffer;
  12044. texture.samples = samples;
  12045. texture._depthStencilBuffer = depthStencilBuffer;
  12046. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12047. attachments.push(attachment);
  12048. }
  12049. gl.drawBuffers(attachments);
  12050. }
  12051. else {
  12052. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12053. }
  12054. this.bindUnboundFramebuffer(null);
  12055. return samples;
  12056. };
  12057. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12058. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12059. };
  12060. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12061. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12062. };
  12063. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12064. var gl = this._gl;
  12065. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12066. var generateMipMaps = true;
  12067. var generateDepthBuffer = true;
  12068. var generateStencilBuffer = false;
  12069. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12070. if (options !== undefined) {
  12071. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12072. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12073. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12074. if (options.samplingMode !== undefined) {
  12075. samplingMode = options.samplingMode;
  12076. }
  12077. }
  12078. texture.isCube = true;
  12079. texture.generateMipMaps = generateMipMaps;
  12080. texture.samples = 1;
  12081. texture.samplingMode = samplingMode;
  12082. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12083. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12084. for (var face = 0; face < 6; face++) {
  12085. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12086. }
  12087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12088. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12089. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12091. // Create the framebuffer
  12092. var framebuffer = gl.createFramebuffer();
  12093. this.bindUnboundFramebuffer(framebuffer);
  12094. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12095. // Mipmaps
  12096. if (texture.generateMipMaps) {
  12097. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12098. }
  12099. // Unbind
  12100. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12101. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12102. this.bindUnboundFramebuffer(null);
  12103. texture._framebuffer = framebuffer;
  12104. texture.width = size;
  12105. texture.height = size;
  12106. texture.isReady = true;
  12107. //this.resetTextureCache();
  12108. this._internalTexturesCache.push(texture);
  12109. return texture;
  12110. };
  12111. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12112. var _this = this;
  12113. if (onLoad === void 0) { onLoad = null; }
  12114. if (onError === void 0) { onError = null; }
  12115. if (forcedExtension === void 0) { forcedExtension = null; }
  12116. var callback = function (loadData) {
  12117. if (!loadData) {
  12118. if (onLoad) {
  12119. onLoad(null);
  12120. }
  12121. return;
  12122. }
  12123. var texture = loadData.texture;
  12124. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12125. texture._lodGenerationScale = scale;
  12126. texture._lodGenerationOffset = offset;
  12127. if (_this._caps.textureLOD) {
  12128. // Do not add extra process if texture lod is supported.
  12129. if (onLoad) {
  12130. onLoad(texture);
  12131. }
  12132. return;
  12133. }
  12134. var mipSlices = 3;
  12135. var gl = _this._gl;
  12136. var width = loadData.width;
  12137. if (!width) {
  12138. return;
  12139. }
  12140. var textures = [];
  12141. for (var i = 0; i < mipSlices; i++) {
  12142. //compute LOD from even spacing in smoothness (matching shader calculation)
  12143. var smoothness = i / (mipSlices - 1);
  12144. var roughness = 1 - smoothness;
  12145. var minLODIndex = offset; // roughness = 0
  12146. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12147. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12148. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12149. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12150. glTextureFromLod.isCube = true;
  12151. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12156. if (loadData.isDDS) {
  12157. var info = loadData.info;
  12158. var data = loadData.data;
  12159. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12160. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12161. }
  12162. else {
  12163. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12164. }
  12165. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12166. // Wrap in a base texture for easy binding.
  12167. var lodTexture = new BABYLON.BaseTexture(scene);
  12168. lodTexture.isCube = true;
  12169. lodTexture._texture = glTextureFromLod;
  12170. glTextureFromLod.isReady = true;
  12171. textures.push(lodTexture);
  12172. }
  12173. texture._lodTextureHigh = textures[2];
  12174. texture._lodTextureMid = textures[1];
  12175. texture._lodTextureLow = textures[0];
  12176. if (onLoad) {
  12177. onLoad(texture);
  12178. }
  12179. };
  12180. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12181. };
  12182. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12183. var _this = this;
  12184. if (onLoad === void 0) { onLoad = null; }
  12185. if (onError === void 0) { onError = null; }
  12186. if (forcedExtension === void 0) { forcedExtension = null; }
  12187. var gl = this._gl;
  12188. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12189. texture.isCube = true;
  12190. texture.url = rootUrl;
  12191. texture.generateMipMaps = !noMipmap;
  12192. if (!this._doNotHandleContextLost) {
  12193. texture._extension = forcedExtension;
  12194. texture._files = files;
  12195. }
  12196. var isKTX = false;
  12197. var isDDS = false;
  12198. var lastDot = rootUrl.lastIndexOf('.');
  12199. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12200. if (this._textureFormatInUse) {
  12201. extension = this._textureFormatInUse;
  12202. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12203. isKTX = true;
  12204. }
  12205. else {
  12206. isDDS = (extension === ".dds");
  12207. }
  12208. var onerror = function (request, exception) {
  12209. if (onError && request) {
  12210. onError(request.status + " " + request.statusText, exception);
  12211. }
  12212. };
  12213. if (isKTX) {
  12214. this._loadFile(rootUrl, function (data) {
  12215. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12216. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12217. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12218. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12219. ktx.uploadLevels(_this._gl, !noMipmap);
  12220. _this.setCubeMapTextureParams(gl, loadMipmap);
  12221. texture.width = ktx.pixelWidth;
  12222. texture.height = ktx.pixelHeight;
  12223. texture.isReady = true;
  12224. }, undefined, undefined, true, onerror);
  12225. }
  12226. else if (isDDS) {
  12227. if (files && files.length === 6) {
  12228. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12229. var info;
  12230. var loadMipmap = false;
  12231. var width = 0;
  12232. for (var index = 0; index < imgs.length; index++) {
  12233. var data = imgs[index];
  12234. info = BABYLON.DDSTools.GetDDSInfo(data);
  12235. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12238. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12239. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12240. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12241. }
  12242. texture.width = info.width;
  12243. texture.height = info.height;
  12244. texture.type = info.textureType;
  12245. width = info.width;
  12246. }
  12247. _this.setCubeMapTextureParams(gl, loadMipmap);
  12248. texture.isReady = true;
  12249. if (onLoad) {
  12250. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12251. }
  12252. }, files, onError);
  12253. }
  12254. else {
  12255. this._loadFile(rootUrl, function (data) {
  12256. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12257. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12258. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12259. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12260. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12261. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12262. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12263. }
  12264. _this.setCubeMapTextureParams(gl, loadMipmap);
  12265. texture.width = info.width;
  12266. texture.height = info.height;
  12267. texture.isReady = true;
  12268. texture.type = info.textureType;
  12269. if (onLoad) {
  12270. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12271. }
  12272. }, undefined, undefined, true, onerror);
  12273. }
  12274. }
  12275. else {
  12276. if (!files) {
  12277. throw new Error("Cannot load cubemap because files were not defined");
  12278. }
  12279. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12280. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12281. var height = width;
  12282. _this._prepareWorkingCanvas();
  12283. if (!_this._workingCanvas || !_this._workingContext) {
  12284. return;
  12285. }
  12286. _this._workingCanvas.width = width;
  12287. _this._workingCanvas.height = height;
  12288. var faces = [
  12289. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12290. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12291. ];
  12292. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12293. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12294. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12295. for (var index = 0; index < faces.length; index++) {
  12296. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12297. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12298. }
  12299. if (!noMipmap) {
  12300. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12301. }
  12302. _this.setCubeMapTextureParams(gl, !noMipmap);
  12303. texture.width = width;
  12304. texture.height = height;
  12305. texture.isReady = true;
  12306. if (format) {
  12307. texture.format = format;
  12308. }
  12309. texture.onLoadedObservable.notifyObservers(texture);
  12310. texture.onLoadedObservable.clear();
  12311. if (onLoad) {
  12312. onLoad();
  12313. }
  12314. }, files, onError);
  12315. }
  12316. this._internalTexturesCache.push(texture);
  12317. return texture;
  12318. };
  12319. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12324. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12325. // this.resetTextureCache();
  12326. };
  12327. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12328. if (compression === void 0) { compression = null; }
  12329. if (level === void 0) { level = 0; }
  12330. texture._bufferViewArray = data;
  12331. texture.format = format;
  12332. texture.type = type;
  12333. texture.invertY = invertY;
  12334. texture._compression = compression;
  12335. var gl = this._gl;
  12336. var textureType = this._getWebGLTextureType(type);
  12337. var internalFormat = this._getInternalFormat(format);
  12338. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12339. var needConversion = false;
  12340. if (internalFormat === gl.RGB) {
  12341. internalFormat = gl.RGBA;
  12342. needConversion = true;
  12343. }
  12344. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12345. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12346. if (texture.width % 4 !== 0) {
  12347. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12348. }
  12349. // Data are known to be in +X +Y +Z -X -Y -Z
  12350. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12351. var faceData = data[faceIndex];
  12352. if (compression) {
  12353. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12354. }
  12355. else {
  12356. if (needConversion) {
  12357. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12358. }
  12359. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12360. }
  12361. }
  12362. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12363. if (isPot && texture.generateMipMaps && level === 0) {
  12364. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12365. }
  12366. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12367. // this.resetTextureCache();
  12368. texture.isReady = true;
  12369. };
  12370. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12371. if (compression === void 0) { compression = null; }
  12372. var gl = this._gl;
  12373. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12374. texture.isCube = true;
  12375. texture.generateMipMaps = generateMipMaps;
  12376. texture.format = format;
  12377. texture.type = type;
  12378. if (!this._doNotHandleContextLost) {
  12379. texture._bufferViewArray = data;
  12380. }
  12381. var textureType = this._getWebGLTextureType(type);
  12382. var internalFormat = this._getInternalFormat(format);
  12383. if (internalFormat === gl.RGB) {
  12384. internalFormat = gl.RGBA;
  12385. }
  12386. var width = size;
  12387. var height = width;
  12388. texture.width = width;
  12389. texture.height = height;
  12390. // Double check on POT to generate Mips.
  12391. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12392. if (!isPot) {
  12393. generateMipMaps = false;
  12394. }
  12395. // Upload data if needed. The texture won't be ready until then.
  12396. if (data) {
  12397. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12398. }
  12399. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12400. // Filters
  12401. if (data && generateMipMaps) {
  12402. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12403. }
  12404. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12407. }
  12408. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12409. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12411. }
  12412. else {
  12413. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12416. }
  12417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12419. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12420. return texture;
  12421. };
  12422. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12423. var _this = this;
  12424. if (onLoad === void 0) { onLoad = null; }
  12425. if (onError === void 0) { onError = null; }
  12426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12427. if (invertY === void 0) { invertY = false; }
  12428. var gl = this._gl;
  12429. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12430. scene._addPendingData(texture);
  12431. texture.url = url;
  12432. this._internalTexturesCache.push(texture);
  12433. var onerror = function (request, exception) {
  12434. scene._removePendingData(texture);
  12435. if (onError && request) {
  12436. onError(request.status + " " + request.statusText, exception);
  12437. }
  12438. };
  12439. var internalCallback = function (data) {
  12440. var width = texture.width;
  12441. var faceDataArrays = callback(data);
  12442. if (!faceDataArrays) {
  12443. return;
  12444. }
  12445. if (mipmmapGenerator) {
  12446. var textureType = _this._getWebGLTextureType(type);
  12447. var internalFormat = _this._getInternalFormat(format);
  12448. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12449. var needConversion = false;
  12450. if (internalFormat === gl.RGB) {
  12451. internalFormat = gl.RGBA;
  12452. needConversion = true;
  12453. }
  12454. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12455. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12456. var mipData = mipmmapGenerator(faceDataArrays);
  12457. for (var level = 0; level < mipData.length; level++) {
  12458. var mipSize = width >> level;
  12459. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12460. var mipFaceData = mipData[level][faceIndex];
  12461. if (needConversion) {
  12462. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12463. }
  12464. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12465. }
  12466. }
  12467. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12468. }
  12469. else {
  12470. texture.generateMipMaps = !noMipmap;
  12471. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12472. }
  12473. texture.isReady = true;
  12474. // this.resetTextureCache();
  12475. scene._removePendingData(texture);
  12476. if (onLoad) {
  12477. onLoad();
  12478. }
  12479. };
  12480. this._loadFile(url, function (data) {
  12481. internalCallback(data);
  12482. }, undefined, scene.database, true, onerror);
  12483. return texture;
  12484. };
  12485. ;
  12486. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12487. if (compression === void 0) { compression = null; }
  12488. var internalFormat = this._getInternalFormat(format);
  12489. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12490. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12491. if (!this._doNotHandleContextLost) {
  12492. texture._bufferView = data;
  12493. texture.format = format;
  12494. texture.invertY = invertY;
  12495. texture._compression = compression;
  12496. }
  12497. if (texture.width % 4 !== 0) {
  12498. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12499. }
  12500. if (compression && data) {
  12501. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12502. }
  12503. else {
  12504. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12505. }
  12506. if (texture.generateMipMaps) {
  12507. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12508. }
  12509. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12510. // this.resetTextureCache();
  12511. texture.isReady = true;
  12512. };
  12513. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12514. if (compression === void 0) { compression = null; }
  12515. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12516. texture.baseWidth = width;
  12517. texture.baseHeight = height;
  12518. texture.baseDepth = depth;
  12519. texture.width = width;
  12520. texture.height = height;
  12521. texture.depth = depth;
  12522. texture.format = format;
  12523. texture.generateMipMaps = generateMipMaps;
  12524. texture.samplingMode = samplingMode;
  12525. texture.is3D = true;
  12526. if (!this._doNotHandleContextLost) {
  12527. texture._bufferView = data;
  12528. }
  12529. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12530. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12531. // Filters
  12532. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12533. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12534. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12535. if (generateMipMaps) {
  12536. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12537. }
  12538. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12539. this._internalTexturesCache.push(texture);
  12540. return texture;
  12541. };
  12542. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12543. var gl = this._gl;
  12544. if (!gl) {
  12545. return;
  12546. }
  12547. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12550. if (!noMipmap && !isCompressed) {
  12551. gl.generateMipmap(gl.TEXTURE_2D);
  12552. }
  12553. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12554. // this.resetTextureCache();
  12555. if (scene) {
  12556. scene._removePendingData(texture);
  12557. }
  12558. texture.onLoadedObservable.notifyObservers(texture);
  12559. texture.onLoadedObservable.clear();
  12560. };
  12561. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12562. var _this = this;
  12563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12564. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12565. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12566. var gl = this._gl;
  12567. if (!gl) {
  12568. return;
  12569. }
  12570. if (!texture._webGLTexture) {
  12571. // this.resetTextureCache();
  12572. if (scene) {
  12573. scene._removePendingData(texture);
  12574. }
  12575. return;
  12576. }
  12577. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12578. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12579. texture.baseWidth = width;
  12580. texture.baseHeight = height;
  12581. texture.width = potWidth;
  12582. texture.height = potHeight;
  12583. texture.isReady = true;
  12584. if (processFunction(potWidth, potHeight, function () {
  12585. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12586. })) {
  12587. // Returning as texture needs extra async steps
  12588. return;
  12589. }
  12590. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12591. };
  12592. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12593. // Create new RGBA data container.
  12594. var rgbaData;
  12595. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12596. rgbaData = new Float32Array(width * height * 4);
  12597. }
  12598. else {
  12599. rgbaData = new Uint32Array(width * height * 4);
  12600. }
  12601. // Convert each pixel.
  12602. for (var x = 0; x < width; x++) {
  12603. for (var y = 0; y < height; y++) {
  12604. var index = (y * width + x) * 3;
  12605. var newIndex = (y * width + x) * 4;
  12606. // Map Old Value to new value.
  12607. rgbaData[newIndex + 0] = rgbData[index + 0];
  12608. rgbaData[newIndex + 1] = rgbData[index + 1];
  12609. rgbaData[newIndex + 2] = rgbData[index + 2];
  12610. // Add fully opaque alpha channel.
  12611. rgbaData[newIndex + 3] = 1;
  12612. }
  12613. }
  12614. return rgbaData;
  12615. };
  12616. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12617. var gl = this._gl;
  12618. if (texture._framebuffer) {
  12619. gl.deleteFramebuffer(texture._framebuffer);
  12620. texture._framebuffer = null;
  12621. }
  12622. if (texture._depthStencilBuffer) {
  12623. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12624. texture._depthStencilBuffer = null;
  12625. }
  12626. if (texture._MSAAFramebuffer) {
  12627. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12628. texture._MSAAFramebuffer = null;
  12629. }
  12630. if (texture._MSAARenderBuffer) {
  12631. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12632. texture._MSAARenderBuffer = null;
  12633. }
  12634. };
  12635. Engine.prototype._releaseTexture = function (texture) {
  12636. var gl = this._gl;
  12637. this._releaseFramebufferObjects(texture);
  12638. gl.deleteTexture(texture._webGLTexture);
  12639. // Unbind channels
  12640. this.unbindAllTextures();
  12641. var index = this._internalTexturesCache.indexOf(texture);
  12642. if (index !== -1) {
  12643. this._internalTexturesCache.splice(index, 1);
  12644. }
  12645. // Integrated fixed lod samplers.
  12646. if (texture._lodTextureHigh) {
  12647. texture._lodTextureHigh.dispose();
  12648. }
  12649. if (texture._lodTextureMid) {
  12650. texture._lodTextureMid.dispose();
  12651. }
  12652. if (texture._lodTextureLow) {
  12653. texture._lodTextureLow.dispose();
  12654. }
  12655. };
  12656. Engine.prototype.setProgram = function (program) {
  12657. if (this._currentProgram !== program) {
  12658. this._gl.useProgram(program);
  12659. this._currentProgram = program;
  12660. }
  12661. };
  12662. Engine.prototype.bindSamplers = function (effect) {
  12663. this.setProgram(effect.getProgram());
  12664. var samplers = effect.getSamplers();
  12665. for (var index = 0; index < samplers.length; index++) {
  12666. var uniform = effect.getUniform(samplers[index]);
  12667. if (uniform) {
  12668. this._boundUniforms[index] = uniform;
  12669. }
  12670. }
  12671. this._currentEffect = null;
  12672. };
  12673. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12674. if (this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12675. return;
  12676. }
  12677. // Remove
  12678. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12679. // Bind last to it
  12680. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12681. // Bind to dummy
  12682. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12683. };
  12684. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12685. if (!internalTexture) {
  12686. return -1;
  12687. }
  12688. internalTexture._initialSlot = channel;
  12689. if (this.disableTextureBindingOptimization) {
  12690. if (channel !== internalTexture._designatedSlot) {
  12691. this._textureCollisions.addCount(1, false);
  12692. }
  12693. }
  12694. else {
  12695. if (channel !== internalTexture._designatedSlot) {
  12696. if (internalTexture._designatedSlot > -1) {
  12697. return internalTexture._designatedSlot;
  12698. }
  12699. else {
  12700. // No slot for this texture, let's pick a new one (if we find a free slot)
  12701. if (this._nextFreeTextureSlots.length) {
  12702. return this._nextFreeTextureSlots[0];
  12703. }
  12704. // We need to recycle the oldest bound texture, sorry.
  12705. this._textureCollisions.addCount(1, false);
  12706. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12707. }
  12708. }
  12709. }
  12710. return channel;
  12711. };
  12712. Engine.prototype._linkTrackers = function (previous, next) {
  12713. previous.next = next;
  12714. next.previous = previous;
  12715. };
  12716. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12717. var currentSlot = internalTexture._designatedSlot;
  12718. if (currentSlot === -1) {
  12719. return -1;
  12720. }
  12721. internalTexture._designatedSlot = -1;
  12722. // Remove from bound list
  12723. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12724. // Free the slot
  12725. this._boundTexturesCache[currentSlot] = null;
  12726. this._nextFreeTextureSlots.push(currentSlot);
  12727. return currentSlot;
  12728. };
  12729. Engine.prototype._activateCurrentTexture = function () {
  12730. if (this._currentTextureChannel !== this._activeChannel) {
  12731. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12732. this._currentTextureChannel = this._activeChannel;
  12733. }
  12734. };
  12735. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12736. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12737. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12738. this._activeChannel = texture._designatedSlot;
  12739. }
  12740. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12741. var isTextureForRendering = texture && texture._initialSlot > -1;
  12742. if (currentTextureBound !== texture) {
  12743. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12744. this._removeDesignatedSlot(currentTextureBound);
  12745. }
  12746. this._activateCurrentTexture();
  12747. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12748. this._boundTexturesCache[this._activeChannel] = texture;
  12749. if (texture) {
  12750. if (!this.disableTextureBindingOptimization) {
  12751. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12752. if (slotIndex > -1) {
  12753. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12754. }
  12755. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  12756. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  12757. }
  12758. texture._designatedSlot = this._activeChannel;
  12759. }
  12760. }
  12761. else if (forTextureDataUpdate) {
  12762. this._activateCurrentTexture();
  12763. }
  12764. if (isTextureForRendering && !forTextureDataUpdate) {
  12765. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12766. }
  12767. };
  12768. Engine.prototype._bindTexture = function (channel, texture) {
  12769. if (channel < 0) {
  12770. return;
  12771. }
  12772. if (texture) {
  12773. channel = this._getCorrectTextureChannel(channel, texture);
  12774. }
  12775. this._activeChannel = channel;
  12776. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12777. };
  12778. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12779. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12780. };
  12781. Engine.prototype.unbindAllTextures = function () {
  12782. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12783. this._activeChannel = channel;
  12784. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12785. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12786. if (this.webGLVersion > 1) {
  12787. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12788. }
  12789. }
  12790. };
  12791. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12792. if (channel < 0) {
  12793. return;
  12794. }
  12795. if (uniform) {
  12796. this._boundUniforms[channel] = uniform;
  12797. }
  12798. this._setTexture(channel, texture);
  12799. };
  12800. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12801. var uniform = this._boundUniforms[sourceSlot];
  12802. if (uniform._currentState === destination) {
  12803. return;
  12804. }
  12805. this._gl.uniform1i(uniform, destination);
  12806. uniform._currentState = destination;
  12807. };
  12808. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12809. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12810. // Not ready?
  12811. if (!texture) {
  12812. if (this._boundTexturesCache[channel] != null) {
  12813. this._activeChannel = channel;
  12814. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12815. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12816. if (this.webGLVersion > 1) {
  12817. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12818. }
  12819. }
  12820. return false;
  12821. }
  12822. // Video
  12823. if (texture.video) {
  12824. this._activeChannel = channel;
  12825. texture.update();
  12826. }
  12827. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12828. texture.delayLoad();
  12829. return false;
  12830. }
  12831. var internalTexture;
  12832. if (texture.isReady()) {
  12833. internalTexture = texture.getInternalTexture();
  12834. }
  12835. else if (texture.isCube) {
  12836. internalTexture = this.emptyCubeTexture;
  12837. }
  12838. else if (texture.is3D) {
  12839. internalTexture = this.emptyTexture3D;
  12840. }
  12841. else {
  12842. internalTexture = this.emptyTexture;
  12843. }
  12844. if (!isPartOfTextureArray) {
  12845. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12846. }
  12847. if (this._boundTexturesCache[channel] === internalTexture) {
  12848. this._moveBoundTextureOnTop(internalTexture);
  12849. if (!isPartOfTextureArray) {
  12850. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12851. }
  12852. return false;
  12853. }
  12854. this._activeChannel = channel;
  12855. if (internalTexture && internalTexture.is3D) {
  12856. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12857. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12858. internalTexture._cachedWrapU = texture.wrapU;
  12859. switch (texture.wrapU) {
  12860. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12861. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12862. break;
  12863. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12864. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12865. break;
  12866. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12868. break;
  12869. }
  12870. }
  12871. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12872. internalTexture._cachedWrapV = texture.wrapV;
  12873. switch (texture.wrapV) {
  12874. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12875. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12876. break;
  12877. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12878. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12879. break;
  12880. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12881. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12882. break;
  12883. }
  12884. }
  12885. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12886. internalTexture._cachedWrapR = texture.wrapR;
  12887. switch (texture.wrapV) {
  12888. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12889. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12890. break;
  12891. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12892. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12893. break;
  12894. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12895. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12896. break;
  12897. }
  12898. }
  12899. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12900. }
  12901. else if (internalTexture && internalTexture.isCube) {
  12902. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12903. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12904. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12905. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12906. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12907. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12908. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12909. }
  12910. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12911. }
  12912. else {
  12913. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12914. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12915. internalTexture._cachedWrapU = texture.wrapU;
  12916. switch (texture.wrapU) {
  12917. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12919. break;
  12920. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12922. break;
  12923. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12925. break;
  12926. }
  12927. }
  12928. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12929. internalTexture._cachedWrapV = texture.wrapV;
  12930. switch (texture.wrapV) {
  12931. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12933. break;
  12934. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12935. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12936. break;
  12937. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12939. break;
  12940. }
  12941. }
  12942. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12943. }
  12944. return true;
  12945. };
  12946. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12947. if (channel < 0 || !uniform) {
  12948. return;
  12949. }
  12950. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12951. this._textureUnits = new Int32Array(textures.length);
  12952. }
  12953. for (var i = 0; i < textures.length; i++) {
  12954. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12955. }
  12956. this._gl.uniform1iv(uniform, this._textureUnits);
  12957. for (var index = 0; index < textures.length; index++) {
  12958. this._setTexture(this._textureUnits[index], textures[index], true);
  12959. }
  12960. };
  12961. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12962. var internalTexture = texture.getInternalTexture();
  12963. if (!internalTexture) {
  12964. return;
  12965. }
  12966. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12967. var value = texture.anisotropicFilteringLevel;
  12968. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12969. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12970. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12971. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12972. }
  12973. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12974. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12975. internalTexture._cachedAnisotropicFilteringLevel = value;
  12976. }
  12977. };
  12978. Engine.prototype.readPixels = function (x, y, width, height) {
  12979. var data = new Uint8Array(height * width * 4);
  12980. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12981. return data;
  12982. };
  12983. /**
  12984. * Add an externaly attached data from its key.
  12985. * This method call will fail and return false, if such key already exists.
  12986. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12987. * @param key the unique key that identifies the data
  12988. * @param data the data object to associate to the key for this Engine instance
  12989. * @return true if no such key were already present and the data was added successfully, false otherwise
  12990. */
  12991. Engine.prototype.addExternalData = function (key, data) {
  12992. if (!this._externalData) {
  12993. this._externalData = new BABYLON.StringDictionary();
  12994. }
  12995. return this._externalData.add(key, data);
  12996. };
  12997. /**
  12998. * Get an externaly attached data from its key
  12999. * @param key the unique key that identifies the data
  13000. * @return the associated data, if present (can be null), or undefined if not present
  13001. */
  13002. Engine.prototype.getExternalData = function (key) {
  13003. if (!this._externalData) {
  13004. this._externalData = new BABYLON.StringDictionary();
  13005. }
  13006. return this._externalData.get(key);
  13007. };
  13008. /**
  13009. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13010. * @param key the unique key that identifies the data
  13011. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13012. * @return the associated data, can be null if the factory returned null.
  13013. */
  13014. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13015. if (!this._externalData) {
  13016. this._externalData = new BABYLON.StringDictionary();
  13017. }
  13018. return this._externalData.getOrAddWithFactory(key, factory);
  13019. };
  13020. /**
  13021. * Remove an externaly attached data from the Engine instance
  13022. * @param key the unique key that identifies the data
  13023. * @return true if the data was successfully removed, false if it doesn't exist
  13024. */
  13025. Engine.prototype.removeExternalData = function (key) {
  13026. if (!this._externalData) {
  13027. this._externalData = new BABYLON.StringDictionary();
  13028. }
  13029. return this._externalData.remove(key);
  13030. };
  13031. Engine.prototype.unbindAllAttributes = function () {
  13032. if (this._mustWipeVertexAttributes) {
  13033. this._mustWipeVertexAttributes = false;
  13034. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13035. this._gl.disableVertexAttribArray(i);
  13036. this._vertexAttribArraysEnabled[i] = false;
  13037. this._currentBufferPointers[i].active = false;
  13038. }
  13039. return;
  13040. }
  13041. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13042. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13043. continue;
  13044. }
  13045. this._gl.disableVertexAttribArray(i);
  13046. this._vertexAttribArraysEnabled[i] = false;
  13047. this._currentBufferPointers[i].active = false;
  13048. }
  13049. };
  13050. Engine.prototype.releaseEffects = function () {
  13051. for (var name in this._compiledEffects) {
  13052. this._deleteProgram(this._compiledEffects[name]._program);
  13053. }
  13054. this._compiledEffects = {};
  13055. };
  13056. // Dispose
  13057. Engine.prototype.dispose = function () {
  13058. this.hideLoadingUI();
  13059. this.stopRenderLoop();
  13060. // Release postProcesses
  13061. while (this.postProcesses.length) {
  13062. this.postProcesses[0].dispose();
  13063. }
  13064. // Empty texture
  13065. if (this._emptyTexture) {
  13066. this._releaseTexture(this._emptyTexture);
  13067. this._emptyTexture = null;
  13068. }
  13069. if (this._emptyCubeTexture) {
  13070. this._releaseTexture(this._emptyCubeTexture);
  13071. this._emptyCubeTexture = null;
  13072. }
  13073. // Rescale PP
  13074. if (this._rescalePostProcess) {
  13075. this._rescalePostProcess.dispose();
  13076. }
  13077. // Release scenes
  13078. while (this.scenes.length) {
  13079. this.scenes[0].dispose();
  13080. }
  13081. // Release audio engine
  13082. if (Engine.audioEngine) {
  13083. Engine.audioEngine.dispose();
  13084. }
  13085. // Release effects
  13086. this.releaseEffects();
  13087. // Unbind
  13088. this.unbindAllAttributes();
  13089. if (this._dummyFramebuffer) {
  13090. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13091. }
  13092. //WebVR
  13093. this.disableVR();
  13094. // Events
  13095. if (BABYLON.Tools.IsWindowObjectExist()) {
  13096. window.removeEventListener("blur", this._onBlur);
  13097. window.removeEventListener("focus", this._onFocus);
  13098. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13099. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13100. if (this._renderingCanvas) {
  13101. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13102. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13103. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13104. if (!this._doNotHandleContextLost) {
  13105. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13106. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13107. }
  13108. }
  13109. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13110. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13111. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13112. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13113. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13114. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13115. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13116. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13117. if (this._onVrDisplayConnect) {
  13118. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13119. if (this._onVrDisplayDisconnect) {
  13120. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13121. }
  13122. if (this._onVrDisplayPresentChange) {
  13123. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13124. }
  13125. this._onVrDisplayConnect = null;
  13126. this._onVrDisplayDisconnect = null;
  13127. }
  13128. }
  13129. // Remove from Instances
  13130. var index = Engine.Instances.indexOf(this);
  13131. if (index >= 0) {
  13132. Engine.Instances.splice(index, 1);
  13133. }
  13134. this._workingCanvas = null;
  13135. this._workingContext = null;
  13136. this._currentBufferPointers = [];
  13137. this._renderingCanvas = null;
  13138. this._currentProgram = null;
  13139. this.onResizeObservable.clear();
  13140. this.onCanvasBlurObservable.clear();
  13141. this.onCanvasFocusObservable.clear();
  13142. this.onCanvasPointerOutObservable.clear();
  13143. this.onBeginFrameObservable.clear();
  13144. this.onEndFrameObservable.clear();
  13145. BABYLON.Effect.ResetCache();
  13146. // Abort active requests
  13147. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13148. var request = _a[_i];
  13149. request.abort();
  13150. }
  13151. };
  13152. // Loading screen
  13153. Engine.prototype.displayLoadingUI = function () {
  13154. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13155. return;
  13156. }
  13157. var loadingScreen = this.loadingScreen;
  13158. if (loadingScreen) {
  13159. loadingScreen.displayLoadingUI();
  13160. }
  13161. };
  13162. Engine.prototype.hideLoadingUI = function () {
  13163. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13164. return;
  13165. }
  13166. var loadingScreen = this.loadingScreen;
  13167. if (loadingScreen) {
  13168. loadingScreen.hideLoadingUI();
  13169. }
  13170. };
  13171. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13172. get: function () {
  13173. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13174. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13175. return this._loadingScreen;
  13176. },
  13177. set: function (loadingScreen) {
  13178. this._loadingScreen = loadingScreen;
  13179. },
  13180. enumerable: true,
  13181. configurable: true
  13182. });
  13183. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13184. set: function (text) {
  13185. this.loadingScreen.loadingUIText = text;
  13186. },
  13187. enumerable: true,
  13188. configurable: true
  13189. });
  13190. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13191. set: function (color) {
  13192. this.loadingScreen.loadingUIBackgroundColor = color;
  13193. },
  13194. enumerable: true,
  13195. configurable: true
  13196. });
  13197. Engine.prototype.attachContextLostEvent = function (callback) {
  13198. if (this._renderingCanvas) {
  13199. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13200. }
  13201. };
  13202. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13203. if (this._renderingCanvas) {
  13204. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13205. }
  13206. };
  13207. Engine.prototype.getVertexShaderSource = function (program) {
  13208. var shaders = this._gl.getAttachedShaders(program);
  13209. if (!shaders) {
  13210. return null;
  13211. }
  13212. return this._gl.getShaderSource(shaders[0]);
  13213. };
  13214. Engine.prototype.getFragmentShaderSource = function (program) {
  13215. var shaders = this._gl.getAttachedShaders(program);
  13216. if (!shaders) {
  13217. return null;
  13218. }
  13219. return this._gl.getShaderSource(shaders[1]);
  13220. };
  13221. Engine.prototype.getError = function () {
  13222. return this._gl.getError();
  13223. };
  13224. // FPS
  13225. Engine.prototype.getFps = function () {
  13226. return this._fps;
  13227. };
  13228. Engine.prototype.getDeltaTime = function () {
  13229. return this._deltaTime;
  13230. };
  13231. Engine.prototype._measureFps = function () {
  13232. this._performanceMonitor.sampleFrame();
  13233. this._fps = this._performanceMonitor.averageFPS;
  13234. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13235. };
  13236. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13237. if (faceIndex === void 0) { faceIndex = -1; }
  13238. var gl = this._gl;
  13239. if (!this._dummyFramebuffer) {
  13240. var dummy = gl.createFramebuffer();
  13241. if (!dummy) {
  13242. throw new Error("Unable to create dummy framebuffer");
  13243. }
  13244. this._dummyFramebuffer = dummy;
  13245. }
  13246. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13247. if (faceIndex > -1) {
  13248. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13249. }
  13250. else {
  13251. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13252. }
  13253. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13254. var buffer;
  13255. switch (readType) {
  13256. case gl.UNSIGNED_BYTE:
  13257. buffer = new Uint8Array(4 * width * height);
  13258. readType = gl.UNSIGNED_BYTE;
  13259. break;
  13260. default:
  13261. buffer = new Float32Array(4 * width * height);
  13262. readType = gl.FLOAT;
  13263. break;
  13264. }
  13265. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13266. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13267. return buffer;
  13268. };
  13269. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13270. if (this._webGLVersion > 1) {
  13271. return this._caps.colorBufferFloat;
  13272. }
  13273. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13274. };
  13275. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13276. if (this._webGLVersion > 1) {
  13277. return this._caps.colorBufferFloat;
  13278. }
  13279. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13280. };
  13281. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13282. Engine.prototype._canRenderToFramebuffer = function (type) {
  13283. var gl = this._gl;
  13284. //clear existing errors
  13285. while (gl.getError() !== gl.NO_ERROR) { }
  13286. var successful = true;
  13287. var texture = gl.createTexture();
  13288. gl.bindTexture(gl.TEXTURE_2D, texture);
  13289. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13292. var fb = gl.createFramebuffer();
  13293. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13294. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13295. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13296. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13297. successful = successful && (gl.getError() === gl.NO_ERROR);
  13298. //try render by clearing frame buffer's color buffer
  13299. if (successful) {
  13300. gl.clear(gl.COLOR_BUFFER_BIT);
  13301. successful = successful && (gl.getError() === gl.NO_ERROR);
  13302. }
  13303. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13304. if (successful) {
  13305. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13306. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13307. var readFormat = gl.RGBA;
  13308. var readType = gl.UNSIGNED_BYTE;
  13309. var buffer = new Uint8Array(4);
  13310. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13311. successful = successful && (gl.getError() === gl.NO_ERROR);
  13312. }
  13313. //clean up
  13314. gl.deleteTexture(texture);
  13315. gl.deleteFramebuffer(fb);
  13316. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13317. //clear accumulated errors
  13318. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13319. return successful;
  13320. };
  13321. Engine.prototype._getWebGLTextureType = function (type) {
  13322. if (type === Engine.TEXTURETYPE_FLOAT) {
  13323. return this._gl.FLOAT;
  13324. }
  13325. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13326. // Add Half Float Constant.
  13327. return this._gl.HALF_FLOAT_OES;
  13328. }
  13329. return this._gl.UNSIGNED_BYTE;
  13330. };
  13331. ;
  13332. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13333. if (this._webGLVersion === 1) {
  13334. return this._gl.RGBA;
  13335. }
  13336. if (type === Engine.TEXTURETYPE_FLOAT) {
  13337. return this._gl.RGBA32F;
  13338. }
  13339. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13340. return this._gl.RGBA16F;
  13341. }
  13342. return this._gl.RGBA;
  13343. };
  13344. ;
  13345. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13346. if (type === Engine.TEXTURETYPE_FLOAT) {
  13347. return this._gl.RGBA32F;
  13348. }
  13349. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13350. return this._gl.RGBA16F;
  13351. }
  13352. return this._gl.RGBA8;
  13353. };
  13354. ;
  13355. Engine.prototype.createQuery = function () {
  13356. return this._gl.createQuery();
  13357. };
  13358. Engine.prototype.deleteQuery = function (query) {
  13359. this._gl.deleteQuery(query);
  13360. return this;
  13361. };
  13362. Engine.prototype.isQueryResultAvailable = function (query) {
  13363. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13364. };
  13365. Engine.prototype.getQueryResult = function (query) {
  13366. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13367. };
  13368. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13369. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13370. this._gl.beginQuery(glAlgorithm, query);
  13371. return this;
  13372. };
  13373. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13374. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13375. this._gl.endQuery(glAlgorithm);
  13376. return this;
  13377. };
  13378. /* Time queries */
  13379. Engine.prototype._createTimeQuery = function () {
  13380. var timerQuery = this._caps.timerQuery;
  13381. if (timerQuery.createQueryEXT) {
  13382. return timerQuery.createQueryEXT();
  13383. }
  13384. return this.createQuery();
  13385. };
  13386. Engine.prototype._deleteTimeQuery = function (query) {
  13387. var timerQuery = this._caps.timerQuery;
  13388. if (timerQuery.deleteQueryEXT) {
  13389. timerQuery.deleteQueryEXT(query);
  13390. return;
  13391. }
  13392. this.deleteQuery(query);
  13393. };
  13394. Engine.prototype._getTimeQueryResult = function (query) {
  13395. var timerQuery = this._caps.timerQuery;
  13396. if (timerQuery.getQueryObjectEXT) {
  13397. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13398. }
  13399. return this.getQueryResult(query);
  13400. };
  13401. Engine.prototype._getTimeQueryAvailability = function (query) {
  13402. var timerQuery = this._caps.timerQuery;
  13403. if (timerQuery.getQueryObjectEXT) {
  13404. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13405. }
  13406. return this.isQueryResultAvailable(query);
  13407. };
  13408. Engine.prototype.startTimeQuery = function () {
  13409. var timerQuery = this._caps.timerQuery;
  13410. if (!timerQuery) {
  13411. return null;
  13412. }
  13413. var token = new BABYLON._TimeToken();
  13414. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13415. if (this._caps.canUseTimestampForTimerQuery) {
  13416. token._startTimeQuery = this._createTimeQuery();
  13417. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13418. }
  13419. else {
  13420. if (this._currentNonTimestampToken) {
  13421. return this._currentNonTimestampToken;
  13422. }
  13423. token._timeElapsedQuery = this._createTimeQuery();
  13424. if (timerQuery.beginQueryEXT) {
  13425. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13426. }
  13427. else {
  13428. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13429. }
  13430. this._currentNonTimestampToken = token;
  13431. }
  13432. return token;
  13433. };
  13434. Engine.prototype.endTimeQuery = function (token) {
  13435. var timerQuery = this._caps.timerQuery;
  13436. if (!timerQuery || !token) {
  13437. return -1;
  13438. }
  13439. if (this._caps.canUseTimestampForTimerQuery) {
  13440. if (!token._startTimeQuery) {
  13441. return -1;
  13442. }
  13443. if (!token._endTimeQuery) {
  13444. token._endTimeQuery = this._createTimeQuery();
  13445. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13446. }
  13447. }
  13448. else if (!token._timeElapsedQueryEnded) {
  13449. if (!token._timeElapsedQuery) {
  13450. return -1;
  13451. }
  13452. if (timerQuery.endQueryEXT) {
  13453. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13454. }
  13455. else {
  13456. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13457. }
  13458. token._timeElapsedQueryEnded = true;
  13459. }
  13460. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13461. var available = false;
  13462. if (token._endTimeQuery) {
  13463. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13464. }
  13465. else if (token._timeElapsedQuery) {
  13466. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13467. }
  13468. if (available && !disjoint) {
  13469. var result = 0;
  13470. if (this._caps.canUseTimestampForTimerQuery) {
  13471. if (!token._startTimeQuery || !token._endTimeQuery) {
  13472. return -1;
  13473. }
  13474. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13475. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13476. result = timeEnd - timeStart;
  13477. this._deleteTimeQuery(token._startTimeQuery);
  13478. this._deleteTimeQuery(token._endTimeQuery);
  13479. token._startTimeQuery = null;
  13480. token._endTimeQuery = null;
  13481. }
  13482. else {
  13483. if (!token._timeElapsedQuery) {
  13484. return -1;
  13485. }
  13486. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13487. this._deleteTimeQuery(token._timeElapsedQuery);
  13488. token._timeElapsedQuery = null;
  13489. token._timeElapsedQueryEnded = false;
  13490. this._currentNonTimestampToken = null;
  13491. }
  13492. return result;
  13493. }
  13494. return -1;
  13495. };
  13496. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13497. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13498. };
  13499. // Transform feedback
  13500. Engine.prototype.createTransformFeedback = function () {
  13501. return this._gl.createTransformFeedback();
  13502. };
  13503. Engine.prototype.deleteTransformFeedback = function (value) {
  13504. this._gl.deleteTransformFeedback(value);
  13505. };
  13506. Engine.prototype.bindTransformFeedback = function (value) {
  13507. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13508. };
  13509. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13510. if (usePoints === void 0) { usePoints = true; }
  13511. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13512. };
  13513. Engine.prototype.endTransformFeedback = function () {
  13514. this._gl.endTransformFeedback();
  13515. };
  13516. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13517. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13518. };
  13519. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13520. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13521. };
  13522. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13523. var _this = this;
  13524. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13525. this._activeRequests.push(request);
  13526. request.onCompleteObservable.add(function (request) {
  13527. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13528. });
  13529. return request;
  13530. };
  13531. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13532. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13533. var onload = function (data) {
  13534. loadedFiles[index] = data;
  13535. loadedFiles._internalCount++;
  13536. if (loadedFiles._internalCount === 6) {
  13537. onfinish(loadedFiles);
  13538. }
  13539. };
  13540. var onerror = function (request, exception) {
  13541. if (onErrorCallBack && request) {
  13542. onErrorCallBack(request.status + " " + request.statusText, exception);
  13543. }
  13544. };
  13545. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13546. };
  13547. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13548. if (onError === void 0) { onError = null; }
  13549. var loadedFiles = [];
  13550. loadedFiles._internalCount = 0;
  13551. for (var index = 0; index < 6; index++) {
  13552. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13553. }
  13554. };
  13555. // Statics
  13556. Engine.isSupported = function () {
  13557. try {
  13558. var tempcanvas = document.createElement("canvas");
  13559. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13560. return gl != null && !!window.WebGLRenderingContext;
  13561. }
  13562. catch (e) {
  13563. return false;
  13564. }
  13565. };
  13566. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13567. Engine.ExceptionList = [
  13568. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13569. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13570. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13571. ];
  13572. Engine.Instances = new Array();
  13573. // Const statics
  13574. Engine._ALPHA_DISABLE = 0;
  13575. Engine._ALPHA_ADD = 1;
  13576. Engine._ALPHA_COMBINE = 2;
  13577. Engine._ALPHA_SUBTRACT = 3;
  13578. Engine._ALPHA_MULTIPLY = 4;
  13579. Engine._ALPHA_MAXIMIZED = 5;
  13580. Engine._ALPHA_ONEONE = 6;
  13581. Engine._ALPHA_PREMULTIPLIED = 7;
  13582. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13583. Engine._ALPHA_INTERPOLATE = 9;
  13584. Engine._ALPHA_SCREENMODE = 10;
  13585. Engine._DELAYLOADSTATE_NONE = 0;
  13586. Engine._DELAYLOADSTATE_LOADED = 1;
  13587. Engine._DELAYLOADSTATE_LOADING = 2;
  13588. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13589. Engine._TEXTUREFORMAT_ALPHA = 0;
  13590. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13591. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13592. Engine._TEXTUREFORMAT_RGB = 4;
  13593. Engine._TEXTUREFORMAT_RGBA = 5;
  13594. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13595. Engine._TEXTURETYPE_FLOAT = 1;
  13596. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13597. // Depht or Stencil test Constants.
  13598. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13599. 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.
  13600. 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.
  13601. 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.
  13602. 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.
  13603. 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.
  13604. 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.
  13605. 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.
  13606. // Stencil Actions Constants.
  13607. Engine._KEEP = 0x1E00;
  13608. Engine._REPLACE = 0x1E01;
  13609. Engine._INCR = 0x1E02;
  13610. Engine._DECR = 0x1E03;
  13611. Engine._INVERT = 0x150A;
  13612. Engine._INCR_WRAP = 0x8507;
  13613. Engine._DECR_WRAP = 0x8508;
  13614. // Texture rescaling mode
  13615. Engine._SCALEMODE_FLOOR = 1;
  13616. Engine._SCALEMODE_NEAREST = 2;
  13617. Engine._SCALEMODE_CEILING = 3;
  13618. // Updatable statics so stick with vars here
  13619. Engine.CollisionsEpsilon = 0.001;
  13620. Engine.CodeRepository = "src/";
  13621. Engine.ShadersRepository = "src/Shaders/";
  13622. return Engine;
  13623. }());
  13624. BABYLON.Engine = Engine;
  13625. })(BABYLON || (BABYLON = {}));
  13626. //# sourceMappingURL=babylon.engine.js.map
  13627. var BABYLON;
  13628. (function (BABYLON) {
  13629. /**
  13630. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13631. */
  13632. var Node = /** @class */ (function () {
  13633. /**
  13634. * @constructor
  13635. * @param {string} name - the name and id to be given to this node
  13636. * @param {BABYLON.Scene} the scene this node will be added to
  13637. */
  13638. function Node(name, scene) {
  13639. if (scene === void 0) { scene = null; }
  13640. this.state = "";
  13641. this.metadata = null;
  13642. this.doNotSerialize = false;
  13643. this.animations = new Array();
  13644. this._ranges = {};
  13645. this._isEnabled = true;
  13646. this._isReady = true;
  13647. this._currentRenderId = -1;
  13648. this._parentRenderId = -1;
  13649. /**
  13650. * An event triggered when the mesh is disposed.
  13651. * @type {BABYLON.Observable}
  13652. */
  13653. this.onDisposeObservable = new BABYLON.Observable();
  13654. // Behaviors
  13655. this._behaviors = new Array();
  13656. this.name = name;
  13657. this.id = name;
  13658. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13659. this.uniqueId = this._scene.getUniqueId();
  13660. this._initCache();
  13661. }
  13662. Object.defineProperty(Node.prototype, "parent", {
  13663. get: function () {
  13664. return this._parentNode;
  13665. },
  13666. set: function (parent) {
  13667. if (this._parentNode === parent) {
  13668. return;
  13669. }
  13670. // Remove self from list of children of parent
  13671. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13672. var index = this._parentNode._children.indexOf(this);
  13673. if (index !== -1) {
  13674. this._parentNode._children.splice(index, 1);
  13675. }
  13676. }
  13677. // Store new parent
  13678. this._parentNode = parent;
  13679. // Add as child to new parent
  13680. if (this._parentNode) {
  13681. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13682. this._parentNode._children = new Array();
  13683. }
  13684. this._parentNode._children.push(this);
  13685. }
  13686. },
  13687. enumerable: true,
  13688. configurable: true
  13689. });
  13690. Node.prototype.getClassName = function () {
  13691. return "Node";
  13692. };
  13693. Object.defineProperty(Node.prototype, "onDispose", {
  13694. set: function (callback) {
  13695. if (this._onDisposeObserver) {
  13696. this.onDisposeObservable.remove(this._onDisposeObserver);
  13697. }
  13698. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13699. },
  13700. enumerable: true,
  13701. configurable: true
  13702. });
  13703. Node.prototype.getScene = function () {
  13704. return this._scene;
  13705. };
  13706. Node.prototype.getEngine = function () {
  13707. return this._scene.getEngine();
  13708. };
  13709. Node.prototype.addBehavior = function (behavior) {
  13710. var _this = this;
  13711. var index = this._behaviors.indexOf(behavior);
  13712. if (index !== -1) {
  13713. return this;
  13714. }
  13715. behavior.init();
  13716. if (this._scene.isLoading) {
  13717. // We defer the attach when the scene will be loaded
  13718. var observer = this._scene.onDataLoadedObservable.add(function () {
  13719. behavior.attach(_this);
  13720. setTimeout(function () {
  13721. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13722. _this._scene.onDataLoadedObservable.remove(observer);
  13723. }, 0);
  13724. });
  13725. }
  13726. else {
  13727. behavior.attach(this);
  13728. }
  13729. this._behaviors.push(behavior);
  13730. return this;
  13731. };
  13732. Node.prototype.removeBehavior = function (behavior) {
  13733. var index = this._behaviors.indexOf(behavior);
  13734. if (index === -1) {
  13735. return this;
  13736. }
  13737. this._behaviors[index].detach();
  13738. this._behaviors.splice(index, 1);
  13739. return this;
  13740. };
  13741. Object.defineProperty(Node.prototype, "behaviors", {
  13742. get: function () {
  13743. return this._behaviors;
  13744. },
  13745. enumerable: true,
  13746. configurable: true
  13747. });
  13748. Node.prototype.getBehaviorByName = function (name) {
  13749. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13750. var behavior = _a[_i];
  13751. if (behavior.name === name) {
  13752. return behavior;
  13753. }
  13754. }
  13755. return null;
  13756. };
  13757. // override it in derived class
  13758. Node.prototype.getWorldMatrix = function () {
  13759. return BABYLON.Matrix.Identity();
  13760. };
  13761. // override it in derived class if you add new variables to the cache
  13762. // and call the parent class method
  13763. Node.prototype._initCache = function () {
  13764. this._cache = {};
  13765. this._cache.parent = undefined;
  13766. };
  13767. Node.prototype.updateCache = function (force) {
  13768. if (!force && this.isSynchronized())
  13769. return;
  13770. this._cache.parent = this.parent;
  13771. this._updateCache();
  13772. };
  13773. // override it in derived class if you add new variables to the cache
  13774. // and call the parent class method if !ignoreParentClass
  13775. Node.prototype._updateCache = function (ignoreParentClass) {
  13776. };
  13777. // override it in derived class if you add new variables to the cache
  13778. Node.prototype._isSynchronized = function () {
  13779. return true;
  13780. };
  13781. Node.prototype._markSyncedWithParent = function () {
  13782. if (this.parent) {
  13783. this._parentRenderId = this.parent._currentRenderId;
  13784. }
  13785. };
  13786. Node.prototype.isSynchronizedWithParent = function () {
  13787. if (!this.parent) {
  13788. return true;
  13789. }
  13790. if (this._parentRenderId !== this.parent._currentRenderId) {
  13791. return false;
  13792. }
  13793. return this.parent.isSynchronized();
  13794. };
  13795. Node.prototype.isSynchronized = function (updateCache) {
  13796. var check = this.hasNewParent();
  13797. check = check || !this.isSynchronizedWithParent();
  13798. check = check || !this._isSynchronized();
  13799. if (updateCache)
  13800. this.updateCache(true);
  13801. return !check;
  13802. };
  13803. Node.prototype.hasNewParent = function (update) {
  13804. if (this._cache.parent === this.parent)
  13805. return false;
  13806. if (update)
  13807. this._cache.parent = this.parent;
  13808. return true;
  13809. };
  13810. /**
  13811. * Is this node ready to be used/rendered
  13812. * @return {boolean} is it ready
  13813. */
  13814. Node.prototype.isReady = function () {
  13815. return this._isReady;
  13816. };
  13817. /**
  13818. * Is this node enabled.
  13819. * 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.
  13820. * @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.
  13821. * @return {boolean} whether this node (and its parent) is enabled.
  13822. * @see setEnabled
  13823. */
  13824. Node.prototype.isEnabled = function (checkAncestors) {
  13825. if (checkAncestors === void 0) { checkAncestors = true; }
  13826. if (checkAncestors === false) {
  13827. return this._isEnabled;
  13828. }
  13829. if (this._isEnabled === false) {
  13830. return false;
  13831. }
  13832. if (this.parent !== undefined && this.parent !== null) {
  13833. return this.parent.isEnabled(checkAncestors);
  13834. }
  13835. return true;
  13836. };
  13837. /**
  13838. * Set the enabled state of this node.
  13839. * @param {boolean} value - the new enabled state
  13840. * @see isEnabled
  13841. */
  13842. Node.prototype.setEnabled = function (value) {
  13843. this._isEnabled = value;
  13844. };
  13845. /**
  13846. * Is this node a descendant of the given node.
  13847. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13848. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13849. * @see parent
  13850. */
  13851. Node.prototype.isDescendantOf = function (ancestor) {
  13852. if (this.parent) {
  13853. if (this.parent === ancestor) {
  13854. return true;
  13855. }
  13856. return this.parent.isDescendantOf(ancestor);
  13857. }
  13858. return false;
  13859. };
  13860. /**
  13861. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13862. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13863. * @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.
  13864. * @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.
  13865. */
  13866. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13867. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13868. if (!this._children) {
  13869. return;
  13870. }
  13871. for (var index = 0; index < this._children.length; index++) {
  13872. var item = this._children[index];
  13873. if (!predicate || predicate(item)) {
  13874. results.push(item);
  13875. }
  13876. if (!directDescendantsOnly) {
  13877. item._getDescendants(results, false, predicate);
  13878. }
  13879. }
  13880. };
  13881. /**
  13882. * Will return all nodes that have this node as ascendant.
  13883. * @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.
  13884. * @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.
  13885. * @return {BABYLON.Node[]} all children nodes of all types.
  13886. */
  13887. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13888. var results = new Array();
  13889. this._getDescendants(results, directDescendantsOnly, predicate);
  13890. return results;
  13891. };
  13892. /**
  13893. * Get all child-meshes of this node.
  13894. */
  13895. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13896. var results = [];
  13897. this._getDescendants(results, directDescendantsOnly, function (node) {
  13898. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13899. });
  13900. return results;
  13901. };
  13902. /**
  13903. * Get all child-transformNodes of this node.
  13904. */
  13905. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13906. var results = [];
  13907. this._getDescendants(results, directDescendantsOnly, function (node) {
  13908. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13909. });
  13910. return results;
  13911. };
  13912. /**
  13913. * Get all direct children of this node.
  13914. */
  13915. Node.prototype.getChildren = function (predicate) {
  13916. return this.getDescendants(true, predicate);
  13917. };
  13918. Node.prototype._setReady = function (state) {
  13919. if (state === this._isReady) {
  13920. return;
  13921. }
  13922. if (!state) {
  13923. this._isReady = false;
  13924. return;
  13925. }
  13926. this._isReady = true;
  13927. if (this.onReady) {
  13928. this.onReady(this);
  13929. }
  13930. };
  13931. Node.prototype.getAnimationByName = function (name) {
  13932. for (var i = 0; i < this.animations.length; i++) {
  13933. var animation = this.animations[i];
  13934. if (animation.name === name) {
  13935. return animation;
  13936. }
  13937. }
  13938. return null;
  13939. };
  13940. Node.prototype.createAnimationRange = function (name, from, to) {
  13941. // check name not already in use
  13942. if (!this._ranges[name]) {
  13943. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13945. if (this.animations[i]) {
  13946. this.animations[i].createRange(name, from, to);
  13947. }
  13948. }
  13949. }
  13950. };
  13951. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13952. if (deleteFrames === void 0) { deleteFrames = true; }
  13953. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13954. if (this.animations[i]) {
  13955. this.animations[i].deleteRange(name, deleteFrames);
  13956. }
  13957. }
  13958. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13959. };
  13960. Node.prototype.getAnimationRange = function (name) {
  13961. return this._ranges[name];
  13962. };
  13963. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13964. var range = this.getAnimationRange(name);
  13965. if (!range) {
  13966. return;
  13967. }
  13968. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13969. };
  13970. Node.prototype.serializeAnimationRanges = function () {
  13971. var serializationRanges = [];
  13972. for (var name in this._ranges) {
  13973. var localRange = this._ranges[name];
  13974. if (!localRange) {
  13975. continue;
  13976. }
  13977. var range = {};
  13978. range.name = name;
  13979. range.from = localRange.from;
  13980. range.to = localRange.to;
  13981. serializationRanges.push(range);
  13982. }
  13983. return serializationRanges;
  13984. };
  13985. // override it in derived class
  13986. Node.prototype.computeWorldMatrix = function (force) {
  13987. return BABYLON.Matrix.Identity();
  13988. };
  13989. Node.prototype.dispose = function () {
  13990. this.parent = null;
  13991. // Callback
  13992. this.onDisposeObservable.notifyObservers(this);
  13993. this.onDisposeObservable.clear();
  13994. // Behaviors
  13995. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13996. var behavior = _a[_i];
  13997. behavior.detach();
  13998. }
  13999. this._behaviors = [];
  14000. };
  14001. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14002. if (parsedNode.ranges) {
  14003. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14004. var data = parsedNode.ranges[index];
  14005. node.createAnimationRange(data.name, data.from, data.to);
  14006. }
  14007. }
  14008. };
  14009. __decorate([
  14010. BABYLON.serialize()
  14011. ], Node.prototype, "name", void 0);
  14012. __decorate([
  14013. BABYLON.serialize()
  14014. ], Node.prototype, "id", void 0);
  14015. __decorate([
  14016. BABYLON.serialize()
  14017. ], Node.prototype, "uniqueId", void 0);
  14018. __decorate([
  14019. BABYLON.serialize()
  14020. ], Node.prototype, "state", void 0);
  14021. __decorate([
  14022. BABYLON.serialize()
  14023. ], Node.prototype, "metadata", void 0);
  14024. return Node;
  14025. }());
  14026. BABYLON.Node = Node;
  14027. })(BABYLON || (BABYLON = {}));
  14028. //# sourceMappingURL=babylon.node.js.map
  14029. var BABYLON;
  14030. (function (BABYLON) {
  14031. var BoundingSphere = /** @class */ (function () {
  14032. function BoundingSphere(minimum, maximum) {
  14033. this.minimum = minimum;
  14034. this.maximum = maximum;
  14035. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14036. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14037. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14038. this.radius = distance * 0.5;
  14039. this.centerWorld = BABYLON.Vector3.Zero();
  14040. this._update(BABYLON.Matrix.Identity());
  14041. }
  14042. // Methods
  14043. BoundingSphere.prototype._update = function (world) {
  14044. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14045. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14046. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14047. };
  14048. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14049. for (var i = 0; i < 6; i++) {
  14050. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14051. return false;
  14052. }
  14053. return true;
  14054. };
  14055. BoundingSphere.prototype.intersectsPoint = function (point) {
  14056. var x = this.centerWorld.x - point.x;
  14057. var y = this.centerWorld.y - point.y;
  14058. var z = this.centerWorld.z - point.z;
  14059. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14060. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14061. return false;
  14062. return true;
  14063. };
  14064. // Statics
  14065. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14066. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14067. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14068. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14069. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14070. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14071. return false;
  14072. return true;
  14073. };
  14074. return BoundingSphere;
  14075. }());
  14076. BABYLON.BoundingSphere = BoundingSphere;
  14077. })(BABYLON || (BABYLON = {}));
  14078. //# sourceMappingURL=babylon.boundingSphere.js.map
  14079. var BABYLON;
  14080. (function (BABYLON) {
  14081. var BoundingBox = /** @class */ (function () {
  14082. function BoundingBox(minimum, maximum) {
  14083. this.minimum = minimum;
  14084. this.maximum = maximum;
  14085. this.vectors = new Array();
  14086. this.vectorsWorld = new Array();
  14087. // Bounding vectors
  14088. this.vectors.push(this.minimum.clone());
  14089. this.vectors.push(this.maximum.clone());
  14090. this.vectors.push(this.minimum.clone());
  14091. this.vectors[2].x = this.maximum.x;
  14092. this.vectors.push(this.minimum.clone());
  14093. this.vectors[3].y = this.maximum.y;
  14094. this.vectors.push(this.minimum.clone());
  14095. this.vectors[4].z = this.maximum.z;
  14096. this.vectors.push(this.maximum.clone());
  14097. this.vectors[5].z = this.minimum.z;
  14098. this.vectors.push(this.maximum.clone());
  14099. this.vectors[6].x = this.minimum.x;
  14100. this.vectors.push(this.maximum.clone());
  14101. this.vectors[7].y = this.minimum.y;
  14102. // OBB
  14103. this.center = this.maximum.add(this.minimum).scale(0.5);
  14104. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14105. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14106. // World
  14107. for (var index = 0; index < this.vectors.length; index++) {
  14108. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14109. }
  14110. this.minimumWorld = BABYLON.Vector3.Zero();
  14111. this.maximumWorld = BABYLON.Vector3.Zero();
  14112. this.centerWorld = BABYLON.Vector3.Zero();
  14113. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14114. this._update(BABYLON.Matrix.Identity());
  14115. }
  14116. // Methods
  14117. BoundingBox.prototype.getWorldMatrix = function () {
  14118. return this._worldMatrix;
  14119. };
  14120. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14121. this._worldMatrix.copyFrom(matrix);
  14122. return this;
  14123. };
  14124. BoundingBox.prototype._update = function (world) {
  14125. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14126. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14127. for (var index = 0; index < this.vectors.length; index++) {
  14128. var v = this.vectorsWorld[index];
  14129. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14130. if (v.x < this.minimumWorld.x)
  14131. this.minimumWorld.x = v.x;
  14132. if (v.y < this.minimumWorld.y)
  14133. this.minimumWorld.y = v.y;
  14134. if (v.z < this.minimumWorld.z)
  14135. this.minimumWorld.z = v.z;
  14136. if (v.x > this.maximumWorld.x)
  14137. this.maximumWorld.x = v.x;
  14138. if (v.y > this.maximumWorld.y)
  14139. this.maximumWorld.y = v.y;
  14140. if (v.z > this.maximumWorld.z)
  14141. this.maximumWorld.z = v.z;
  14142. }
  14143. // Extend
  14144. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14145. this.extendSizeWorld.scaleInPlace(0.5);
  14146. // OBB
  14147. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14148. this.centerWorld.scaleInPlace(0.5);
  14149. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14150. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14151. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14152. this._worldMatrix = world;
  14153. };
  14154. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14155. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14156. };
  14157. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14158. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14159. };
  14160. BoundingBox.prototype.intersectsPoint = function (point) {
  14161. var delta = -BABYLON.Epsilon;
  14162. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14163. return false;
  14164. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14165. return false;
  14166. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14167. return false;
  14168. return true;
  14169. };
  14170. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14171. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14172. };
  14173. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14174. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14175. return false;
  14176. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14177. return false;
  14178. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14179. return false;
  14180. return true;
  14181. };
  14182. // Statics
  14183. BoundingBox.Intersects = function (box0, box1) {
  14184. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14185. return false;
  14186. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14187. return false;
  14188. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14189. return false;
  14190. return true;
  14191. };
  14192. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14193. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14194. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14195. return (num <= (sphereRadius * sphereRadius));
  14196. };
  14197. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14198. for (var p = 0; p < 6; p++) {
  14199. for (var i = 0; i < 8; i++) {
  14200. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14201. return false;
  14202. }
  14203. }
  14204. }
  14205. return true;
  14206. };
  14207. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14208. for (var p = 0; p < 6; p++) {
  14209. var inCount = 8;
  14210. for (var i = 0; i < 8; i++) {
  14211. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14212. --inCount;
  14213. }
  14214. else {
  14215. break;
  14216. }
  14217. }
  14218. if (inCount === 0)
  14219. return false;
  14220. }
  14221. return true;
  14222. };
  14223. return BoundingBox;
  14224. }());
  14225. BABYLON.BoundingBox = BoundingBox;
  14226. })(BABYLON || (BABYLON = {}));
  14227. //# sourceMappingURL=babylon.boundingBox.js.map
  14228. var BABYLON;
  14229. (function (BABYLON) {
  14230. var computeBoxExtents = function (axis, box) {
  14231. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14232. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14233. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14234. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14235. var r = r0 + r1 + r2;
  14236. return {
  14237. min: p - r,
  14238. max: p + r
  14239. };
  14240. };
  14241. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14242. var axisOverlap = function (axis, box0, box1) {
  14243. var result0 = computeBoxExtents(axis, box0);
  14244. var result1 = computeBoxExtents(axis, box1);
  14245. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14246. };
  14247. var BoundingInfo = /** @class */ (function () {
  14248. function BoundingInfo(minimum, maximum) {
  14249. this.minimum = minimum;
  14250. this.maximum = maximum;
  14251. this._isLocked = false;
  14252. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14253. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14254. }
  14255. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14256. get: function () {
  14257. return this._isLocked;
  14258. },
  14259. set: function (value) {
  14260. this._isLocked = value;
  14261. },
  14262. enumerable: true,
  14263. configurable: true
  14264. });
  14265. // Methods
  14266. BoundingInfo.prototype.update = function (world) {
  14267. if (this._isLocked) {
  14268. return;
  14269. }
  14270. this.boundingBox._update(world);
  14271. this.boundingSphere._update(world);
  14272. };
  14273. /**
  14274. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14275. * @param center New center of the bounding info
  14276. * @param extend New extend of the bounding info
  14277. */
  14278. BoundingInfo.prototype.centerOn = function (center, extend) {
  14279. this.minimum = center.subtract(extend);
  14280. this.maximum = center.add(extend);
  14281. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14282. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14283. return this;
  14284. };
  14285. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14286. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14287. return false;
  14288. return this.boundingBox.isInFrustum(frustumPlanes);
  14289. };
  14290. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14291. /**
  14292. * Gets the world distance between the min and max points of the bounding box
  14293. */
  14294. get: function () {
  14295. var boundingBox = this.boundingBox;
  14296. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14297. return size.length();
  14298. },
  14299. enumerable: true,
  14300. configurable: true
  14301. });
  14302. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14303. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14304. };
  14305. BoundingInfo.prototype._checkCollision = function (collider) {
  14306. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14307. };
  14308. BoundingInfo.prototype.intersectsPoint = function (point) {
  14309. if (!this.boundingSphere.centerWorld) {
  14310. return false;
  14311. }
  14312. if (!this.boundingSphere.intersectsPoint(point)) {
  14313. return false;
  14314. }
  14315. if (!this.boundingBox.intersectsPoint(point)) {
  14316. return false;
  14317. }
  14318. return true;
  14319. };
  14320. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14321. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14322. return false;
  14323. }
  14324. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14325. return false;
  14326. }
  14327. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14328. return false;
  14329. }
  14330. if (!precise) {
  14331. return true;
  14332. }
  14333. var box0 = this.boundingBox;
  14334. var box1 = boundingInfo.boundingBox;
  14335. if (!axisOverlap(box0.directions[0], box0, box1))
  14336. return false;
  14337. if (!axisOverlap(box0.directions[1], box0, box1))
  14338. return false;
  14339. if (!axisOverlap(box0.directions[2], box0, box1))
  14340. return false;
  14341. if (!axisOverlap(box1.directions[0], box0, box1))
  14342. return false;
  14343. if (!axisOverlap(box1.directions[1], box0, box1))
  14344. return false;
  14345. if (!axisOverlap(box1.directions[2], box0, box1))
  14346. return false;
  14347. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14348. return false;
  14349. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14350. return false;
  14351. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14352. return false;
  14353. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14354. return false;
  14355. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14356. return false;
  14357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14358. return false;
  14359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14360. return false;
  14361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14362. return false;
  14363. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14364. return false;
  14365. return true;
  14366. };
  14367. return BoundingInfo;
  14368. }());
  14369. BABYLON.BoundingInfo = BoundingInfo;
  14370. })(BABYLON || (BABYLON = {}));
  14371. //# sourceMappingURL=babylon.boundingInfo.js.map
  14372. var BABYLON;
  14373. (function (BABYLON) {
  14374. var TransformNode = /** @class */ (function (_super) {
  14375. __extends(TransformNode, _super);
  14376. function TransformNode(name, scene, isPure) {
  14377. if (scene === void 0) { scene = null; }
  14378. if (isPure === void 0) { isPure = true; }
  14379. var _this = _super.call(this, name, scene) || this;
  14380. // Properties
  14381. _this._rotation = BABYLON.Vector3.Zero();
  14382. _this._scaling = BABYLON.Vector3.One();
  14383. _this._isDirty = false;
  14384. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14385. _this.scalingDeterminant = 1;
  14386. _this.infiniteDistance = false;
  14387. _this.position = BABYLON.Vector3.Zero();
  14388. _this._localWorld = BABYLON.Matrix.Zero();
  14389. _this._worldMatrix = BABYLON.Matrix.Zero();
  14390. _this._worldMatrixDeterminant = 0;
  14391. _this._absolutePosition = BABYLON.Vector3.Zero();
  14392. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14393. _this._postMultiplyPivotMatrix = false;
  14394. _this._isWorldMatrixFrozen = false;
  14395. /**
  14396. * An event triggered after the world matrix is updated
  14397. * @type {BABYLON.Observable}
  14398. */
  14399. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14400. _this._nonUniformScaling = false;
  14401. if (isPure) {
  14402. _this.getScene().addTransformNode(_this);
  14403. }
  14404. return _this;
  14405. }
  14406. Object.defineProperty(TransformNode.prototype, "rotation", {
  14407. /**
  14408. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14409. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14410. * Default : (0.0, 0.0, 0.0)
  14411. */
  14412. get: function () {
  14413. return this._rotation;
  14414. },
  14415. set: function (newRotation) {
  14416. this._rotation = newRotation;
  14417. },
  14418. enumerable: true,
  14419. configurable: true
  14420. });
  14421. Object.defineProperty(TransformNode.prototype, "scaling", {
  14422. /**
  14423. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14424. * Default : (1.0, 1.0, 1.0)
  14425. */
  14426. get: function () {
  14427. return this._scaling;
  14428. },
  14429. /**
  14430. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14431. * Default : (1.0, 1.0, 1.0)
  14432. */
  14433. set: function (newScaling) {
  14434. this._scaling = newScaling;
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14440. /**
  14441. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14442. * It's null by default.
  14443. * 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)
  14444. */
  14445. get: function () {
  14446. return this._rotationQuaternion;
  14447. },
  14448. set: function (quaternion) {
  14449. this._rotationQuaternion = quaternion;
  14450. //reset the rotation vector.
  14451. if (quaternion && this.rotation.length()) {
  14452. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14453. }
  14454. },
  14455. enumerable: true,
  14456. configurable: true
  14457. });
  14458. /**
  14459. * Returns the latest update of the World matrix
  14460. * Returns a Matrix.
  14461. */
  14462. TransformNode.prototype.getWorldMatrix = function () {
  14463. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14464. this.computeWorldMatrix();
  14465. }
  14466. return this._worldMatrix;
  14467. };
  14468. /**
  14469. * Returns the latest update of the World matrix determinant.
  14470. */
  14471. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14472. return this._worldMatrixDeterminant;
  14473. };
  14474. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14475. /**
  14476. * Returns directly the latest state of the mesh World matrix.
  14477. * A Matrix is returned.
  14478. */
  14479. get: function () {
  14480. return this._worldMatrix;
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. /**
  14486. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14487. * Returns the AbstractMesh.
  14488. */
  14489. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14490. this._poseMatrix.copyFrom(matrix);
  14491. return this;
  14492. };
  14493. /**
  14494. * Returns the mesh Pose matrix.
  14495. * Returned object : Matrix
  14496. */
  14497. TransformNode.prototype.getPoseMatrix = function () {
  14498. return this._poseMatrix;
  14499. };
  14500. TransformNode.prototype._isSynchronized = function () {
  14501. if (this._isDirty) {
  14502. return false;
  14503. }
  14504. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14505. return false;
  14506. if (this._cache.pivotMatrixUpdated) {
  14507. return false;
  14508. }
  14509. if (this.infiniteDistance) {
  14510. return false;
  14511. }
  14512. if (!this._cache.position.equals(this.position))
  14513. return false;
  14514. if (this.rotationQuaternion) {
  14515. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14516. return false;
  14517. }
  14518. if (!this._cache.rotation.equals(this.rotation))
  14519. return false;
  14520. if (!this._cache.scaling.equals(this.scaling))
  14521. return false;
  14522. return true;
  14523. };
  14524. TransformNode.prototype._initCache = function () {
  14525. _super.prototype._initCache.call(this);
  14526. this._cache.localMatrixUpdated = false;
  14527. this._cache.position = BABYLON.Vector3.Zero();
  14528. this._cache.scaling = BABYLON.Vector3.Zero();
  14529. this._cache.rotation = BABYLON.Vector3.Zero();
  14530. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14531. this._cache.billboardMode = -1;
  14532. };
  14533. TransformNode.prototype.markAsDirty = function (property) {
  14534. if (property === "rotation") {
  14535. this.rotationQuaternion = null;
  14536. }
  14537. this._currentRenderId = Number.MAX_VALUE;
  14538. this._isDirty = true;
  14539. return this;
  14540. };
  14541. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14542. /**
  14543. * Returns the current mesh absolute position.
  14544. * Retuns a Vector3.
  14545. */
  14546. get: function () {
  14547. return this._absolutePosition;
  14548. },
  14549. enumerable: true,
  14550. configurable: true
  14551. });
  14552. /**
  14553. * Sets a new pivot matrix to the mesh.
  14554. * Returns the AbstractMesh.
  14555. */
  14556. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14557. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14558. this._pivotMatrix = matrix.clone();
  14559. this._cache.pivotMatrixUpdated = true;
  14560. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14561. if (this._postMultiplyPivotMatrix) {
  14562. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14563. }
  14564. return this;
  14565. };
  14566. /**
  14567. * Returns the mesh pivot matrix.
  14568. * Default : Identity.
  14569. * A Matrix is returned.
  14570. */
  14571. TransformNode.prototype.getPivotMatrix = function () {
  14572. return this._pivotMatrix;
  14573. };
  14574. /**
  14575. * Prevents the World matrix to be computed any longer.
  14576. * Returns the AbstractMesh.
  14577. */
  14578. TransformNode.prototype.freezeWorldMatrix = function () {
  14579. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14580. this.computeWorldMatrix(true);
  14581. this._isWorldMatrixFrozen = true;
  14582. return this;
  14583. };
  14584. /**
  14585. * Allows back the World matrix computation.
  14586. * Returns the AbstractMesh.
  14587. */
  14588. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14589. this._isWorldMatrixFrozen = false;
  14590. this.computeWorldMatrix(true);
  14591. return this;
  14592. };
  14593. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14594. /**
  14595. * True if the World matrix has been frozen.
  14596. * Returns a boolean.
  14597. */
  14598. get: function () {
  14599. return this._isWorldMatrixFrozen;
  14600. },
  14601. enumerable: true,
  14602. configurable: true
  14603. });
  14604. /**
  14605. * Retuns the mesh absolute position in the World.
  14606. * Returns a Vector3.
  14607. */
  14608. TransformNode.prototype.getAbsolutePosition = function () {
  14609. this.computeWorldMatrix();
  14610. return this._absolutePosition;
  14611. };
  14612. /**
  14613. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14614. * Returns the AbstractMesh.
  14615. */
  14616. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14617. if (!absolutePosition) {
  14618. return this;
  14619. }
  14620. var absolutePositionX;
  14621. var absolutePositionY;
  14622. var absolutePositionZ;
  14623. if (absolutePosition.x === undefined) {
  14624. if (arguments.length < 3) {
  14625. return this;
  14626. }
  14627. absolutePositionX = arguments[0];
  14628. absolutePositionY = arguments[1];
  14629. absolutePositionZ = arguments[2];
  14630. }
  14631. else {
  14632. absolutePositionX = absolutePosition.x;
  14633. absolutePositionY = absolutePosition.y;
  14634. absolutePositionZ = absolutePosition.z;
  14635. }
  14636. if (this.parent) {
  14637. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14638. invertParentWorldMatrix.invert();
  14639. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14640. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14641. }
  14642. else {
  14643. this.position.x = absolutePositionX;
  14644. this.position.y = absolutePositionY;
  14645. this.position.z = absolutePositionZ;
  14646. }
  14647. return this;
  14648. };
  14649. /**
  14650. * Sets the mesh position in its local space.
  14651. * Returns the AbstractMesh.
  14652. */
  14653. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14654. this.computeWorldMatrix();
  14655. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14656. return this;
  14657. };
  14658. /**
  14659. * Returns the mesh position in the local space from the current World matrix values.
  14660. * Returns a new Vector3.
  14661. */
  14662. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14663. this.computeWorldMatrix();
  14664. var invLocalWorldMatrix = this._localWorld.clone();
  14665. invLocalWorldMatrix.invert();
  14666. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14667. };
  14668. /**
  14669. * Translates the mesh along the passed Vector3 in its local space.
  14670. * Returns the AbstractMesh.
  14671. */
  14672. TransformNode.prototype.locallyTranslate = function (vector3) {
  14673. this.computeWorldMatrix(true);
  14674. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14675. return this;
  14676. };
  14677. /**
  14678. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14679. * @param targetPoint the position (must be in same space as current mesh) to look at
  14680. * @param yawCor optional yaw (y-axis) correction in radians
  14681. * @param pitchCor optional pitch (x-axis) correction in radians
  14682. * @param rollCor optional roll (z-axis) correction in radians
  14683. * @param space the choosen space of the target
  14684. * @returns the TransformNode.
  14685. */
  14686. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14687. if (yawCor === void 0) { yawCor = 0; }
  14688. if (pitchCor === void 0) { pitchCor = 0; }
  14689. if (rollCor === void 0) { rollCor = 0; }
  14690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14691. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14692. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14693. targetPoint.subtractToRef(pos, dv);
  14694. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14695. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14696. var pitch = Math.atan2(dv.y, len);
  14697. if (this.rotationQuaternion) {
  14698. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14699. }
  14700. else {
  14701. this.rotation.x = pitch + pitchCor;
  14702. this.rotation.y = yaw + yawCor;
  14703. this.rotation.z = rollCor;
  14704. }
  14705. return this;
  14706. };
  14707. /**
  14708. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14709. * This Vector3 is expressed in the World space.
  14710. */
  14711. TransformNode.prototype.getDirection = function (localAxis) {
  14712. var result = BABYLON.Vector3.Zero();
  14713. this.getDirectionToRef(localAxis, result);
  14714. return result;
  14715. };
  14716. /**
  14717. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14718. * localAxis is expressed in the mesh local space.
  14719. * result is computed in the Wordl space from the mesh World matrix.
  14720. * Returns the AbstractMesh.
  14721. */
  14722. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14723. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14724. return this;
  14725. };
  14726. TransformNode.prototype.setPivotPoint = function (point, space) {
  14727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14728. if (this.getScene().getRenderId() == 0) {
  14729. this.computeWorldMatrix(true);
  14730. }
  14731. var wm = this.getWorldMatrix();
  14732. if (space == BABYLON.Space.WORLD) {
  14733. var tmat = BABYLON.Tmp.Matrix[0];
  14734. wm.invertToRef(tmat);
  14735. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14736. }
  14737. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14738. this._pivotMatrix.m[12] = -point.x;
  14739. this._pivotMatrix.m[13] = -point.y;
  14740. this._pivotMatrix.m[14] = -point.z;
  14741. this._cache.pivotMatrixUpdated = true;
  14742. return this;
  14743. };
  14744. /**
  14745. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14746. */
  14747. TransformNode.prototype.getPivotPoint = function () {
  14748. var point = BABYLON.Vector3.Zero();
  14749. this.getPivotPointToRef(point);
  14750. return point;
  14751. };
  14752. /**
  14753. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14754. * Returns the AbstractMesh.
  14755. */
  14756. TransformNode.prototype.getPivotPointToRef = function (result) {
  14757. result.x = -this._pivotMatrix.m[12];
  14758. result.y = -this._pivotMatrix.m[13];
  14759. result.z = -this._pivotMatrix.m[14];
  14760. return this;
  14761. };
  14762. /**
  14763. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14764. */
  14765. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14766. var point = BABYLON.Vector3.Zero();
  14767. this.getAbsolutePivotPointToRef(point);
  14768. return point;
  14769. };
  14770. /**
  14771. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14772. * Returns the AbstractMesh.
  14773. */
  14774. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14775. result.x = this._pivotMatrix.m[12];
  14776. result.y = this._pivotMatrix.m[13];
  14777. result.z = this._pivotMatrix.m[14];
  14778. this.getPivotPointToRef(result);
  14779. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14780. return this;
  14781. };
  14782. /**
  14783. * Defines the passed node as the parent of the current node.
  14784. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14785. * Returns the TransformNode.
  14786. */
  14787. TransformNode.prototype.setParent = function (node) {
  14788. if (node === null) {
  14789. var rotation = BABYLON.Tmp.Quaternion[0];
  14790. var position = BABYLON.Tmp.Vector3[0];
  14791. var scale = BABYLON.Tmp.Vector3[1];
  14792. if (this.parent && this.parent.computeWorldMatrix) {
  14793. this.parent.computeWorldMatrix(true);
  14794. }
  14795. this.computeWorldMatrix(true);
  14796. this.getWorldMatrix().decompose(scale, rotation, position);
  14797. if (this.rotationQuaternion) {
  14798. this.rotationQuaternion.copyFrom(rotation);
  14799. }
  14800. else {
  14801. rotation.toEulerAnglesToRef(this.rotation);
  14802. }
  14803. this.scaling.x = scale.x;
  14804. this.scaling.y = scale.y;
  14805. this.scaling.z = scale.z;
  14806. this.position.x = position.x;
  14807. this.position.y = position.y;
  14808. this.position.z = position.z;
  14809. }
  14810. else {
  14811. var rotation = BABYLON.Tmp.Quaternion[0];
  14812. var position = BABYLON.Tmp.Vector3[0];
  14813. var scale = BABYLON.Tmp.Vector3[1];
  14814. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14815. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14816. this.computeWorldMatrix(true);
  14817. node.computeWorldMatrix(true);
  14818. node.getWorldMatrix().invertToRef(invParentMatrix);
  14819. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14820. diffMatrix.decompose(scale, rotation, position);
  14821. if (this.rotationQuaternion) {
  14822. this.rotationQuaternion.copyFrom(rotation);
  14823. }
  14824. else {
  14825. rotation.toEulerAnglesToRef(this.rotation);
  14826. }
  14827. this.position.x = position.x;
  14828. this.position.y = position.y;
  14829. this.position.z = position.z;
  14830. this.scaling.x = scale.x;
  14831. this.scaling.y = scale.y;
  14832. this.scaling.z = scale.z;
  14833. }
  14834. this.parent = node;
  14835. return this;
  14836. };
  14837. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14838. get: function () {
  14839. return this._nonUniformScaling;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14845. if (this._nonUniformScaling === value) {
  14846. return false;
  14847. }
  14848. this._nonUniformScaling = true;
  14849. return true;
  14850. };
  14851. /**
  14852. * Attach the current TransformNode to another TransformNode associated with a bone
  14853. * @param bone Bone affecting the TransformNode
  14854. * @param affectedTransformNode TransformNode associated with the bone
  14855. */
  14856. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14857. this._transformToBoneReferal = affectedTransformNode;
  14858. this.parent = bone;
  14859. if (bone.getWorldMatrix().determinant() < 0) {
  14860. this.scalingDeterminant *= -1;
  14861. }
  14862. return this;
  14863. };
  14864. TransformNode.prototype.detachFromBone = function () {
  14865. if (!this.parent) {
  14866. return this;
  14867. }
  14868. if (this.parent.getWorldMatrix().determinant() < 0) {
  14869. this.scalingDeterminant *= -1;
  14870. }
  14871. this._transformToBoneReferal = null;
  14872. this.parent = null;
  14873. return this;
  14874. };
  14875. /**
  14876. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14877. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14878. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14879. * The passed axis is also normalized.
  14880. * Returns the AbstractMesh.
  14881. */
  14882. TransformNode.prototype.rotate = function (axis, amount, space) {
  14883. axis.normalize();
  14884. if (!this.rotationQuaternion) {
  14885. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14886. this.rotation = BABYLON.Vector3.Zero();
  14887. }
  14888. var rotationQuaternion;
  14889. if (!space || space === BABYLON.Space.LOCAL) {
  14890. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14891. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14892. }
  14893. else {
  14894. if (this.parent) {
  14895. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14896. invertParentWorldMatrix.invert();
  14897. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14898. }
  14899. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14900. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14901. }
  14902. return this;
  14903. };
  14904. /**
  14905. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14906. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14907. * The passed axis is also normalized.
  14908. * Returns the AbstractMesh.
  14909. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14910. */
  14911. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14912. axis.normalize();
  14913. if (!this.rotationQuaternion) {
  14914. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14915. this.rotation.copyFromFloats(0, 0, 0);
  14916. }
  14917. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14918. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14919. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14920. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14921. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14922. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14923. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14924. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14925. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14926. return this;
  14927. };
  14928. /**
  14929. * Translates the mesh along the axis vector for the passed distance in the given space.
  14930. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14931. * Returns the AbstractMesh.
  14932. */
  14933. TransformNode.prototype.translate = function (axis, distance, space) {
  14934. var displacementVector = axis.scale(distance);
  14935. if (!space || space === BABYLON.Space.LOCAL) {
  14936. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14937. this.setPositionWithLocalVector(tempV3);
  14938. }
  14939. else {
  14940. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14941. }
  14942. return this;
  14943. };
  14944. /**
  14945. * Adds a rotation step to the mesh current rotation.
  14946. * x, y, z are Euler angles expressed in radians.
  14947. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14948. * This means this rotation is made in the mesh local space only.
  14949. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14950. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14951. * ```javascript
  14952. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14953. * ```
  14954. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14955. * 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.
  14956. * Returns the AbstractMesh.
  14957. */
  14958. TransformNode.prototype.addRotation = function (x, y, z) {
  14959. var rotationQuaternion;
  14960. if (this.rotationQuaternion) {
  14961. rotationQuaternion = this.rotationQuaternion;
  14962. }
  14963. else {
  14964. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14965. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14966. }
  14967. var accumulation = BABYLON.Tmp.Quaternion[0];
  14968. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14969. rotationQuaternion.multiplyInPlace(accumulation);
  14970. if (!this.rotationQuaternion) {
  14971. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14972. }
  14973. return this;
  14974. };
  14975. /**
  14976. * Computes the mesh World matrix and returns it.
  14977. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14978. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14979. * If the parameter `force`is set to `true`, the actual computation is done.
  14980. * Returns the mesh World Matrix.
  14981. */
  14982. TransformNode.prototype.computeWorldMatrix = function (force) {
  14983. if (this._isWorldMatrixFrozen) {
  14984. return this._worldMatrix;
  14985. }
  14986. if (!force && this.isSynchronized(true)) {
  14987. return this._worldMatrix;
  14988. }
  14989. this._cache.position.copyFrom(this.position);
  14990. this._cache.scaling.copyFrom(this.scaling);
  14991. this._cache.pivotMatrixUpdated = false;
  14992. this._cache.billboardMode = this.billboardMode;
  14993. this._currentRenderId = this.getScene().getRenderId();
  14994. this._isDirty = false;
  14995. // Scaling
  14996. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14997. // Rotation
  14998. //rotate, if quaternion is set and rotation was used
  14999. if (this.rotationQuaternion) {
  15000. var len = this.rotation.length();
  15001. if (len) {
  15002. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15003. this.rotation.copyFromFloats(0, 0, 0);
  15004. }
  15005. }
  15006. if (this.rotationQuaternion) {
  15007. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15008. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15009. }
  15010. else {
  15011. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15012. this._cache.rotation.copyFrom(this.rotation);
  15013. }
  15014. // Translation
  15015. var camera = this.getScene().activeCamera;
  15016. if (this.infiniteDistance && !this.parent && camera) {
  15017. var cameraWorldMatrix = camera.getWorldMatrix();
  15018. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15019. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15020. }
  15021. else {
  15022. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15023. }
  15024. // Composing transformations
  15025. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15026. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15027. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15028. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15029. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15030. // Need to decompose each rotation here
  15031. var currentPosition = BABYLON.Tmp.Vector3[3];
  15032. if (this.parent && this.parent.getWorldMatrix) {
  15033. if (this._transformToBoneReferal) {
  15034. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15035. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15036. }
  15037. else {
  15038. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15039. }
  15040. }
  15041. else {
  15042. currentPosition.copyFrom(this.position);
  15043. }
  15044. currentPosition.subtractInPlace(camera.globalPosition);
  15045. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15046. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15047. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15048. }
  15049. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15050. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15051. }
  15052. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15053. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15054. }
  15055. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15056. }
  15057. else {
  15058. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15059. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15060. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15061. }
  15062. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15063. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15064. }
  15065. // Local world
  15066. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15067. // Parent
  15068. if (this.parent && this.parent.getWorldMatrix) {
  15069. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15070. if (this._transformToBoneReferal) {
  15071. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15072. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15073. }
  15074. else {
  15075. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15076. }
  15077. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15078. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15079. this._worldMatrix.copyFrom(this._localWorld);
  15080. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15081. }
  15082. else {
  15083. if (this._transformToBoneReferal) {
  15084. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15085. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15086. }
  15087. else {
  15088. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15089. }
  15090. }
  15091. this._markSyncedWithParent();
  15092. }
  15093. else {
  15094. this._worldMatrix.copyFrom(this._localWorld);
  15095. }
  15096. // Post multiply inverse of pivotMatrix
  15097. if (this._postMultiplyPivotMatrix) {
  15098. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15099. }
  15100. // Normal matrix
  15101. if (this.scaling.isNonUniform) {
  15102. this._updateNonUniformScalingState(true);
  15103. }
  15104. else if (this.parent && this.parent._nonUniformScaling) {
  15105. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15106. }
  15107. else {
  15108. this._updateNonUniformScalingState(false);
  15109. }
  15110. this._afterComputeWorldMatrix();
  15111. // Absolute position
  15112. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15113. // Callbacks
  15114. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15115. if (!this._poseMatrix) {
  15116. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15117. }
  15118. // Cache the determinant
  15119. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15120. return this._worldMatrix;
  15121. };
  15122. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15123. };
  15124. /**
  15125. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15126. * @param func: callback function to add
  15127. *
  15128. * Returns the TransformNode.
  15129. */
  15130. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15131. this.onAfterWorldMatrixUpdateObservable.add(func);
  15132. return this;
  15133. };
  15134. /**
  15135. * Removes a registered callback function.
  15136. * Returns the TransformNode.
  15137. */
  15138. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15139. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15140. return this;
  15141. };
  15142. /**
  15143. * Clone the current transform node
  15144. * Returns the new transform node
  15145. * @param name Name of the new clone
  15146. * @param newParent New parent for the clone
  15147. * @param doNotCloneChildren Do not clone children hierarchy
  15148. */
  15149. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15150. var _this = this;
  15151. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15152. result.name = name;
  15153. result.id = name;
  15154. if (newParent) {
  15155. result.parent = newParent;
  15156. }
  15157. if (!doNotCloneChildren) {
  15158. // Children
  15159. var directDescendants = this.getDescendants(true);
  15160. for (var index = 0; index < directDescendants.length; index++) {
  15161. var child = directDescendants[index];
  15162. if (child.clone) {
  15163. child.clone(name + "." + child.name, result);
  15164. }
  15165. }
  15166. }
  15167. return result;
  15168. };
  15169. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15170. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15171. serializationObject.type = this.getClassName();
  15172. // Parent
  15173. if (this.parent) {
  15174. serializationObject.parentId = this.parent.id;
  15175. }
  15176. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15177. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15178. }
  15179. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15180. serializationObject.isEnabled = this.isEnabled();
  15181. // Parent
  15182. if (this.parent) {
  15183. serializationObject.parentId = this.parent.id;
  15184. }
  15185. return serializationObject;
  15186. };
  15187. // Statics
  15188. /**
  15189. * Returns a new TransformNode object parsed from the source provided.
  15190. * The parameter `parsedMesh` is the source.
  15191. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15192. */
  15193. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15194. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15195. if (BABYLON.Tags) {
  15196. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15197. }
  15198. if (parsedTransformNode.localMatrix) {
  15199. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15200. }
  15201. else if (parsedTransformNode.pivotMatrix) {
  15202. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15203. }
  15204. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15205. // Parent
  15206. if (parsedTransformNode.parentId) {
  15207. transformNode._waitingParentId = parsedTransformNode.parentId;
  15208. }
  15209. return transformNode;
  15210. };
  15211. /**
  15212. * Disposes the TransformNode.
  15213. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15214. * Returns nothing.
  15215. */
  15216. TransformNode.prototype.dispose = function (doNotRecurse) {
  15217. // Animations
  15218. this.getScene().stopAnimation(this);
  15219. // Remove from scene
  15220. this.getScene().removeTransformNode(this);
  15221. if (!doNotRecurse) {
  15222. // Children
  15223. var objects = this.getDescendants(true);
  15224. for (var index = 0; index < objects.length; index++) {
  15225. objects[index].dispose();
  15226. }
  15227. }
  15228. else {
  15229. var childMeshes = this.getChildMeshes(true);
  15230. for (index = 0; index < childMeshes.length; index++) {
  15231. var child = childMeshes[index];
  15232. child.parent = null;
  15233. child.computeWorldMatrix(true);
  15234. }
  15235. }
  15236. this.onAfterWorldMatrixUpdateObservable.clear();
  15237. _super.prototype.dispose.call(this);
  15238. };
  15239. // Statics
  15240. TransformNode.BILLBOARDMODE_NONE = 0;
  15241. TransformNode.BILLBOARDMODE_X = 1;
  15242. TransformNode.BILLBOARDMODE_Y = 2;
  15243. TransformNode.BILLBOARDMODE_Z = 4;
  15244. TransformNode.BILLBOARDMODE_ALL = 7;
  15245. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15246. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15247. __decorate([
  15248. BABYLON.serializeAsVector3()
  15249. ], TransformNode.prototype, "_rotation", void 0);
  15250. __decorate([
  15251. BABYLON.serializeAsQuaternion()
  15252. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15253. __decorate([
  15254. BABYLON.serializeAsVector3()
  15255. ], TransformNode.prototype, "_scaling", void 0);
  15256. __decorate([
  15257. BABYLON.serialize()
  15258. ], TransformNode.prototype, "billboardMode", void 0);
  15259. __decorate([
  15260. BABYLON.serialize()
  15261. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15262. __decorate([
  15263. BABYLON.serialize()
  15264. ], TransformNode.prototype, "infiniteDistance", void 0);
  15265. __decorate([
  15266. BABYLON.serializeAsVector3()
  15267. ], TransformNode.prototype, "position", void 0);
  15268. return TransformNode;
  15269. }(BABYLON.Node));
  15270. BABYLON.TransformNode = TransformNode;
  15271. })(BABYLON || (BABYLON = {}));
  15272. //# sourceMappingURL=babylon.transformNode.js.map
  15273. var BABYLON;
  15274. (function (BABYLON) {
  15275. var AbstractMesh = /** @class */ (function (_super) {
  15276. __extends(AbstractMesh, _super);
  15277. // Constructor
  15278. function AbstractMesh(name, scene) {
  15279. if (scene === void 0) { scene = null; }
  15280. var _this = _super.call(this, name, scene, false) || this;
  15281. _this._facetNb = 0; // facet number
  15282. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15283. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15284. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15285. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15286. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15287. _this._subDiv = {
  15288. max: 1,
  15289. X: 1,
  15290. Y: 1,
  15291. Z: 1
  15292. };
  15293. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15294. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15295. // Events
  15296. /**
  15297. * An event triggered when this mesh collides with another one
  15298. * @type {BABYLON.Observable}
  15299. */
  15300. _this.onCollideObservable = new BABYLON.Observable();
  15301. /**
  15302. * An event triggered when the collision's position changes
  15303. * @type {BABYLON.Observable}
  15304. */
  15305. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15306. /**
  15307. * An event triggered when material is changed
  15308. * @type {BABYLON.Observable}
  15309. */
  15310. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15311. // Properties
  15312. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15313. /**
  15314. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15315. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15316. * or
  15317. * 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.
  15318. * for more info check WebGl documentations
  15319. */
  15320. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15321. /**
  15322. * 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:
  15323. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15324. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15325. * 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.
  15326. */
  15327. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15328. /**
  15329. * 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.
  15330. * The default value is -1 which means don't break the query and wait till the result.
  15331. */
  15332. _this.occlusionRetryCount = -1;
  15333. _this._occlusionInternalRetryCounter = 0;
  15334. _this._isOccluded = false;
  15335. _this._isOcclusionQueryInProgress = false;
  15336. _this.visibility = 1.0;
  15337. _this.alphaIndex = Number.MAX_VALUE;
  15338. _this.isVisible = true;
  15339. _this.isPickable = true;
  15340. _this.showBoundingBox = false;
  15341. _this.showSubMeshesBoundingBox = false;
  15342. _this.isBlocker = false;
  15343. _this.enablePointerMoveEvents = false;
  15344. _this.renderingGroupId = 0;
  15345. _this._receiveShadows = false;
  15346. _this.renderOutline = false;
  15347. _this.outlineColor = BABYLON.Color3.Red();
  15348. _this.outlineWidth = 0.02;
  15349. _this.renderOverlay = false;
  15350. _this.overlayColor = BABYLON.Color3.Red();
  15351. _this.overlayAlpha = 0.5;
  15352. _this._hasVertexAlpha = false;
  15353. _this._useVertexColors = true;
  15354. _this._computeBonesUsingShaders = true;
  15355. _this._numBoneInfluencers = 4;
  15356. _this._applyFog = true;
  15357. _this.useOctreeForRenderingSelection = true;
  15358. _this.useOctreeForPicking = true;
  15359. _this.useOctreeForCollisions = true;
  15360. _this._layerMask = 0x0FFFFFFF;
  15361. /**
  15362. * True if the mesh must be rendered in any case.
  15363. */
  15364. _this.alwaysSelectAsActiveMesh = false;
  15365. /**
  15366. * This scene's action manager
  15367. * @type {BABYLON.ActionManager}
  15368. */
  15369. _this.actionManager = null;
  15370. // Physics
  15371. _this.physicsImpostor = null;
  15372. // Collisions
  15373. _this._checkCollisions = false;
  15374. _this._collisionMask = -1;
  15375. _this._collisionGroup = -1;
  15376. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15377. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15378. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15379. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15380. // Edges
  15381. _this.edgesWidth = 1;
  15382. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15383. // Cache
  15384. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15385. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15386. _this._isDisposed = false;
  15387. _this._renderId = 0;
  15388. _this._intersectionsInProgress = new Array();
  15389. _this._unIndexed = false;
  15390. _this._lightSources = new Array();
  15391. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15392. if (collidedMesh === void 0) { collidedMesh = null; }
  15393. //TODO move this to the collision coordinator!
  15394. if (_this.getScene().workerCollisions)
  15395. newPosition.multiplyInPlace(_this._collider._radius);
  15396. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15397. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15398. _this.position.addInPlace(_this._diffPositionForCollisions);
  15399. }
  15400. if (collidedMesh) {
  15401. _this.onCollideObservable.notifyObservers(collidedMesh);
  15402. }
  15403. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15404. };
  15405. _this.getScene().addMesh(_this);
  15406. _this._resyncLightSources();
  15407. return _this;
  15408. }
  15409. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15410. get: function () {
  15411. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15412. },
  15413. enumerable: true,
  15414. configurable: true
  15415. });
  15416. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15417. get: function () {
  15418. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15424. get: function () {
  15425. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15426. },
  15427. enumerable: true,
  15428. configurable: true
  15429. });
  15430. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15431. get: function () {
  15432. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15433. },
  15434. enumerable: true,
  15435. configurable: true
  15436. });
  15437. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15438. get: function () {
  15439. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15440. },
  15441. enumerable: true,
  15442. configurable: true
  15443. });
  15444. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15445. /**
  15446. * Read-only : the number of facets in the mesh
  15447. */
  15448. get: function () {
  15449. return this._facetNb;
  15450. },
  15451. enumerable: true,
  15452. configurable: true
  15453. });
  15454. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15455. /**
  15456. * The number (integer) of subdivisions per axis in the partioning space
  15457. */
  15458. get: function () {
  15459. return this._partitioningSubdivisions;
  15460. },
  15461. set: function (nb) {
  15462. this._partitioningSubdivisions = nb;
  15463. },
  15464. enumerable: true,
  15465. configurable: true
  15466. });
  15467. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15468. /**
  15469. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15470. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15471. */
  15472. get: function () {
  15473. return this._partitioningBBoxRatio;
  15474. },
  15475. set: function (ratio) {
  15476. this._partitioningBBoxRatio = ratio;
  15477. },
  15478. enumerable: true,
  15479. configurable: true
  15480. });
  15481. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15482. /**
  15483. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15484. * Works only for updatable meshes.
  15485. * Doesn't work with multi-materials.
  15486. */
  15487. get: function () {
  15488. return this._facetDepthSort;
  15489. },
  15490. set: function (sort) {
  15491. this._facetDepthSort = sort;
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15497. /**
  15498. * The location (Vector3) where the facet depth sort must be computed from.
  15499. * By default, the active camera position.
  15500. * Used only when facet depth sort is enabled.
  15501. */
  15502. get: function () {
  15503. return this._facetDepthSortFrom;
  15504. },
  15505. set: function (location) {
  15506. this._facetDepthSortFrom = location;
  15507. },
  15508. enumerable: true,
  15509. configurable: true
  15510. });
  15511. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15512. /**
  15513. * Read-only boolean : is the feature facetData enabled ?
  15514. */
  15515. get: function () {
  15516. return this._facetDataEnabled;
  15517. },
  15518. enumerable: true,
  15519. configurable: true
  15520. });
  15521. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15522. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15523. return false;
  15524. }
  15525. this._markSubMeshesAsMiscDirty();
  15526. return true;
  15527. };
  15528. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15529. set: function (callback) {
  15530. if (this._onCollideObserver) {
  15531. this.onCollideObservable.remove(this._onCollideObserver);
  15532. }
  15533. this._onCollideObserver = this.onCollideObservable.add(callback);
  15534. },
  15535. enumerable: true,
  15536. configurable: true
  15537. });
  15538. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15539. set: function (callback) {
  15540. if (this._onCollisionPositionChangeObserver) {
  15541. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15542. }
  15543. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15544. },
  15545. enumerable: true,
  15546. configurable: true
  15547. });
  15548. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15549. /**
  15550. * 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.
  15551. */
  15552. get: function () {
  15553. return this._isOccluded;
  15554. },
  15555. set: function (value) {
  15556. this._isOccluded = value;
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15562. /**
  15563. * Flag to check the progress status of the query
  15564. */
  15565. get: function () {
  15566. return this._isOcclusionQueryInProgress;
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(AbstractMesh.prototype, "material", {
  15572. get: function () {
  15573. return this._material;
  15574. },
  15575. set: function (value) {
  15576. if (this._material === value) {
  15577. return;
  15578. }
  15579. this._material = value;
  15580. if (this.onMaterialChangedObservable.hasObservers) {
  15581. this.onMaterialChangedObservable.notifyObservers(this);
  15582. }
  15583. if (!this.subMeshes) {
  15584. return;
  15585. }
  15586. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15587. var subMesh = _a[_i];
  15588. subMesh.setEffect(null);
  15589. }
  15590. },
  15591. enumerable: true,
  15592. configurable: true
  15593. });
  15594. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15595. get: function () {
  15596. return this._receiveShadows;
  15597. },
  15598. set: function (value) {
  15599. if (this._receiveShadows === value) {
  15600. return;
  15601. }
  15602. this._receiveShadows = value;
  15603. this._markSubMeshesAsLightDirty();
  15604. },
  15605. enumerable: true,
  15606. configurable: true
  15607. });
  15608. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15609. get: function () {
  15610. return this._hasVertexAlpha;
  15611. },
  15612. set: function (value) {
  15613. if (this._hasVertexAlpha === value) {
  15614. return;
  15615. }
  15616. this._hasVertexAlpha = value;
  15617. this._markSubMeshesAsAttributesDirty();
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15623. get: function () {
  15624. return this._useVertexColors;
  15625. },
  15626. set: function (value) {
  15627. if (this._useVertexColors === value) {
  15628. return;
  15629. }
  15630. this._useVertexColors = value;
  15631. this._markSubMeshesAsAttributesDirty();
  15632. },
  15633. enumerable: true,
  15634. configurable: true
  15635. });
  15636. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15637. get: function () {
  15638. return this._computeBonesUsingShaders;
  15639. },
  15640. set: function (value) {
  15641. if (this._computeBonesUsingShaders === value) {
  15642. return;
  15643. }
  15644. this._computeBonesUsingShaders = value;
  15645. this._markSubMeshesAsAttributesDirty();
  15646. },
  15647. enumerable: true,
  15648. configurable: true
  15649. });
  15650. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15651. get: function () {
  15652. return this._numBoneInfluencers;
  15653. },
  15654. set: function (value) {
  15655. if (this._numBoneInfluencers === value) {
  15656. return;
  15657. }
  15658. this._numBoneInfluencers = value;
  15659. this._markSubMeshesAsAttributesDirty();
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15665. get: function () {
  15666. return this._applyFog;
  15667. },
  15668. set: function (value) {
  15669. if (this._applyFog === value) {
  15670. return;
  15671. }
  15672. this._applyFog = value;
  15673. this._markSubMeshesAsMiscDirty();
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15679. get: function () {
  15680. return this._layerMask;
  15681. },
  15682. set: function (value) {
  15683. if (value === this._layerMask) {
  15684. return;
  15685. }
  15686. this._layerMask = value;
  15687. this._resyncLightSources();
  15688. },
  15689. enumerable: true,
  15690. configurable: true
  15691. });
  15692. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15693. get: function () {
  15694. return this._collisionMask;
  15695. },
  15696. set: function (mask) {
  15697. this._collisionMask = !isNaN(mask) ? mask : -1;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15703. get: function () {
  15704. return this._collisionGroup;
  15705. },
  15706. set: function (mask) {
  15707. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15708. },
  15709. enumerable: true,
  15710. configurable: true
  15711. });
  15712. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15713. get: function () {
  15714. return null;
  15715. },
  15716. enumerable: true,
  15717. configurable: true
  15718. });
  15719. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15720. get: function () {
  15721. return this._skeleton;
  15722. },
  15723. set: function (value) {
  15724. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15725. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15726. }
  15727. if (value && value.needInitialSkinMatrix) {
  15728. value._registerMeshWithPoseMatrix(this);
  15729. }
  15730. this._skeleton = value;
  15731. if (!this._skeleton) {
  15732. this._bonesTransformMatrices = null;
  15733. }
  15734. this._markSubMeshesAsAttributesDirty();
  15735. },
  15736. enumerable: true,
  15737. configurable: true
  15738. });
  15739. /**
  15740. * Boolean : true if the mesh has been disposed.
  15741. */
  15742. AbstractMesh.prototype.isDisposed = function () {
  15743. return this._isDisposed;
  15744. };
  15745. /**
  15746. * Returns the string "AbstractMesh"
  15747. */
  15748. AbstractMesh.prototype.getClassName = function () {
  15749. return "AbstractMesh";
  15750. };
  15751. /**
  15752. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15753. */
  15754. AbstractMesh.prototype.toString = function (fullDetails) {
  15755. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15756. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15757. if (this._skeleton) {
  15758. ret += ", skeleton: " + this._skeleton.name;
  15759. }
  15760. if (fullDetails) {
  15761. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15762. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15763. }
  15764. return ret;
  15765. };
  15766. AbstractMesh.prototype._rebuild = function () {
  15767. if (this._occlusionQuery) {
  15768. this._occlusionQuery = null;
  15769. }
  15770. if (this._edgesRenderer) {
  15771. this._edgesRenderer._rebuild();
  15772. }
  15773. if (!this.subMeshes) {
  15774. return;
  15775. }
  15776. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15777. var subMesh = _a[_i];
  15778. subMesh._rebuild();
  15779. }
  15780. };
  15781. AbstractMesh.prototype._resyncLightSources = function () {
  15782. this._lightSources.length = 0;
  15783. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15784. var light = _a[_i];
  15785. if (!light.isEnabled()) {
  15786. continue;
  15787. }
  15788. if (light.canAffectMesh(this)) {
  15789. this._lightSources.push(light);
  15790. }
  15791. }
  15792. this._markSubMeshesAsLightDirty();
  15793. };
  15794. AbstractMesh.prototype._resyncLighSource = function (light) {
  15795. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15796. var index = this._lightSources.indexOf(light);
  15797. if (index === -1) {
  15798. if (!isIn) {
  15799. return;
  15800. }
  15801. this._lightSources.push(light);
  15802. }
  15803. else {
  15804. if (isIn) {
  15805. return;
  15806. }
  15807. this._lightSources.splice(index, 1);
  15808. }
  15809. this._markSubMeshesAsLightDirty();
  15810. };
  15811. AbstractMesh.prototype._removeLightSource = function (light) {
  15812. var index = this._lightSources.indexOf(light);
  15813. if (index === -1) {
  15814. return;
  15815. }
  15816. this._lightSources.splice(index, 1);
  15817. };
  15818. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15819. if (!this.subMeshes) {
  15820. return;
  15821. }
  15822. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15823. var subMesh = _a[_i];
  15824. if (subMesh._materialDefines) {
  15825. func(subMesh._materialDefines);
  15826. }
  15827. }
  15828. };
  15829. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15830. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15831. };
  15832. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15833. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15834. };
  15835. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15836. if (!this.subMeshes) {
  15837. return;
  15838. }
  15839. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15840. var subMesh = _a[_i];
  15841. var material = subMesh.getMaterial();
  15842. if (material) {
  15843. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15844. }
  15845. }
  15846. };
  15847. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15848. /**
  15849. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15850. * Default : (1.0, 1.0, 1.0)
  15851. */
  15852. get: function () {
  15853. return this._scaling;
  15854. },
  15855. /**
  15856. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15857. * Default : (1.0, 1.0, 1.0)
  15858. */
  15859. set: function (newScaling) {
  15860. this._scaling = newScaling;
  15861. if (this.physicsImpostor) {
  15862. this.physicsImpostor.forceUpdate();
  15863. }
  15864. },
  15865. enumerable: true,
  15866. configurable: true
  15867. });
  15868. // Methods
  15869. /**
  15870. * Disables the mesh edger rendering mode.
  15871. * Returns the AbstractMesh.
  15872. */
  15873. AbstractMesh.prototype.disableEdgesRendering = function () {
  15874. if (this._edgesRenderer) {
  15875. this._edgesRenderer.dispose();
  15876. this._edgesRenderer = null;
  15877. }
  15878. return this;
  15879. };
  15880. /**
  15881. * Enables the edge rendering mode on the mesh.
  15882. * This mode makes the mesh edges visible.
  15883. * Returns the AbstractMesh.
  15884. */
  15885. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15886. if (epsilon === void 0) { epsilon = 0.95; }
  15887. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15888. this.disableEdgesRendering();
  15889. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15890. return this;
  15891. };
  15892. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15893. /**
  15894. * Returns true if the mesh is blocked. Used by the class Mesh.
  15895. * Returns the boolean `false` by default.
  15896. */
  15897. get: function () {
  15898. return false;
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. /**
  15904. * Returns the mesh itself by default, used by the class Mesh.
  15905. * Returned type : AbstractMesh
  15906. */
  15907. AbstractMesh.prototype.getLOD = function (camera) {
  15908. return this;
  15909. };
  15910. /**
  15911. * Returns 0 by default, used by the class Mesh.
  15912. * Returns an integer.
  15913. */
  15914. AbstractMesh.prototype.getTotalVertices = function () {
  15915. return 0;
  15916. };
  15917. /**
  15918. * Returns null by default, used by the class Mesh.
  15919. * Returned type : integer array
  15920. */
  15921. AbstractMesh.prototype.getIndices = function () {
  15922. return null;
  15923. };
  15924. /**
  15925. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15926. * Returned type : float array or Float32Array
  15927. */
  15928. AbstractMesh.prototype.getVerticesData = function (kind) {
  15929. return null;
  15930. };
  15931. /**
  15932. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15933. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15934. * The `data` are either a numeric array either a Float32Array.
  15935. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15936. * 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).
  15937. * Note that a new underlying VertexBuffer object is created each call.
  15938. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15939. *
  15940. * Possible `kind` values :
  15941. * - BABYLON.VertexBuffer.PositionKind
  15942. * - BABYLON.VertexBuffer.UVKind
  15943. * - BABYLON.VertexBuffer.UV2Kind
  15944. * - BABYLON.VertexBuffer.UV3Kind
  15945. * - BABYLON.VertexBuffer.UV4Kind
  15946. * - BABYLON.VertexBuffer.UV5Kind
  15947. * - BABYLON.VertexBuffer.UV6Kind
  15948. * - BABYLON.VertexBuffer.ColorKind
  15949. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15950. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15951. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15952. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15953. *
  15954. * Returns the Mesh.
  15955. */
  15956. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15957. return this;
  15958. };
  15959. /**
  15960. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15961. * If the mesh has no geometry, it is simply returned as it is.
  15962. * The `data` are either a numeric array either a Float32Array.
  15963. * No new underlying VertexBuffer object is created.
  15964. * 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.
  15965. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15966. *
  15967. * Possible `kind` values :
  15968. * - BABYLON.VertexBuffer.PositionKind
  15969. * - BABYLON.VertexBuffer.UVKind
  15970. * - BABYLON.VertexBuffer.UV2Kind
  15971. * - BABYLON.VertexBuffer.UV3Kind
  15972. * - BABYLON.VertexBuffer.UV4Kind
  15973. * - BABYLON.VertexBuffer.UV5Kind
  15974. * - BABYLON.VertexBuffer.UV6Kind
  15975. * - BABYLON.VertexBuffer.ColorKind
  15976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15980. *
  15981. * Returns the Mesh.
  15982. */
  15983. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15984. return this;
  15985. };
  15986. /**
  15987. * Sets the mesh indices.
  15988. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15989. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15990. * This method creates a new index buffer each call.
  15991. * Returns the Mesh.
  15992. */
  15993. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15994. return this;
  15995. };
  15996. /** Returns false by default, used by the class Mesh.
  15997. * Returns a boolean
  15998. */
  15999. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16000. return false;
  16001. };
  16002. /**
  16003. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16004. * Returns a BoundingInfo
  16005. */
  16006. AbstractMesh.prototype.getBoundingInfo = function () {
  16007. if (this._masterMesh) {
  16008. return this._masterMesh.getBoundingInfo();
  16009. }
  16010. if (!this._boundingInfo) {
  16011. // this._boundingInfo is being created here
  16012. this._updateBoundingInfo();
  16013. }
  16014. // cannot be null.
  16015. return this._boundingInfo;
  16016. };
  16017. /**
  16018. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16019. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16020. */
  16021. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16022. if (includeDescendants === void 0) { includeDescendants = true; }
  16023. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16024. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16025. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16026. if (maxDimension === 0) {
  16027. return this;
  16028. }
  16029. var scale = 1 / maxDimension;
  16030. this.scaling.scaleInPlace(scale);
  16031. return this;
  16032. };
  16033. /**
  16034. * Sets a mesh new object BoundingInfo.
  16035. * Returns the AbstractMesh.
  16036. */
  16037. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16038. this._boundingInfo = boundingInfo;
  16039. return this;
  16040. };
  16041. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16042. get: function () {
  16043. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16044. },
  16045. enumerable: true,
  16046. configurable: true
  16047. });
  16048. AbstractMesh.prototype._preActivate = function () {
  16049. };
  16050. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16051. };
  16052. AbstractMesh.prototype._activate = function (renderId) {
  16053. this._renderId = renderId;
  16054. };
  16055. /**
  16056. * Returns the latest update of the World matrix
  16057. * Returns a Matrix.
  16058. */
  16059. AbstractMesh.prototype.getWorldMatrix = function () {
  16060. if (this._masterMesh) {
  16061. return this._masterMesh.getWorldMatrix();
  16062. }
  16063. return _super.prototype.getWorldMatrix.call(this);
  16064. };
  16065. /**
  16066. * Returns the latest update of the World matrix determinant.
  16067. */
  16068. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16069. if (this._masterMesh) {
  16070. return this._masterMesh._getWorldMatrixDeterminant();
  16071. }
  16072. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16073. };
  16074. // ================================== Point of View Movement =================================
  16075. /**
  16076. * Perform relative position change from the point of view of behind the front of the mesh.
  16077. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16078. * Supports definition of mesh facing forward or backward.
  16079. * @param {number} amountRight
  16080. * @param {number} amountUp
  16081. * @param {number} amountForward
  16082. *
  16083. * Returns the AbstractMesh.
  16084. */
  16085. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16086. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16087. return this;
  16088. };
  16089. /**
  16090. * Calculate relative position change from the point of view of behind the front of the mesh.
  16091. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16092. * Supports definition of mesh facing forward or backward.
  16093. * @param {number} amountRight
  16094. * @param {number} amountUp
  16095. * @param {number} amountForward
  16096. *
  16097. * Returns a new Vector3.
  16098. */
  16099. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16100. var rotMatrix = new BABYLON.Matrix();
  16101. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16102. rotQuaternion.toRotationMatrix(rotMatrix);
  16103. var translationDelta = BABYLON.Vector3.Zero();
  16104. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16105. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16106. return translationDelta;
  16107. };
  16108. // ================================== Point of View Rotation =================================
  16109. /**
  16110. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16111. * Supports definition of mesh facing forward or backward.
  16112. * @param {number} flipBack
  16113. * @param {number} twirlClockwise
  16114. * @param {number} tiltRight
  16115. *
  16116. * Returns the AbstractMesh.
  16117. */
  16118. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16119. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16120. return this;
  16121. };
  16122. /**
  16123. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16124. * Supports definition of mesh facing forward or backward.
  16125. * @param {number} flipBack
  16126. * @param {number} twirlClockwise
  16127. * @param {number} tiltRight
  16128. *
  16129. * Returns a new Vector3.
  16130. */
  16131. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16132. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16133. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16134. };
  16135. /**
  16136. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16137. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16138. */
  16139. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16140. if (includeDescendants === void 0) { includeDescendants = true; }
  16141. this.computeWorldMatrix(true);
  16142. var min;
  16143. var max;
  16144. var boundingInfo = this.getBoundingInfo();
  16145. if (!this.subMeshes) {
  16146. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16147. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16148. }
  16149. else {
  16150. min = boundingInfo.boundingBox.minimumWorld;
  16151. max = boundingInfo.boundingBox.maximumWorld;
  16152. }
  16153. if (includeDescendants) {
  16154. var descendants = this.getDescendants(false);
  16155. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16156. var descendant = descendants_1[_i];
  16157. var childMesh = descendant;
  16158. childMesh.computeWorldMatrix(true);
  16159. //make sure we have the needed params to get mix and max
  16160. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16161. continue;
  16162. }
  16163. var childBoundingInfo = childMesh.getBoundingInfo();
  16164. var boundingBox = childBoundingInfo.boundingBox;
  16165. var minBox = boundingBox.minimumWorld;
  16166. var maxBox = boundingBox.maximumWorld;
  16167. BABYLON.Tools.CheckExtends(minBox, min, max);
  16168. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16169. }
  16170. }
  16171. return {
  16172. min: min,
  16173. max: max
  16174. };
  16175. };
  16176. /**
  16177. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16178. * Returns the AbstractMesh.
  16179. */
  16180. AbstractMesh.prototype._updateBoundingInfo = function () {
  16181. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16182. this._boundingInfo.update(this.worldMatrixFromCache);
  16183. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16184. return this;
  16185. };
  16186. /**
  16187. * Update a mesh's children BoundingInfo objects only.
  16188. * Returns the AbstractMesh.
  16189. */
  16190. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16191. if (!this.subMeshes) {
  16192. return this;
  16193. }
  16194. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16195. var subMesh = this.subMeshes[subIndex];
  16196. if (!subMesh.IsGlobal) {
  16197. subMesh.updateBoundingInfo(matrix);
  16198. }
  16199. }
  16200. return this;
  16201. };
  16202. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16203. // Bounding info
  16204. this._updateBoundingInfo();
  16205. };
  16206. /**
  16207. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16208. * A mesh is in the frustum if its bounding box intersects the frustum.
  16209. * Boolean returned.
  16210. */
  16211. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16212. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16213. };
  16214. /**
  16215. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16216. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16217. * Boolean returned.
  16218. */
  16219. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16220. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16221. ;
  16222. };
  16223. /**
  16224. * True if the mesh intersects another mesh or a SolidParticle object.
  16225. * 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)
  16226. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16227. * Returns a boolean.
  16228. */
  16229. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16230. if (precise === void 0) { precise = false; }
  16231. if (!this._boundingInfo || !mesh._boundingInfo) {
  16232. return false;
  16233. }
  16234. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16235. return true;
  16236. }
  16237. if (includeDescendants) {
  16238. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16239. var child = _a[_i];
  16240. if (child.intersectsMesh(mesh, precise, true)) {
  16241. return true;
  16242. }
  16243. }
  16244. }
  16245. return false;
  16246. };
  16247. /**
  16248. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16249. * Returns a boolean.
  16250. */
  16251. AbstractMesh.prototype.intersectsPoint = function (point) {
  16252. if (!this._boundingInfo) {
  16253. return false;
  16254. }
  16255. return this._boundingInfo.intersectsPoint(point);
  16256. };
  16257. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16258. return this.physicsImpostor;
  16259. };
  16260. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16261. if (camera === void 0) { camera = null; }
  16262. if (!camera) {
  16263. camera = this.getScene().activeCamera;
  16264. }
  16265. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16266. };
  16267. /**
  16268. * Returns the distance from the mesh to the active camera.
  16269. * Returns a float.
  16270. */
  16271. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16272. if (camera === void 0) { camera = null; }
  16273. if (!camera) {
  16274. camera = this.getScene().activeCamera;
  16275. }
  16276. return this.absolutePosition.subtract(camera.position).length();
  16277. };
  16278. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16279. if (!this.physicsImpostor) {
  16280. return this;
  16281. }
  16282. this.physicsImpostor.applyImpulse(force, contactPoint);
  16283. return this;
  16284. };
  16285. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16286. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16287. return this;
  16288. }
  16289. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16290. mainPivot: pivot1,
  16291. connectedPivot: pivot2,
  16292. nativeParams: options
  16293. });
  16294. return this;
  16295. };
  16296. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16297. // Collisions
  16298. /**
  16299. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16300. * Default `false`.
  16301. */
  16302. get: function () {
  16303. return this._checkCollisions;
  16304. },
  16305. set: function (collisionEnabled) {
  16306. this._checkCollisions = collisionEnabled;
  16307. if (this.getScene().workerCollisions) {
  16308. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16309. }
  16310. },
  16311. enumerable: true,
  16312. configurable: true
  16313. });
  16314. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16315. /**
  16316. * Gets Collider object used to compute collisions (not physics)
  16317. */
  16318. get: function () {
  16319. return this._collider;
  16320. },
  16321. enumerable: true,
  16322. configurable: true
  16323. });
  16324. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16325. var globalPosition = this.getAbsolutePosition();
  16326. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16327. if (!this._collider) {
  16328. this._collider = new BABYLON.Collider();
  16329. }
  16330. this._collider._radius = this.ellipsoid;
  16331. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16332. return this;
  16333. };
  16334. // Submeshes octree
  16335. /**
  16336. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16337. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16338. * Returns an Octree of submeshes.
  16339. */
  16340. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16341. if (maxCapacity === void 0) { maxCapacity = 64; }
  16342. if (maxDepth === void 0) { maxDepth = 2; }
  16343. if (!this._submeshesOctree) {
  16344. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16345. }
  16346. this.computeWorldMatrix(true);
  16347. var boundingInfo = this.getBoundingInfo();
  16348. // Update octree
  16349. var bbox = boundingInfo.boundingBox;
  16350. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16351. return this._submeshesOctree;
  16352. };
  16353. // Collisions
  16354. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16355. this._generatePointsArray();
  16356. if (!this._positions) {
  16357. return this;
  16358. }
  16359. // Transformation
  16360. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16361. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16362. subMesh._lastColliderWorldVertices = [];
  16363. subMesh._trianglePlanes = [];
  16364. var start = subMesh.verticesStart;
  16365. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16366. for (var i = start; i < end; i++) {
  16367. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16368. }
  16369. }
  16370. // Collide
  16371. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16372. if (collider.collisionFound) {
  16373. collider.collidedMesh = this;
  16374. }
  16375. return this;
  16376. };
  16377. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16378. var subMeshes;
  16379. var len;
  16380. // Octrees
  16381. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16382. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16383. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16384. len = intersections.length;
  16385. subMeshes = intersections.data;
  16386. }
  16387. else {
  16388. subMeshes = this.subMeshes;
  16389. len = subMeshes.length;
  16390. }
  16391. for (var index = 0; index < len; index++) {
  16392. var subMesh = subMeshes[index];
  16393. // Bounding test
  16394. if (len > 1 && !subMesh._checkCollision(collider))
  16395. continue;
  16396. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16397. }
  16398. return this;
  16399. };
  16400. AbstractMesh.prototype._checkCollision = function (collider) {
  16401. // Bounding box test
  16402. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16403. return this;
  16404. // Transformation matrix
  16405. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16406. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16407. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16408. return this;
  16409. };
  16410. // Picking
  16411. AbstractMesh.prototype._generatePointsArray = function () {
  16412. return false;
  16413. };
  16414. /**
  16415. * Checks if the passed Ray intersects with the mesh.
  16416. * Returns an object PickingInfo.
  16417. */
  16418. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16419. var pickingInfo = new BABYLON.PickingInfo();
  16420. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16421. return pickingInfo;
  16422. }
  16423. if (!this._generatePointsArray()) {
  16424. return pickingInfo;
  16425. }
  16426. var intersectInfo = null;
  16427. // Octrees
  16428. var subMeshes;
  16429. var len;
  16430. if (this._submeshesOctree && this.useOctreeForPicking) {
  16431. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16432. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16433. len = intersections.length;
  16434. subMeshes = intersections.data;
  16435. }
  16436. else {
  16437. subMeshes = this.subMeshes;
  16438. len = subMeshes.length;
  16439. }
  16440. for (var index = 0; index < len; index++) {
  16441. var subMesh = subMeshes[index];
  16442. // Bounding test
  16443. if (len > 1 && !subMesh.canIntersects(ray))
  16444. continue;
  16445. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16446. if (currentIntersectInfo) {
  16447. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16448. intersectInfo = currentIntersectInfo;
  16449. intersectInfo.subMeshId = index;
  16450. if (fastCheck) {
  16451. break;
  16452. }
  16453. }
  16454. }
  16455. }
  16456. if (intersectInfo) {
  16457. // Get picked point
  16458. var world = this.getWorldMatrix();
  16459. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16460. var direction = ray.direction.clone();
  16461. direction = direction.scale(intersectInfo.distance);
  16462. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16463. var pickedPoint = worldOrigin.add(worldDirection);
  16464. // Return result
  16465. pickingInfo.hit = true;
  16466. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16467. pickingInfo.pickedPoint = pickedPoint;
  16468. pickingInfo.pickedMesh = this;
  16469. pickingInfo.bu = intersectInfo.bu || 0;
  16470. pickingInfo.bv = intersectInfo.bv || 0;
  16471. pickingInfo.faceId = intersectInfo.faceId;
  16472. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16473. return pickingInfo;
  16474. }
  16475. return pickingInfo;
  16476. };
  16477. /**
  16478. * Clones the mesh, used by the class Mesh.
  16479. * Just returns `null` for an AbstractMesh.
  16480. */
  16481. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16482. return null;
  16483. };
  16484. /**
  16485. * Disposes all the mesh submeshes.
  16486. * Returns the AbstractMesh.
  16487. */
  16488. AbstractMesh.prototype.releaseSubMeshes = function () {
  16489. if (this.subMeshes) {
  16490. while (this.subMeshes.length) {
  16491. this.subMeshes[0].dispose();
  16492. }
  16493. }
  16494. else {
  16495. this.subMeshes = new Array();
  16496. }
  16497. return this;
  16498. };
  16499. /**
  16500. * Disposes the AbstractMesh.
  16501. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16502. * Returns nothing.
  16503. */
  16504. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16505. var _this = this;
  16506. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16507. var index;
  16508. // Action manager
  16509. if (this.actionManager !== undefined && this.actionManager !== null) {
  16510. this.actionManager.dispose();
  16511. this.actionManager = null;
  16512. }
  16513. // Skeleton
  16514. this.skeleton = null;
  16515. // Physics
  16516. if (this.physicsImpostor) {
  16517. this.physicsImpostor.dispose();
  16518. }
  16519. // Intersections in progress
  16520. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16521. var other = this._intersectionsInProgress[index];
  16522. var pos = other._intersectionsInProgress.indexOf(this);
  16523. other._intersectionsInProgress.splice(pos, 1);
  16524. }
  16525. this._intersectionsInProgress = [];
  16526. // Lights
  16527. var lights = this.getScene().lights;
  16528. lights.forEach(function (light) {
  16529. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16530. if (meshIndex !== -1) {
  16531. light.includedOnlyMeshes.splice(meshIndex, 1);
  16532. }
  16533. meshIndex = light.excludedMeshes.indexOf(_this);
  16534. if (meshIndex !== -1) {
  16535. light.excludedMeshes.splice(meshIndex, 1);
  16536. }
  16537. // Shadow generators
  16538. var generator = light.getShadowGenerator();
  16539. if (generator) {
  16540. var shadowMap = generator.getShadowMap();
  16541. if (shadowMap && shadowMap.renderList) {
  16542. meshIndex = shadowMap.renderList.indexOf(_this);
  16543. if (meshIndex !== -1) {
  16544. shadowMap.renderList.splice(meshIndex, 1);
  16545. }
  16546. }
  16547. }
  16548. });
  16549. // Edges
  16550. if (this._edgesRenderer) {
  16551. this._edgesRenderer.dispose();
  16552. this._edgesRenderer = null;
  16553. }
  16554. // SubMeshes
  16555. if (this.getClassName() !== "InstancedMesh") {
  16556. this.releaseSubMeshes();
  16557. }
  16558. // Octree
  16559. var sceneOctree = this.getScene().selectionOctree;
  16560. if (sceneOctree !== undefined && sceneOctree !== null) {
  16561. var index = sceneOctree.dynamicContent.indexOf(this);
  16562. if (index !== -1) {
  16563. sceneOctree.dynamicContent.splice(index, 1);
  16564. }
  16565. }
  16566. // Query
  16567. var engine = this.getScene().getEngine();
  16568. if (this._occlusionQuery) {
  16569. this._isOcclusionQueryInProgress = false;
  16570. engine.deleteQuery(this._occlusionQuery);
  16571. this._occlusionQuery = null;
  16572. }
  16573. // Engine
  16574. engine.wipeCaches();
  16575. // Remove from scene
  16576. this.getScene().removeMesh(this);
  16577. if (disposeMaterialAndTextures) {
  16578. if (this.material) {
  16579. this.material.dispose(false, true);
  16580. }
  16581. }
  16582. if (!doNotRecurse) {
  16583. // Particles
  16584. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16585. if (this.getScene().particleSystems[index].emitter === this) {
  16586. this.getScene().particleSystems[index].dispose();
  16587. index--;
  16588. }
  16589. }
  16590. }
  16591. // facet data
  16592. if (this._facetDataEnabled) {
  16593. this.disableFacetData();
  16594. }
  16595. this.onAfterWorldMatrixUpdateObservable.clear();
  16596. this.onCollideObservable.clear();
  16597. this.onCollisionPositionChangeObservable.clear();
  16598. this._isDisposed = true;
  16599. _super.prototype.dispose.call(this, doNotRecurse);
  16600. };
  16601. /**
  16602. * Adds the passed mesh as a child to the current mesh.
  16603. * Returns the AbstractMesh.
  16604. */
  16605. AbstractMesh.prototype.addChild = function (mesh) {
  16606. mesh.setParent(this);
  16607. return this;
  16608. };
  16609. /**
  16610. * Removes the passed mesh from the current mesh children list.
  16611. * Returns the AbstractMesh.
  16612. */
  16613. AbstractMesh.prototype.removeChild = function (mesh) {
  16614. mesh.setParent(null);
  16615. return this;
  16616. };
  16617. // Facet data
  16618. /**
  16619. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16620. * Returns the AbstractMesh.
  16621. */
  16622. AbstractMesh.prototype._initFacetData = function () {
  16623. if (!this._facetNormals) {
  16624. this._facetNormals = new Array();
  16625. }
  16626. if (!this._facetPositions) {
  16627. this._facetPositions = new Array();
  16628. }
  16629. if (!this._facetPartitioning) {
  16630. this._facetPartitioning = new Array();
  16631. }
  16632. this._facetNb = (this.getIndices().length / 3) | 0;
  16633. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16634. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16635. for (var f = 0; f < this._facetNb; f++) {
  16636. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16637. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16638. }
  16639. this._facetDataEnabled = true;
  16640. return this;
  16641. };
  16642. /**
  16643. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16644. * This method can be called within the render loop.
  16645. * 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.
  16646. * Returns the AbstractMesh.
  16647. */
  16648. AbstractMesh.prototype.updateFacetData = function () {
  16649. if (!this._facetDataEnabled) {
  16650. this._initFacetData();
  16651. }
  16652. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16653. var indices = this.getIndices();
  16654. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16655. var bInfo = this.getBoundingInfo();
  16656. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16657. // init arrays, matrix and sort function on first call
  16658. this._facetDepthSortEnabled = true;
  16659. if (indices instanceof Uint16Array) {
  16660. this._depthSortedIndices = new Uint16Array(indices);
  16661. }
  16662. else if (indices instanceof Uint32Array) {
  16663. this._depthSortedIndices = new Uint32Array(indices);
  16664. }
  16665. else {
  16666. var needs32bits = false;
  16667. for (var i = 0; i < indices.length; i++) {
  16668. if (indices[i] > 65535) {
  16669. needs32bits = true;
  16670. break;
  16671. }
  16672. }
  16673. if (needs32bits) {
  16674. this._depthSortedIndices = new Uint32Array(indices);
  16675. }
  16676. else {
  16677. this._depthSortedIndices = new Uint16Array(indices);
  16678. }
  16679. }
  16680. this._facetDepthSortFunction = function (f1, f2) {
  16681. return (f2.sqDistance - f1.sqDistance);
  16682. };
  16683. if (!this._facetDepthSortFrom) {
  16684. var camera = this.getScene().activeCamera;
  16685. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16686. }
  16687. this._depthSortedFacets = [];
  16688. for (var f = 0; f < this._facetNb; f++) {
  16689. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16690. this._depthSortedFacets.push(depthSortedFacet);
  16691. }
  16692. this._invertedMatrix = BABYLON.Matrix.Identity();
  16693. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16694. }
  16695. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16696. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16697. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16698. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16699. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16700. this._subDiv.max = this._partitioningSubdivisions;
  16701. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16702. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16703. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16704. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16705. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16706. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16707. // set the parameters for ComputeNormals()
  16708. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16709. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16710. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16711. this._facetParameters.bInfo = bInfo;
  16712. this._facetParameters.bbSize = this._bbSize;
  16713. this._facetParameters.subDiv = this._subDiv;
  16714. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16715. this._facetParameters.depthSort = this._facetDepthSort;
  16716. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16717. this.computeWorldMatrix(true);
  16718. this._worldMatrix.invertToRef(this._invertedMatrix);
  16719. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16720. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16721. }
  16722. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16723. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16724. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16725. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16726. var l = (this._depthSortedIndices.length / 3) | 0;
  16727. for (var f = 0; f < l; f++) {
  16728. var sind = this._depthSortedFacets[f].ind;
  16729. this._depthSortedIndices[f * 3] = indices[sind];
  16730. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16731. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16732. }
  16733. this.updateIndices(this._depthSortedIndices);
  16734. }
  16735. return this;
  16736. };
  16737. /**
  16738. * Returns the facetLocalNormals array.
  16739. * The normals are expressed in the mesh local space.
  16740. */
  16741. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16742. if (!this._facetNormals) {
  16743. this.updateFacetData();
  16744. }
  16745. return this._facetNormals;
  16746. };
  16747. /**
  16748. * Returns the facetLocalPositions array.
  16749. * The facet positions are expressed in the mesh local space.
  16750. */
  16751. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16752. if (!this._facetPositions) {
  16753. this.updateFacetData();
  16754. }
  16755. return this._facetPositions;
  16756. };
  16757. /**
  16758. * Returns the facetLocalPartioning array.
  16759. */
  16760. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16761. if (!this._facetPartitioning) {
  16762. this.updateFacetData();
  16763. }
  16764. return this._facetPartitioning;
  16765. };
  16766. /**
  16767. * Returns the i-th facet position in the world system.
  16768. * This method allocates a new Vector3 per call.
  16769. */
  16770. AbstractMesh.prototype.getFacetPosition = function (i) {
  16771. var pos = BABYLON.Vector3.Zero();
  16772. this.getFacetPositionToRef(i, pos);
  16773. return pos;
  16774. };
  16775. /**
  16776. * Sets the reference Vector3 with the i-th facet position in the world system.
  16777. * Returns the AbstractMesh.
  16778. */
  16779. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16780. var localPos = (this.getFacetLocalPositions())[i];
  16781. var world = this.getWorldMatrix();
  16782. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16783. return this;
  16784. };
  16785. /**
  16786. * Returns the i-th facet normal in the world system.
  16787. * This method allocates a new Vector3 per call.
  16788. */
  16789. AbstractMesh.prototype.getFacetNormal = function (i) {
  16790. var norm = BABYLON.Vector3.Zero();
  16791. this.getFacetNormalToRef(i, norm);
  16792. return norm;
  16793. };
  16794. /**
  16795. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16796. * Returns the AbstractMesh.
  16797. */
  16798. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16799. var localNorm = (this.getFacetLocalNormals())[i];
  16800. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16801. return this;
  16802. };
  16803. /**
  16804. * 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).
  16805. */
  16806. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16807. var bInfo = this.getBoundingInfo();
  16808. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16809. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16810. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16811. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16812. return null;
  16813. }
  16814. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16815. };
  16816. /**
  16817. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16818. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16819. * 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.
  16820. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16821. * 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.
  16822. */
  16823. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16824. if (checkFace === void 0) { checkFace = false; }
  16825. if (facing === void 0) { facing = true; }
  16826. var world = this.getWorldMatrix();
  16827. var invMat = BABYLON.Tmp.Matrix[5];
  16828. world.invertToRef(invMat);
  16829. var invVect = BABYLON.Tmp.Vector3[8];
  16830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16831. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16832. if (projected) {
  16833. // tranform the local computed projected vector to world coordinates
  16834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16835. }
  16836. return closest;
  16837. };
  16838. /**
  16839. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16840. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16841. * 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.
  16842. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16843. * 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.
  16844. */
  16845. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16846. if (checkFace === void 0) { checkFace = false; }
  16847. if (facing === void 0) { facing = true; }
  16848. var closest = null;
  16849. var tmpx = 0.0;
  16850. var tmpy = 0.0;
  16851. var tmpz = 0.0;
  16852. var d = 0.0; // tmp dot facet normal * facet position
  16853. var t0 = 0.0;
  16854. var projx = 0.0;
  16855. var projy = 0.0;
  16856. var projz = 0.0;
  16857. // Get all the facets in the same partitioning block than (x, y, z)
  16858. var facetPositions = this.getFacetLocalPositions();
  16859. var facetNormals = this.getFacetLocalNormals();
  16860. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16861. if (!facetsInBlock) {
  16862. return null;
  16863. }
  16864. // Get the closest facet to (x, y, z)
  16865. var shortest = Number.MAX_VALUE; // init distance vars
  16866. var tmpDistance = shortest;
  16867. var fib; // current facet in the block
  16868. var norm; // current facet normal
  16869. var p0; // current facet barycenter position
  16870. // loop on all the facets in the current partitioning block
  16871. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16872. fib = facetsInBlock[idx];
  16873. norm = facetNormals[fib];
  16874. p0 = facetPositions[fib];
  16875. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16876. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16877. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16878. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16879. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16880. projx = x + norm.x * t0;
  16881. projy = y + norm.y * t0;
  16882. projz = z + norm.z * t0;
  16883. tmpx = projx - x;
  16884. tmpy = projy - y;
  16885. tmpz = projz - z;
  16886. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16887. if (tmpDistance < shortest) {
  16888. shortest = tmpDistance;
  16889. closest = fib;
  16890. if (projected) {
  16891. projected.x = projx;
  16892. projected.y = projy;
  16893. projected.z = projz;
  16894. }
  16895. }
  16896. }
  16897. }
  16898. return closest;
  16899. };
  16900. /**
  16901. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16902. */
  16903. AbstractMesh.prototype.getFacetDataParameters = function () {
  16904. return this._facetParameters;
  16905. };
  16906. /**
  16907. * Disables the feature FacetData and frees the related memory.
  16908. * Returns the AbstractMesh.
  16909. */
  16910. AbstractMesh.prototype.disableFacetData = function () {
  16911. if (this._facetDataEnabled) {
  16912. this._facetDataEnabled = false;
  16913. this._facetPositions = new Array();
  16914. this._facetNormals = new Array();
  16915. this._facetPartitioning = new Array();
  16916. this._facetParameters = null;
  16917. this._depthSortedIndices = new Uint32Array(0);
  16918. }
  16919. return this;
  16920. };
  16921. /**
  16922. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16923. * Returns the mesh.
  16924. */
  16925. AbstractMesh.prototype.updateIndices = function (indices) {
  16926. return this;
  16927. };
  16928. /**
  16929. * The mesh Geometry. Actually used by the Mesh object.
  16930. * Returns a blank geometry object.
  16931. */
  16932. /**
  16933. * Creates new normals data for the mesh.
  16934. * @param updatable.
  16935. */
  16936. AbstractMesh.prototype.createNormals = function (updatable) {
  16937. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16938. var indices = this.getIndices();
  16939. var normals;
  16940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16941. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16942. }
  16943. else {
  16944. normals = [];
  16945. }
  16946. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16947. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16948. };
  16949. /**
  16950. * Align the mesh with a normal.
  16951. * Returns the mesh.
  16952. */
  16953. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16954. if (!upDirection) {
  16955. upDirection = BABYLON.Axis.Y;
  16956. }
  16957. var axisX = BABYLON.Tmp.Vector3[0];
  16958. var axisZ = BABYLON.Tmp.Vector3[1];
  16959. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16960. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16961. if (this.rotationQuaternion) {
  16962. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16963. }
  16964. else {
  16965. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16966. }
  16967. return this;
  16968. };
  16969. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16970. var engine = this.getEngine();
  16971. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16972. this._isOccluded = false;
  16973. return;
  16974. }
  16975. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16976. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16977. if (isOcclusionQueryAvailable) {
  16978. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16979. this._isOcclusionQueryInProgress = false;
  16980. this._occlusionInternalRetryCounter = 0;
  16981. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16982. }
  16983. else {
  16984. this._occlusionInternalRetryCounter++;
  16985. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16986. this._isOcclusionQueryInProgress = false;
  16987. this._occlusionInternalRetryCounter = 0;
  16988. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16989. // if strict continue the last state of the object.
  16990. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16991. }
  16992. else {
  16993. return;
  16994. }
  16995. }
  16996. }
  16997. var scene = this.getScene();
  16998. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16999. if (!this._occlusionQuery) {
  17000. this._occlusionQuery = engine.createQuery();
  17001. }
  17002. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17003. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17004. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17005. this._isOcclusionQueryInProgress = true;
  17006. };
  17007. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17008. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17009. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17010. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17011. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17012. return AbstractMesh;
  17013. }(BABYLON.TransformNode));
  17014. BABYLON.AbstractMesh = AbstractMesh;
  17015. })(BABYLON || (BABYLON = {}));
  17016. //# sourceMappingURL=babylon.abstractMesh.js.map
  17017. var BABYLON;
  17018. (function (BABYLON) {
  17019. var Light = /** @class */ (function (_super) {
  17020. __extends(Light, _super);
  17021. /**
  17022. * Creates a Light object in the scene.
  17023. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17024. */
  17025. function Light(name, scene) {
  17026. var _this = _super.call(this, name, scene) || this;
  17027. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17028. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17029. _this.intensity = 1.0;
  17030. _this.range = Number.MAX_VALUE;
  17031. /**
  17032. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17033. * of light.
  17034. */
  17035. _this._photometricScale = 1.0;
  17036. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17037. _this._radius = 0.00001;
  17038. _this.renderPriority = 0;
  17039. /**
  17040. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17041. * the current shadow generator.
  17042. */
  17043. _this.shadowEnabled = true;
  17044. _this._excludeWithLayerMask = 0;
  17045. _this._includeOnlyWithLayerMask = 0;
  17046. _this._lightmapMode = 0;
  17047. _this._excludedMeshesIds = new Array();
  17048. _this._includedOnlyMeshesIds = new Array();
  17049. _this.getScene().addLight(_this);
  17050. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17051. _this._buildUniformLayout();
  17052. _this.includedOnlyMeshes = new Array();
  17053. _this.excludedMeshes = new Array();
  17054. _this._resyncMeshes();
  17055. return _this;
  17056. }
  17057. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17058. /**
  17059. * If every light affecting the material is in this lightmapMode,
  17060. * material.lightmapTexture adds or multiplies
  17061. * (depends on material.useLightmapAsShadowmap)
  17062. * after every other light calculations.
  17063. */
  17064. get: function () {
  17065. return Light._LIGHTMAP_DEFAULT;
  17066. },
  17067. enumerable: true,
  17068. configurable: true
  17069. });
  17070. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17071. /**
  17072. * material.lightmapTexture as only diffuse lighting from this light
  17073. * adds only specular lighting from this light
  17074. * adds dynamic shadows
  17075. */
  17076. get: function () {
  17077. return Light._LIGHTMAP_SPECULAR;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17083. /**
  17084. * material.lightmapTexture as only lighting
  17085. * no light calculation from this light
  17086. * only adds dynamic shadows from this light
  17087. */
  17088. get: function () {
  17089. return Light._LIGHTMAP_SHADOWSONLY;
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17095. /**
  17096. * Each light type uses the default quantity according to its type:
  17097. * point/spot lights use luminous intensity
  17098. * directional lights use illuminance
  17099. */
  17100. get: function () {
  17101. return Light._INTENSITYMODE_AUTOMATIC;
  17102. },
  17103. enumerable: true,
  17104. configurable: true
  17105. });
  17106. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17107. /**
  17108. * lumen (lm)
  17109. */
  17110. get: function () {
  17111. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17112. },
  17113. enumerable: true,
  17114. configurable: true
  17115. });
  17116. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17117. /**
  17118. * candela (lm/sr)
  17119. */
  17120. get: function () {
  17121. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17122. },
  17123. enumerable: true,
  17124. configurable: true
  17125. });
  17126. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17127. /**
  17128. * lux (lm/m^2)
  17129. */
  17130. get: function () {
  17131. return Light._INTENSITYMODE_ILLUMINANCE;
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17137. /**
  17138. * nit (cd/m^2)
  17139. */
  17140. get: function () {
  17141. return Light._INTENSITYMODE_LUMINANCE;
  17142. },
  17143. enumerable: true,
  17144. configurable: true
  17145. });
  17146. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17147. /**
  17148. * Light type const id of the point light.
  17149. */
  17150. get: function () {
  17151. return Light._LIGHTTYPEID_POINTLIGHT;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17157. /**
  17158. * Light type const id of the directional light.
  17159. */
  17160. get: function () {
  17161. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17162. },
  17163. enumerable: true,
  17164. configurable: true
  17165. });
  17166. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17167. /**
  17168. * Light type const id of the spot light.
  17169. */
  17170. get: function () {
  17171. return Light._LIGHTTYPEID_SPOTLIGHT;
  17172. },
  17173. enumerable: true,
  17174. configurable: true
  17175. });
  17176. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17177. /**
  17178. * Light type const id of the hemispheric light.
  17179. */
  17180. get: function () {
  17181. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17182. },
  17183. enumerable: true,
  17184. configurable: true
  17185. });
  17186. Object.defineProperty(Light.prototype, "intensityMode", {
  17187. /**
  17188. * Gets the photometric scale used to interpret the intensity.
  17189. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17190. */
  17191. get: function () {
  17192. return this._intensityMode;
  17193. },
  17194. /**
  17195. * Sets the photometric scale used to interpret the intensity.
  17196. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17197. */
  17198. set: function (value) {
  17199. this._intensityMode = value;
  17200. this._computePhotometricScale();
  17201. },
  17202. enumerable: true,
  17203. configurable: true
  17204. });
  17205. ;
  17206. ;
  17207. Object.defineProperty(Light.prototype, "radius", {
  17208. /**
  17209. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17210. */
  17211. get: function () {
  17212. return this._radius;
  17213. },
  17214. /**
  17215. * sets the light radius used by PBR Materials to simulate soft area lights.
  17216. */
  17217. set: function (value) {
  17218. this._radius = value;
  17219. this._computePhotometricScale();
  17220. },
  17221. enumerable: true,
  17222. configurable: true
  17223. });
  17224. ;
  17225. ;
  17226. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17227. get: function () {
  17228. return this._includedOnlyMeshes;
  17229. },
  17230. set: function (value) {
  17231. this._includedOnlyMeshes = value;
  17232. this._hookArrayForIncludedOnly(value);
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17238. get: function () {
  17239. return this._excludedMeshes;
  17240. },
  17241. set: function (value) {
  17242. this._excludedMeshes = value;
  17243. this._hookArrayForExcluded(value);
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17249. get: function () {
  17250. return this._excludeWithLayerMask;
  17251. },
  17252. set: function (value) {
  17253. this._excludeWithLayerMask = value;
  17254. this._resyncMeshes();
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17260. get: function () {
  17261. return this._includeOnlyWithLayerMask;
  17262. },
  17263. set: function (value) {
  17264. this._includeOnlyWithLayerMask = value;
  17265. this._resyncMeshes();
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(Light.prototype, "lightmapMode", {
  17271. get: function () {
  17272. return this._lightmapMode;
  17273. },
  17274. set: function (value) {
  17275. if (this._lightmapMode === value) {
  17276. return;
  17277. }
  17278. this._lightmapMode = value;
  17279. this._markMeshesAsLightDirty();
  17280. },
  17281. enumerable: true,
  17282. configurable: true
  17283. });
  17284. Light.prototype._buildUniformLayout = function () {
  17285. // Overridden
  17286. };
  17287. /**
  17288. * Returns the string "Light".
  17289. */
  17290. Light.prototype.getClassName = function () {
  17291. return "Light";
  17292. };
  17293. /**
  17294. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17295. */
  17296. Light.prototype.toString = function (fullDetails) {
  17297. var ret = "Name: " + this.name;
  17298. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17299. if (this.animations) {
  17300. for (var i = 0; i < this.animations.length; i++) {
  17301. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17302. }
  17303. }
  17304. if (fullDetails) {
  17305. }
  17306. return ret;
  17307. };
  17308. /**
  17309. * Set the enabled state of this node.
  17310. * @param {boolean} value - the new enabled state
  17311. * @see isEnabled
  17312. */
  17313. Light.prototype.setEnabled = function (value) {
  17314. _super.prototype.setEnabled.call(this, value);
  17315. this._resyncMeshes();
  17316. };
  17317. /**
  17318. * Returns the Light associated shadow generator.
  17319. */
  17320. Light.prototype.getShadowGenerator = function () {
  17321. return this._shadowGenerator;
  17322. };
  17323. /**
  17324. * Returns a Vector3, the absolute light position in the World.
  17325. */
  17326. Light.prototype.getAbsolutePosition = function () {
  17327. return BABYLON.Vector3.Zero();
  17328. };
  17329. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17330. };
  17331. Light.prototype._getWorldMatrix = function () {
  17332. return BABYLON.Matrix.Identity();
  17333. };
  17334. /**
  17335. * Boolean : True if the light will affect the passed mesh.
  17336. */
  17337. Light.prototype.canAffectMesh = function (mesh) {
  17338. if (!mesh) {
  17339. return true;
  17340. }
  17341. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17342. return false;
  17343. }
  17344. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17345. return false;
  17346. }
  17347. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17348. return false;
  17349. }
  17350. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17351. return false;
  17352. }
  17353. return true;
  17354. };
  17355. /**
  17356. * Returns the light World matrix.
  17357. */
  17358. Light.prototype.getWorldMatrix = function () {
  17359. this._currentRenderId = this.getScene().getRenderId();
  17360. var worldMatrix = this._getWorldMatrix();
  17361. if (this.parent && this.parent.getWorldMatrix) {
  17362. if (!this._parentedWorldMatrix) {
  17363. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17364. }
  17365. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17366. this._markSyncedWithParent();
  17367. return this._parentedWorldMatrix;
  17368. }
  17369. return worldMatrix;
  17370. };
  17371. /**
  17372. * Sort function to order lights for rendering.
  17373. * @param a First Light object to compare to second.
  17374. * @param b Second Light object to compare first.
  17375. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17376. */
  17377. Light.compareLightsPriority = function (a, b) {
  17378. //shadow-casting lights have priority over non-shadow-casting lights
  17379. //the renderPrioirty is a secondary sort criterion
  17380. if (a.shadowEnabled !== b.shadowEnabled) {
  17381. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17382. }
  17383. return b.renderPriority - a.renderPriority;
  17384. };
  17385. /**
  17386. * Disposes the light.
  17387. */
  17388. Light.prototype.dispose = function () {
  17389. if (this._shadowGenerator) {
  17390. this._shadowGenerator.dispose();
  17391. this._shadowGenerator = null;
  17392. }
  17393. // Animations
  17394. this.getScene().stopAnimation(this);
  17395. this._uniformBuffer.dispose();
  17396. // Remove from scene
  17397. this.getScene().removeLight(this);
  17398. _super.prototype.dispose.call(this);
  17399. };
  17400. /**
  17401. * Returns the light type ID (integer).
  17402. */
  17403. Light.prototype.getTypeID = function () {
  17404. return 0;
  17405. };
  17406. /**
  17407. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17408. */
  17409. Light.prototype.getScaledIntensity = function () {
  17410. return this._photometricScale * this.intensity;
  17411. };
  17412. /**
  17413. * Returns a new Light object, named "name", from the current one.
  17414. */
  17415. Light.prototype.clone = function (name) {
  17416. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17417. if (!constructor) {
  17418. return null;
  17419. }
  17420. return BABYLON.SerializationHelper.Clone(constructor, this);
  17421. };
  17422. /**
  17423. * Serializes the current light into a Serialization object.
  17424. * Returns the serialized object.
  17425. */
  17426. Light.prototype.serialize = function () {
  17427. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17428. // Type
  17429. serializationObject.type = this.getTypeID();
  17430. // Parent
  17431. if (this.parent) {
  17432. serializationObject.parentId = this.parent.id;
  17433. }
  17434. // Inclusion / exclusions
  17435. if (this.excludedMeshes.length > 0) {
  17436. serializationObject.excludedMeshesIds = [];
  17437. this.excludedMeshes.forEach(function (mesh) {
  17438. serializationObject.excludedMeshesIds.push(mesh.id);
  17439. });
  17440. }
  17441. if (this.includedOnlyMeshes.length > 0) {
  17442. serializationObject.includedOnlyMeshesIds = [];
  17443. this.includedOnlyMeshes.forEach(function (mesh) {
  17444. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17445. });
  17446. }
  17447. // Animations
  17448. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17449. serializationObject.ranges = this.serializeAnimationRanges();
  17450. return serializationObject;
  17451. };
  17452. /**
  17453. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17454. * This new light is named "name" and added to the passed scene.
  17455. */
  17456. Light.GetConstructorFromName = function (type, name, scene) {
  17457. switch (type) {
  17458. case 0:
  17459. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17460. case 1:
  17461. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17462. case 2:
  17463. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17464. case 3:
  17465. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17466. }
  17467. return null;
  17468. };
  17469. /**
  17470. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17471. */
  17472. Light.Parse = function (parsedLight, scene) {
  17473. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17474. if (!constructor) {
  17475. return null;
  17476. }
  17477. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17478. // Inclusion / exclusions
  17479. if (parsedLight.excludedMeshesIds) {
  17480. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17481. }
  17482. if (parsedLight.includedOnlyMeshesIds) {
  17483. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17484. }
  17485. // Parent
  17486. if (parsedLight.parentId) {
  17487. light._waitingParentId = parsedLight.parentId;
  17488. }
  17489. // Animations
  17490. if (parsedLight.animations) {
  17491. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17492. var parsedAnimation = parsedLight.animations[animationIndex];
  17493. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17494. }
  17495. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17496. }
  17497. if (parsedLight.autoAnimate) {
  17498. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17499. }
  17500. return light;
  17501. };
  17502. Light.prototype._hookArrayForExcluded = function (array) {
  17503. var _this = this;
  17504. var oldPush = array.push;
  17505. array.push = function () {
  17506. var items = [];
  17507. for (var _i = 0; _i < arguments.length; _i++) {
  17508. items[_i] = arguments[_i];
  17509. }
  17510. var result = oldPush.apply(array, items);
  17511. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17512. var item = items_1[_a];
  17513. item._resyncLighSource(_this);
  17514. }
  17515. return result;
  17516. };
  17517. var oldSplice = array.splice;
  17518. array.splice = function (index, deleteCount) {
  17519. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17520. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17521. var item = deleted_1[_i];
  17522. item._resyncLighSource(_this);
  17523. }
  17524. return deleted;
  17525. };
  17526. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17527. var item = array_1[_i];
  17528. item._resyncLighSource(this);
  17529. }
  17530. };
  17531. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17532. var _this = this;
  17533. var oldPush = array.push;
  17534. array.push = function () {
  17535. var items = [];
  17536. for (var _i = 0; _i < arguments.length; _i++) {
  17537. items[_i] = arguments[_i];
  17538. }
  17539. var result = oldPush.apply(array, items);
  17540. _this._resyncMeshes();
  17541. return result;
  17542. };
  17543. var oldSplice = array.splice;
  17544. array.splice = function (index, deleteCount) {
  17545. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17546. _this._resyncMeshes();
  17547. return deleted;
  17548. };
  17549. this._resyncMeshes();
  17550. };
  17551. Light.prototype._resyncMeshes = function () {
  17552. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17553. var mesh = _a[_i];
  17554. mesh._resyncLighSource(this);
  17555. }
  17556. };
  17557. Light.prototype._markMeshesAsLightDirty = function () {
  17558. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17559. var mesh = _a[_i];
  17560. if (mesh._lightSources.indexOf(this) !== -1) {
  17561. mesh._markSubMeshesAsLightDirty();
  17562. }
  17563. }
  17564. };
  17565. /**
  17566. * Recomputes the cached photometric scale if needed.
  17567. */
  17568. Light.prototype._computePhotometricScale = function () {
  17569. this._photometricScale = this._getPhotometricScale();
  17570. this.getScene().resetCachedMaterial();
  17571. };
  17572. /**
  17573. * Returns the Photometric Scale according to the light type and intensity mode.
  17574. */
  17575. Light.prototype._getPhotometricScale = function () {
  17576. var photometricScale = 0.0;
  17577. var lightTypeID = this.getTypeID();
  17578. //get photometric mode
  17579. var photometricMode = this.intensityMode;
  17580. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17581. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17582. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17583. }
  17584. else {
  17585. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17586. }
  17587. }
  17588. //compute photometric scale
  17589. switch (lightTypeID) {
  17590. case Light.LIGHTTYPEID_POINTLIGHT:
  17591. case Light.LIGHTTYPEID_SPOTLIGHT:
  17592. switch (photometricMode) {
  17593. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17594. photometricScale = 1.0 / (4.0 * Math.PI);
  17595. break;
  17596. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17597. photometricScale = 1.0;
  17598. break;
  17599. case Light.INTENSITYMODE_LUMINANCE:
  17600. photometricScale = this.radius * this.radius;
  17601. break;
  17602. }
  17603. break;
  17604. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17605. switch (photometricMode) {
  17606. case Light.INTENSITYMODE_ILLUMINANCE:
  17607. photometricScale = 1.0;
  17608. break;
  17609. case Light.INTENSITYMODE_LUMINANCE:
  17610. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17611. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17612. var apexAngleRadians = this.radius;
  17613. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17614. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17615. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17616. photometricScale = solidAngle;
  17617. break;
  17618. }
  17619. break;
  17620. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17621. // No fall off in hemisperic light.
  17622. photometricScale = 1.0;
  17623. break;
  17624. }
  17625. return photometricScale;
  17626. };
  17627. Light.prototype._reorderLightsInScene = function () {
  17628. var scene = this.getScene();
  17629. if (this._renderPriority != 0) {
  17630. scene.requireLightSorting = true;
  17631. }
  17632. this.getScene().sortLightsByPriority();
  17633. };
  17634. //lightmapMode Consts
  17635. Light._LIGHTMAP_DEFAULT = 0;
  17636. Light._LIGHTMAP_SPECULAR = 1;
  17637. Light._LIGHTMAP_SHADOWSONLY = 2;
  17638. // Intensity Mode Consts
  17639. Light._INTENSITYMODE_AUTOMATIC = 0;
  17640. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17641. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17642. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17643. Light._INTENSITYMODE_LUMINANCE = 4;
  17644. // Light types ids const.
  17645. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17646. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17647. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17648. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17649. __decorate([
  17650. BABYLON.serializeAsColor3()
  17651. ], Light.prototype, "diffuse", void 0);
  17652. __decorate([
  17653. BABYLON.serializeAsColor3()
  17654. ], Light.prototype, "specular", void 0);
  17655. __decorate([
  17656. BABYLON.serialize()
  17657. ], Light.prototype, "intensity", void 0);
  17658. __decorate([
  17659. BABYLON.serialize()
  17660. ], Light.prototype, "range", void 0);
  17661. __decorate([
  17662. BABYLON.serialize()
  17663. ], Light.prototype, "intensityMode", null);
  17664. __decorate([
  17665. BABYLON.serialize()
  17666. ], Light.prototype, "radius", null);
  17667. __decorate([
  17668. BABYLON.serialize()
  17669. ], Light.prototype, "_renderPriority", void 0);
  17670. __decorate([
  17671. BABYLON.expandToProperty("_reorderLightsInScene")
  17672. ], Light.prototype, "renderPriority", void 0);
  17673. __decorate([
  17674. BABYLON.serialize()
  17675. ], Light.prototype, "shadowEnabled", void 0);
  17676. __decorate([
  17677. BABYLON.serialize("excludeWithLayerMask")
  17678. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17679. __decorate([
  17680. BABYLON.serialize("includeOnlyWithLayerMask")
  17681. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17682. __decorate([
  17683. BABYLON.serialize("lightmapMode")
  17684. ], Light.prototype, "_lightmapMode", void 0);
  17685. return Light;
  17686. }(BABYLON.Node));
  17687. BABYLON.Light = Light;
  17688. })(BABYLON || (BABYLON = {}));
  17689. //# sourceMappingURL=babylon.light.js.map
  17690. var BABYLON;
  17691. (function (BABYLON) {
  17692. var Camera = /** @class */ (function (_super) {
  17693. __extends(Camera, _super);
  17694. function Camera(name, position, scene) {
  17695. var _this = _super.call(this, name, scene) || this;
  17696. _this.upVector = BABYLON.Vector3.Up();
  17697. _this.orthoLeft = null;
  17698. _this.orthoRight = null;
  17699. _this.orthoBottom = null;
  17700. _this.orthoTop = null;
  17701. /**
  17702. * default : 0.8
  17703. * FOV is set in Radians.
  17704. */
  17705. _this.fov = 0.8;
  17706. _this.minZ = 1;
  17707. _this.maxZ = 10000.0;
  17708. _this.inertia = 0.9;
  17709. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17710. _this.isIntermediate = false;
  17711. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17712. /**
  17713. * Restricts the camera to viewing objects with the same layerMask.
  17714. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17715. */
  17716. _this.layerMask = 0x0FFFFFFF;
  17717. /**
  17718. * default : FOVMODE_VERTICAL_FIXED
  17719. * fovMode sets the camera frustum bounds to the viewport bounds.
  17720. */
  17721. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17722. // Camera rig members
  17723. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17724. _this._rigCameras = new Array();
  17725. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17726. _this._skipRendering = false;
  17727. _this.customRenderTargets = new Array();
  17728. // Observables
  17729. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17730. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17731. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17732. _this.onRestoreStateObservable = new BABYLON.Observable();
  17733. // Cache
  17734. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17735. _this._projectionMatrix = new BABYLON.Matrix();
  17736. _this._doNotComputeProjectionMatrix = false;
  17737. _this._postProcesses = new Array();
  17738. _this._transformMatrix = BABYLON.Matrix.Zero();
  17739. _this._activeMeshes = new BABYLON.SmartArray(256);
  17740. _this._globalPosition = BABYLON.Vector3.Zero();
  17741. _this._refreshFrustumPlanes = true;
  17742. _this.getScene().addCamera(_this);
  17743. if (!_this.getScene().activeCamera) {
  17744. _this.getScene().activeCamera = _this;
  17745. }
  17746. _this.position = position;
  17747. return _this;
  17748. }
  17749. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17750. get: function () {
  17751. return Camera._PERSPECTIVE_CAMERA;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17757. get: function () {
  17758. return Camera._ORTHOGRAPHIC_CAMERA;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17764. /**
  17765. * This is the default FOV mode for perspective cameras.
  17766. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17767. *
  17768. */
  17769. get: function () {
  17770. return Camera._FOVMODE_VERTICAL_FIXED;
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17776. /**
  17777. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17778. *
  17779. */
  17780. get: function () {
  17781. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17787. get: function () {
  17788. return Camera._RIG_MODE_NONE;
  17789. },
  17790. enumerable: true,
  17791. configurable: true
  17792. });
  17793. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17794. get: function () {
  17795. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17801. get: function () {
  17802. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17808. get: function () {
  17809. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17815. get: function () {
  17816. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17822. get: function () {
  17823. return Camera._RIG_MODE_VR;
  17824. },
  17825. enumerable: true,
  17826. configurable: true
  17827. });
  17828. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17829. get: function () {
  17830. return Camera._RIG_MODE_WEBVR;
  17831. },
  17832. enumerable: true,
  17833. configurable: true
  17834. });
  17835. /**
  17836. * Store current camera state (fov, position, etc..)
  17837. */
  17838. Camera.prototype.storeState = function () {
  17839. this._stateStored = true;
  17840. this._storedFov = this.fov;
  17841. return this;
  17842. };
  17843. /**
  17844. * Restores the camera state values if it has been stored. You must call storeState() first
  17845. */
  17846. Camera.prototype._restoreStateValues = function () {
  17847. if (!this._stateStored) {
  17848. return false;
  17849. }
  17850. this.fov = this._storedFov;
  17851. return true;
  17852. };
  17853. /**
  17854. * Restored camera state. You must call storeState() first
  17855. */
  17856. Camera.prototype.restoreState = function () {
  17857. if (this._restoreStateValues()) {
  17858. this.onRestoreStateObservable.notifyObservers(this);
  17859. return true;
  17860. }
  17861. return false;
  17862. };
  17863. Camera.prototype.getClassName = function () {
  17864. return "Camera";
  17865. };
  17866. /**
  17867. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17868. */
  17869. Camera.prototype.toString = function (fullDetails) {
  17870. var ret = "Name: " + this.name;
  17871. ret += ", type: " + this.getClassName();
  17872. if (this.animations) {
  17873. for (var i = 0; i < this.animations.length; i++) {
  17874. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17875. }
  17876. }
  17877. if (fullDetails) {
  17878. }
  17879. return ret;
  17880. };
  17881. Object.defineProperty(Camera.prototype, "globalPosition", {
  17882. get: function () {
  17883. return this._globalPosition;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Camera.prototype.getActiveMeshes = function () {
  17889. return this._activeMeshes;
  17890. };
  17891. Camera.prototype.isActiveMesh = function (mesh) {
  17892. return (this._activeMeshes.indexOf(mesh) !== -1);
  17893. };
  17894. //Cache
  17895. Camera.prototype._initCache = function () {
  17896. _super.prototype._initCache.call(this);
  17897. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17898. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17899. this._cache.mode = undefined;
  17900. this._cache.minZ = undefined;
  17901. this._cache.maxZ = undefined;
  17902. this._cache.fov = undefined;
  17903. this._cache.fovMode = undefined;
  17904. this._cache.aspectRatio = undefined;
  17905. this._cache.orthoLeft = undefined;
  17906. this._cache.orthoRight = undefined;
  17907. this._cache.orthoBottom = undefined;
  17908. this._cache.orthoTop = undefined;
  17909. this._cache.renderWidth = undefined;
  17910. this._cache.renderHeight = undefined;
  17911. };
  17912. Camera.prototype._updateCache = function (ignoreParentClass) {
  17913. if (!ignoreParentClass) {
  17914. _super.prototype._updateCache.call(this);
  17915. }
  17916. this._cache.position.copyFrom(this.position);
  17917. this._cache.upVector.copyFrom(this.upVector);
  17918. };
  17919. // Synchronized
  17920. Camera.prototype._isSynchronized = function () {
  17921. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17922. };
  17923. Camera.prototype._isSynchronizedViewMatrix = function () {
  17924. if (!_super.prototype._isSynchronized.call(this))
  17925. return false;
  17926. return this._cache.position.equals(this.position)
  17927. && this._cache.upVector.equals(this.upVector)
  17928. && this.isSynchronizedWithParent();
  17929. };
  17930. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17931. var check = this._cache.mode === this.mode
  17932. && this._cache.minZ === this.minZ
  17933. && this._cache.maxZ === this.maxZ;
  17934. if (!check) {
  17935. return false;
  17936. }
  17937. var engine = this.getEngine();
  17938. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17939. check = this._cache.fov === this.fov
  17940. && this._cache.fovMode === this.fovMode
  17941. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17942. }
  17943. else {
  17944. check = this._cache.orthoLeft === this.orthoLeft
  17945. && this._cache.orthoRight === this.orthoRight
  17946. && this._cache.orthoBottom === this.orthoBottom
  17947. && this._cache.orthoTop === this.orthoTop
  17948. && this._cache.renderWidth === engine.getRenderWidth()
  17949. && this._cache.renderHeight === engine.getRenderHeight();
  17950. }
  17951. return check;
  17952. };
  17953. // Controls
  17954. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17955. };
  17956. Camera.prototype.detachControl = function (element) {
  17957. };
  17958. Camera.prototype.update = function () {
  17959. this._checkInputs();
  17960. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17961. this._updateRigCameras();
  17962. }
  17963. };
  17964. Camera.prototype._checkInputs = function () {
  17965. this.onAfterCheckInputsObservable.notifyObservers(this);
  17966. };
  17967. Object.defineProperty(Camera.prototype, "rigCameras", {
  17968. get: function () {
  17969. return this._rigCameras;
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17975. get: function () {
  17976. return this._rigPostProcess;
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17982. // invalidate framebuffer
  17983. if (this._postProcesses.length > 0) {
  17984. this._postProcesses[0].markTextureDirty();
  17985. }
  17986. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17987. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17988. var cam = this._rigCameras[i];
  17989. var rigPostProcess = cam._rigPostProcess;
  17990. // for VR rig, there does not have to be a post process
  17991. if (rigPostProcess) {
  17992. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17993. if (isPass) {
  17994. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17995. cam.isIntermediate = this._postProcesses.length === 0;
  17996. }
  17997. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17998. rigPostProcess.markTextureDirty();
  17999. }
  18000. else {
  18001. cam._postProcesses = this._postProcesses.slice(0);
  18002. }
  18003. }
  18004. };
  18005. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18006. if (insertAt === void 0) { insertAt = null; }
  18007. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18008. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18009. return 0;
  18010. }
  18011. if (insertAt == null || insertAt < 0) {
  18012. this._postProcesses.push(postProcess);
  18013. }
  18014. else {
  18015. this._postProcesses.splice(insertAt, 0, postProcess);
  18016. }
  18017. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18018. return this._postProcesses.indexOf(postProcess);
  18019. };
  18020. Camera.prototype.detachPostProcess = function (postProcess) {
  18021. var idx = this._postProcesses.indexOf(postProcess);
  18022. if (idx !== -1) {
  18023. this._postProcesses.splice(idx, 1);
  18024. }
  18025. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18026. };
  18027. Camera.prototype.getWorldMatrix = function () {
  18028. if (!this._worldMatrix) {
  18029. this._worldMatrix = BABYLON.Matrix.Identity();
  18030. }
  18031. var viewMatrix = this.getViewMatrix();
  18032. viewMatrix.invertToRef(this._worldMatrix);
  18033. return this._worldMatrix;
  18034. };
  18035. Camera.prototype._getViewMatrix = function () {
  18036. return BABYLON.Matrix.Identity();
  18037. };
  18038. Camera.prototype.getViewMatrix = function (force) {
  18039. if (!force && this._isSynchronizedViewMatrix()) {
  18040. return this._computedViewMatrix;
  18041. }
  18042. this.updateCache();
  18043. this._computedViewMatrix = this._getViewMatrix();
  18044. this._currentRenderId = this.getScene().getRenderId();
  18045. this._refreshFrustumPlanes = true;
  18046. if (!this.parent || !this.parent.getWorldMatrix) {
  18047. this._globalPosition.copyFrom(this.position);
  18048. }
  18049. else {
  18050. if (!this._worldMatrix) {
  18051. this._worldMatrix = BABYLON.Matrix.Identity();
  18052. }
  18053. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18054. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18055. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18056. this._computedViewMatrix.invert();
  18057. this._markSyncedWithParent();
  18058. }
  18059. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18060. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18061. }
  18062. this.onViewMatrixChangedObservable.notifyObservers(this);
  18063. return this._computedViewMatrix;
  18064. };
  18065. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18066. this._doNotComputeProjectionMatrix = true;
  18067. if (projection !== undefined) {
  18068. this._projectionMatrix = projection;
  18069. }
  18070. };
  18071. ;
  18072. Camera.prototype.unfreezeProjectionMatrix = function () {
  18073. this._doNotComputeProjectionMatrix = false;
  18074. };
  18075. ;
  18076. Camera.prototype.getProjectionMatrix = function (force) {
  18077. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18078. return this._projectionMatrix;
  18079. }
  18080. // Cache
  18081. this._cache.mode = this.mode;
  18082. this._cache.minZ = this.minZ;
  18083. this._cache.maxZ = this.maxZ;
  18084. // Matrix
  18085. this._refreshFrustumPlanes = true;
  18086. var engine = this.getEngine();
  18087. var scene = this.getScene();
  18088. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18089. this._cache.fov = this.fov;
  18090. this._cache.fovMode = this.fovMode;
  18091. this._cache.aspectRatio = engine.getAspectRatio(this);
  18092. if (this.minZ <= 0) {
  18093. this.minZ = 0.1;
  18094. }
  18095. if (scene.useRightHandedSystem) {
  18096. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18097. }
  18098. else {
  18099. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18100. }
  18101. }
  18102. else {
  18103. var halfWidth = engine.getRenderWidth() / 2.0;
  18104. var halfHeight = engine.getRenderHeight() / 2.0;
  18105. if (scene.useRightHandedSystem) {
  18106. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18107. }
  18108. else {
  18109. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18110. }
  18111. this._cache.orthoLeft = this.orthoLeft;
  18112. this._cache.orthoRight = this.orthoRight;
  18113. this._cache.orthoBottom = this.orthoBottom;
  18114. this._cache.orthoTop = this.orthoTop;
  18115. this._cache.renderWidth = engine.getRenderWidth();
  18116. this._cache.renderHeight = engine.getRenderHeight();
  18117. }
  18118. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18119. return this._projectionMatrix;
  18120. };
  18121. Camera.prototype.getTranformationMatrix = function () {
  18122. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18123. return this._transformMatrix;
  18124. };
  18125. Camera.prototype.updateFrustumPlanes = function () {
  18126. if (!this._refreshFrustumPlanes) {
  18127. return;
  18128. }
  18129. this.getTranformationMatrix();
  18130. if (!this._frustumPlanes) {
  18131. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18132. }
  18133. else {
  18134. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18135. }
  18136. this._refreshFrustumPlanes = false;
  18137. };
  18138. Camera.prototype.isInFrustum = function (target) {
  18139. this.updateFrustumPlanes();
  18140. return target.isInFrustum(this._frustumPlanes);
  18141. };
  18142. Camera.prototype.isCompletelyInFrustum = function (target) {
  18143. this.updateFrustumPlanes();
  18144. return target.isCompletelyInFrustum(this._frustumPlanes);
  18145. };
  18146. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18147. if (length === void 0) { length = 100; }
  18148. if (!transform) {
  18149. transform = this.getWorldMatrix();
  18150. }
  18151. if (!origin) {
  18152. origin = this.position;
  18153. }
  18154. var forward = new BABYLON.Vector3(0, 0, 1);
  18155. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18156. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18157. return new BABYLON.Ray(origin, direction, length);
  18158. };
  18159. Camera.prototype.dispose = function () {
  18160. // Observables
  18161. this.onViewMatrixChangedObservable.clear();
  18162. this.onProjectionMatrixChangedObservable.clear();
  18163. this.onAfterCheckInputsObservable.clear();
  18164. this.onRestoreStateObservable.clear();
  18165. // Inputs
  18166. if (this.inputs) {
  18167. this.inputs.clear();
  18168. }
  18169. // Animations
  18170. this.getScene().stopAnimation(this);
  18171. // Remove from scene
  18172. this.getScene().removeCamera(this);
  18173. while (this._rigCameras.length > 0) {
  18174. var camera = this._rigCameras.pop();
  18175. if (camera) {
  18176. camera.dispose();
  18177. }
  18178. }
  18179. // Postprocesses
  18180. if (this._rigPostProcess) {
  18181. this._rigPostProcess.dispose(this);
  18182. this._rigPostProcess = null;
  18183. this._postProcesses = [];
  18184. }
  18185. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18186. this._rigPostProcess = null;
  18187. this._postProcesses = [];
  18188. }
  18189. else {
  18190. var i = this._postProcesses.length;
  18191. while (--i >= 0) {
  18192. this._postProcesses[i].dispose(this);
  18193. }
  18194. }
  18195. // Render targets
  18196. var i = this.customRenderTargets.length;
  18197. while (--i >= 0) {
  18198. this.customRenderTargets[i].dispose();
  18199. }
  18200. this.customRenderTargets = [];
  18201. // Active Meshes
  18202. this._activeMeshes.dispose();
  18203. _super.prototype.dispose.call(this);
  18204. };
  18205. Object.defineProperty(Camera.prototype, "leftCamera", {
  18206. // ---- Camera rigs section ----
  18207. get: function () {
  18208. if (this._rigCameras.length < 1) {
  18209. return null;
  18210. }
  18211. return this._rigCameras[0];
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. Object.defineProperty(Camera.prototype, "rightCamera", {
  18217. get: function () {
  18218. if (this._rigCameras.length < 2) {
  18219. return null;
  18220. }
  18221. return this._rigCameras[1];
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Camera.prototype.getLeftTarget = function () {
  18227. if (this._rigCameras.length < 1) {
  18228. return null;
  18229. }
  18230. return this._rigCameras[0].getTarget();
  18231. };
  18232. Camera.prototype.getRightTarget = function () {
  18233. if (this._rigCameras.length < 2) {
  18234. return null;
  18235. }
  18236. return this._rigCameras[1].getTarget();
  18237. };
  18238. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18239. if (this.cameraRigMode === mode) {
  18240. return;
  18241. }
  18242. while (this._rigCameras.length > 0) {
  18243. var camera = this._rigCameras.pop();
  18244. if (camera) {
  18245. camera.dispose();
  18246. }
  18247. }
  18248. this.cameraRigMode = mode;
  18249. this._cameraRigParams = {};
  18250. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18251. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18252. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18253. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18254. // create the rig cameras, unless none
  18255. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18256. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18257. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18258. if (leftCamera && rightCamera) {
  18259. this._rigCameras.push(leftCamera);
  18260. this._rigCameras.push(rightCamera);
  18261. }
  18262. }
  18263. switch (this.cameraRigMode) {
  18264. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18265. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18266. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18267. break;
  18268. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18269. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18270. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18271. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18272. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18273. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18274. break;
  18275. case Camera.RIG_MODE_VR:
  18276. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18277. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18278. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18279. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18280. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18281. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18282. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18283. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18284. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18285. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18286. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18287. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18288. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18289. if (metrics.compensateDistortion) {
  18290. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18291. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18292. }
  18293. break;
  18294. case Camera.RIG_MODE_WEBVR:
  18295. if (rigParams.vrDisplay) {
  18296. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18297. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18298. //Left eye
  18299. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18300. this._rigCameras[0].setCameraRigParameter("left", true);
  18301. //leaving this for future reference
  18302. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18303. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18304. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18305. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18306. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18307. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18308. this._rigCameras[0].parent = this;
  18309. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18310. //Right eye
  18311. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18312. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18313. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18314. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18315. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18316. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18317. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18318. this._rigCameras[1].parent = this;
  18319. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18320. if (Camera.UseAlternateWebVRRendering) {
  18321. this._rigCameras[1]._skipRendering = true;
  18322. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18323. }
  18324. }
  18325. break;
  18326. }
  18327. this._cascadePostProcessesToRigCams();
  18328. this.update();
  18329. };
  18330. Camera.prototype._getVRProjectionMatrix = function () {
  18331. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18332. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18333. return this._projectionMatrix;
  18334. };
  18335. Camera.prototype._updateCameraRotationMatrix = function () {
  18336. //Here for WebVR
  18337. };
  18338. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18339. //Here for WebVR
  18340. };
  18341. /**
  18342. * This function MUST be overwritten by the different WebVR cameras available.
  18343. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18344. */
  18345. Camera.prototype._getWebVRProjectionMatrix = function () {
  18346. return BABYLON.Matrix.Identity();
  18347. };
  18348. /**
  18349. * This function MUST be overwritten by the different WebVR cameras available.
  18350. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18351. */
  18352. Camera.prototype._getWebVRViewMatrix = function () {
  18353. return BABYLON.Matrix.Identity();
  18354. };
  18355. Camera.prototype.setCameraRigParameter = function (name, value) {
  18356. if (!this._cameraRigParams) {
  18357. this._cameraRigParams = {};
  18358. }
  18359. this._cameraRigParams[name] = value;
  18360. //provisionnally:
  18361. if (name === "interaxialDistance") {
  18362. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18363. }
  18364. };
  18365. /**
  18366. * needs to be overridden by children so sub has required properties to be copied
  18367. */
  18368. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18369. return null;
  18370. };
  18371. /**
  18372. * May need to be overridden by children
  18373. */
  18374. Camera.prototype._updateRigCameras = function () {
  18375. for (var i = 0; i < this._rigCameras.length; i++) {
  18376. this._rigCameras[i].minZ = this.minZ;
  18377. this._rigCameras[i].maxZ = this.maxZ;
  18378. this._rigCameras[i].fov = this.fov;
  18379. }
  18380. // only update viewport when ANAGLYPH
  18381. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18382. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18383. }
  18384. };
  18385. Camera.prototype._setupInputs = function () {
  18386. };
  18387. Camera.prototype.serialize = function () {
  18388. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18389. // Type
  18390. serializationObject.type = this.getClassName();
  18391. // Parent
  18392. if (this.parent) {
  18393. serializationObject.parentId = this.parent.id;
  18394. }
  18395. if (this.inputs) {
  18396. this.inputs.serialize(serializationObject);
  18397. }
  18398. // Animations
  18399. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18400. serializationObject.ranges = this.serializeAnimationRanges();
  18401. return serializationObject;
  18402. };
  18403. Camera.prototype.clone = function (name) {
  18404. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18405. };
  18406. Camera.prototype.getDirection = function (localAxis) {
  18407. var result = BABYLON.Vector3.Zero();
  18408. this.getDirectionToRef(localAxis, result);
  18409. return result;
  18410. };
  18411. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18412. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18413. };
  18414. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18415. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18416. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18417. switch (type) {
  18418. case "ArcRotateCamera":
  18419. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18420. case "DeviceOrientationCamera":
  18421. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18422. case "FollowCamera":
  18423. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18424. case "ArcFollowCamera":
  18425. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18426. case "GamepadCamera":
  18427. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18428. case "TouchCamera":
  18429. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18430. case "VirtualJoysticksCamera":
  18431. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18432. case "WebVRFreeCamera":
  18433. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18434. case "WebVRGamepadCamera":
  18435. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18436. case "VRDeviceOrientationFreeCamera":
  18437. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18438. case "VRDeviceOrientationGamepadCamera":
  18439. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18440. case "AnaglyphArcRotateCamera":
  18441. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18442. case "AnaglyphFreeCamera":
  18443. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18444. case "AnaglyphGamepadCamera":
  18445. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18446. case "AnaglyphUniversalCamera":
  18447. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18448. case "StereoscopicArcRotateCamera":
  18449. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18450. case "StereoscopicFreeCamera":
  18451. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18452. case "StereoscopicGamepadCamera":
  18453. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18454. case "StereoscopicUniversalCamera":
  18455. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18456. case "FreeCamera":// Forcing Universal here
  18457. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18458. default:// Universal Camera is the default value
  18459. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18460. }
  18461. };
  18462. Camera.prototype.computeWorldMatrix = function () {
  18463. return this.getWorldMatrix();
  18464. };
  18465. Camera.Parse = function (parsedCamera, scene) {
  18466. var type = parsedCamera.type;
  18467. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18468. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18469. // Parent
  18470. if (parsedCamera.parentId) {
  18471. camera._waitingParentId = parsedCamera.parentId;
  18472. }
  18473. //If camera has an input manager, let it parse inputs settings
  18474. if (camera.inputs) {
  18475. camera.inputs.parse(parsedCamera);
  18476. camera._setupInputs();
  18477. }
  18478. if (camera.setPosition) {
  18479. camera.position.copyFromFloats(0, 0, 0);
  18480. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18481. }
  18482. // Target
  18483. if (parsedCamera.target) {
  18484. if (camera.setTarget) {
  18485. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18486. }
  18487. }
  18488. // Apply 3d rig, when found
  18489. if (parsedCamera.cameraRigMode) {
  18490. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18491. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18492. }
  18493. // Animations
  18494. if (parsedCamera.animations) {
  18495. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18496. var parsedAnimation = parsedCamera.animations[animationIndex];
  18497. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18498. }
  18499. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18500. }
  18501. if (parsedCamera.autoAnimate) {
  18502. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18503. }
  18504. return camera;
  18505. };
  18506. // Statics
  18507. Camera._PERSPECTIVE_CAMERA = 0;
  18508. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18509. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18510. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18511. Camera._RIG_MODE_NONE = 0;
  18512. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18513. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18514. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18515. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18516. Camera._RIG_MODE_VR = 20;
  18517. Camera._RIG_MODE_WEBVR = 21;
  18518. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18519. Camera.UseAlternateWebVRRendering = false;
  18520. __decorate([
  18521. BABYLON.serializeAsVector3()
  18522. ], Camera.prototype, "position", void 0);
  18523. __decorate([
  18524. BABYLON.serializeAsVector3()
  18525. ], Camera.prototype, "upVector", void 0);
  18526. __decorate([
  18527. BABYLON.serialize()
  18528. ], Camera.prototype, "orthoLeft", void 0);
  18529. __decorate([
  18530. BABYLON.serialize()
  18531. ], Camera.prototype, "orthoRight", void 0);
  18532. __decorate([
  18533. BABYLON.serialize()
  18534. ], Camera.prototype, "orthoBottom", void 0);
  18535. __decorate([
  18536. BABYLON.serialize()
  18537. ], Camera.prototype, "orthoTop", void 0);
  18538. __decorate([
  18539. BABYLON.serialize()
  18540. ], Camera.prototype, "fov", void 0);
  18541. __decorate([
  18542. BABYLON.serialize()
  18543. ], Camera.prototype, "minZ", void 0);
  18544. __decorate([
  18545. BABYLON.serialize()
  18546. ], Camera.prototype, "maxZ", void 0);
  18547. __decorate([
  18548. BABYLON.serialize()
  18549. ], Camera.prototype, "inertia", void 0);
  18550. __decorate([
  18551. BABYLON.serialize()
  18552. ], Camera.prototype, "mode", void 0);
  18553. __decorate([
  18554. BABYLON.serialize()
  18555. ], Camera.prototype, "layerMask", void 0);
  18556. __decorate([
  18557. BABYLON.serialize()
  18558. ], Camera.prototype, "fovMode", void 0);
  18559. __decorate([
  18560. BABYLON.serialize()
  18561. ], Camera.prototype, "cameraRigMode", void 0);
  18562. __decorate([
  18563. BABYLON.serialize()
  18564. ], Camera.prototype, "interaxialDistance", void 0);
  18565. __decorate([
  18566. BABYLON.serialize()
  18567. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18568. return Camera;
  18569. }(BABYLON.Node));
  18570. BABYLON.Camera = Camera;
  18571. })(BABYLON || (BABYLON = {}));
  18572. //# sourceMappingURL=babylon.camera.js.map
  18573. var BABYLON;
  18574. (function (BABYLON) {
  18575. var RenderingManager = /** @class */ (function () {
  18576. function RenderingManager(scene) {
  18577. this._renderingGroups = new Array();
  18578. this._autoClearDepthStencil = {};
  18579. this._customOpaqueSortCompareFn = {};
  18580. this._customAlphaTestSortCompareFn = {};
  18581. this._customTransparentSortCompareFn = {};
  18582. this._renderinGroupInfo = null;
  18583. this._scene = scene;
  18584. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18585. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18586. }
  18587. }
  18588. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18589. if (depth === void 0) { depth = true; }
  18590. if (stencil === void 0) { stencil = true; }
  18591. if (this._depthStencilBufferAlreadyCleaned) {
  18592. return;
  18593. }
  18594. this._scene.getEngine().clear(null, false, depth, stencil);
  18595. this._depthStencilBufferAlreadyCleaned = true;
  18596. };
  18597. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18598. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18599. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18600. var info = null;
  18601. if (observable) {
  18602. if (!this._renderinGroupInfo) {
  18603. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18604. }
  18605. info = this._renderinGroupInfo;
  18606. info.scene = this._scene;
  18607. info.camera = this._scene.activeCamera;
  18608. }
  18609. // Dispatch sprites
  18610. if (renderSprites) {
  18611. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18612. var manager = this._scene.spriteManagers[index];
  18613. this.dispatchSprites(manager);
  18614. }
  18615. }
  18616. // Render
  18617. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18618. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18619. var renderingGroup = this._renderingGroups[index];
  18620. if (!renderingGroup && !observable)
  18621. continue;
  18622. var renderingGroupMask = 0;
  18623. // Fire PRECLEAR stage
  18624. if (observable && info) {
  18625. renderingGroupMask = Math.pow(2, index);
  18626. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18627. info.renderingGroupId = index;
  18628. observable.notifyObservers(info, renderingGroupMask);
  18629. }
  18630. // Clear depth/stencil if needed
  18631. if (RenderingManager.AUTOCLEAR) {
  18632. var autoClear = this._autoClearDepthStencil[index];
  18633. if (autoClear && autoClear.autoClear) {
  18634. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18635. }
  18636. }
  18637. if (observable && info) {
  18638. // Fire PREOPAQUE stage
  18639. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18640. observable.notifyObservers(info, renderingGroupMask);
  18641. // Fire PRETRANSPARENT stage
  18642. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18643. observable.notifyObservers(info, renderingGroupMask);
  18644. }
  18645. if (renderingGroup)
  18646. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18647. // Fire POSTTRANSPARENT stage
  18648. if (observable && info) {
  18649. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18650. observable.notifyObservers(info, renderingGroupMask);
  18651. }
  18652. }
  18653. };
  18654. RenderingManager.prototype.reset = function () {
  18655. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18656. var renderingGroup = this._renderingGroups[index];
  18657. if (renderingGroup) {
  18658. renderingGroup.prepare();
  18659. }
  18660. }
  18661. };
  18662. RenderingManager.prototype.dispose = function () {
  18663. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18664. var renderingGroup = this._renderingGroups[index];
  18665. if (renderingGroup) {
  18666. renderingGroup.dispose();
  18667. }
  18668. }
  18669. this._renderingGroups.length = 0;
  18670. };
  18671. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18672. if (this._renderingGroups[renderingGroupId] === undefined) {
  18673. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18674. }
  18675. };
  18676. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18677. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18678. this._prepareRenderingGroup(renderingGroupId);
  18679. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18680. };
  18681. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18682. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18683. this._prepareRenderingGroup(renderingGroupId);
  18684. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18685. };
  18686. /**
  18687. * @param subMesh The submesh to dispatch
  18688. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18689. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18690. */
  18691. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18692. if (mesh === undefined) {
  18693. mesh = subMesh.getMesh();
  18694. }
  18695. var renderingGroupId = mesh.renderingGroupId || 0;
  18696. this._prepareRenderingGroup(renderingGroupId);
  18697. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18698. };
  18699. /**
  18700. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18701. * This allowed control for front to back rendering or reversly depending of the special needs.
  18702. *
  18703. * @param renderingGroupId The rendering group id corresponding to its index
  18704. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18705. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18706. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18707. */
  18708. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18709. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18710. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18711. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18712. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18713. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18714. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18715. if (this._renderingGroups[renderingGroupId]) {
  18716. var group = this._renderingGroups[renderingGroupId];
  18717. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18718. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18719. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18720. }
  18721. };
  18722. /**
  18723. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18724. *
  18725. * @param renderingGroupId The rendering group id corresponding to its index
  18726. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18727. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18728. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18729. */
  18730. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18731. if (depth === void 0) { depth = true; }
  18732. if (stencil === void 0) { stencil = true; }
  18733. this._autoClearDepthStencil[renderingGroupId] = {
  18734. autoClear: autoClearDepthStencil,
  18735. depth: depth,
  18736. stencil: stencil
  18737. };
  18738. };
  18739. /**
  18740. * The max id used for rendering groups (not included)
  18741. */
  18742. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18743. /**
  18744. * The min id used for rendering groups (included)
  18745. */
  18746. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18747. /**
  18748. * Used to globally prevent autoclearing scenes.
  18749. */
  18750. RenderingManager.AUTOCLEAR = true;
  18751. return RenderingManager;
  18752. }());
  18753. BABYLON.RenderingManager = RenderingManager;
  18754. })(BABYLON || (BABYLON = {}));
  18755. //# sourceMappingURL=babylon.renderingManager.js.map
  18756. var BABYLON;
  18757. (function (BABYLON) {
  18758. var RenderingGroup = /** @class */ (function () {
  18759. /**
  18760. * Creates a new rendering group.
  18761. * @param index The rendering group index
  18762. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18763. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18764. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18765. */
  18766. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18767. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18768. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18769. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18770. this.index = index;
  18771. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18772. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18773. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18774. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18775. this._particleSystems = new BABYLON.SmartArray(256);
  18776. this._spriteManagers = new BABYLON.SmartArray(256);
  18777. this._edgesRenderers = new BABYLON.SmartArray(16);
  18778. this._scene = scene;
  18779. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18780. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18781. this.transparentSortCompareFn = transparentSortCompareFn;
  18782. }
  18783. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18784. /**
  18785. * Set the opaque sort comparison function.
  18786. * If null the sub meshes will be render in the order they were created
  18787. */
  18788. set: function (value) {
  18789. this._opaqueSortCompareFn = value;
  18790. if (value) {
  18791. this._renderOpaque = this.renderOpaqueSorted;
  18792. }
  18793. else {
  18794. this._renderOpaque = RenderingGroup.renderUnsorted;
  18795. }
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18801. /**
  18802. * Set the alpha test sort comparison function.
  18803. * If null the sub meshes will be render in the order they were created
  18804. */
  18805. set: function (value) {
  18806. this._alphaTestSortCompareFn = value;
  18807. if (value) {
  18808. this._renderAlphaTest = this.renderAlphaTestSorted;
  18809. }
  18810. else {
  18811. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18812. }
  18813. },
  18814. enumerable: true,
  18815. configurable: true
  18816. });
  18817. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18818. /**
  18819. * Set the transparent sort comparison function.
  18820. * If null the sub meshes will be render in the order they were created
  18821. */
  18822. set: function (value) {
  18823. if (value) {
  18824. this._transparentSortCompareFn = value;
  18825. }
  18826. else {
  18827. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18828. }
  18829. this._renderTransparent = this.renderTransparentSorted;
  18830. },
  18831. enumerable: true,
  18832. configurable: true
  18833. });
  18834. /**
  18835. * Render all the sub meshes contained in the group.
  18836. * @param customRenderFunction Used to override the default render behaviour of the group.
  18837. * @returns true if rendered some submeshes.
  18838. */
  18839. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18840. if (customRenderFunction) {
  18841. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18842. return;
  18843. }
  18844. var engine = this._scene.getEngine();
  18845. // Depth only
  18846. if (this._depthOnlySubMeshes.length !== 0) {
  18847. engine.setColorWrite(false);
  18848. this._renderAlphaTest(this._depthOnlySubMeshes);
  18849. engine.setColorWrite(true);
  18850. }
  18851. // Opaque
  18852. if (this._opaqueSubMeshes.length !== 0) {
  18853. this._renderOpaque(this._opaqueSubMeshes);
  18854. }
  18855. // Alpha test
  18856. if (this._alphaTestSubMeshes.length !== 0) {
  18857. this._renderAlphaTest(this._alphaTestSubMeshes);
  18858. }
  18859. var stencilState = engine.getStencilBuffer();
  18860. engine.setStencilBuffer(false);
  18861. // Sprites
  18862. if (renderSprites) {
  18863. this._renderSprites();
  18864. }
  18865. // Particles
  18866. if (renderParticles) {
  18867. this._renderParticles(activeMeshes);
  18868. }
  18869. if (this.onBeforeTransparentRendering) {
  18870. this.onBeforeTransparentRendering();
  18871. }
  18872. // Transparent
  18873. if (this._transparentSubMeshes.length !== 0) {
  18874. this._renderTransparent(this._transparentSubMeshes);
  18875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18876. }
  18877. // Set back stencil to false in case it changes before the edge renderer.
  18878. engine.setStencilBuffer(false);
  18879. // Edges
  18880. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18881. this._edgesRenderers.data[edgesRendererIndex].render();
  18882. }
  18883. // Restore Stencil state.
  18884. engine.setStencilBuffer(stencilState);
  18885. };
  18886. /**
  18887. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18888. * @param subMeshes The submeshes to render
  18889. */
  18890. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18891. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18892. };
  18893. /**
  18894. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18895. * @param subMeshes The submeshes to render
  18896. */
  18897. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18898. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18899. };
  18900. /**
  18901. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18902. * @param subMeshes The submeshes to render
  18903. */
  18904. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18905. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18906. };
  18907. /**
  18908. * Renders the submeshes in a specified order.
  18909. * @param subMeshes The submeshes to sort before render
  18910. * @param sortCompareFn The comparison function use to sort
  18911. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18912. * @param transparent Specifies to activate blending if true
  18913. */
  18914. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18915. var subIndex = 0;
  18916. var subMesh;
  18917. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18918. for (; subIndex < subMeshes.length; subIndex++) {
  18919. subMesh = subMeshes.data[subIndex];
  18920. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18921. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18922. }
  18923. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18924. if (sortCompareFn) {
  18925. sortedArray.sort(sortCompareFn);
  18926. }
  18927. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18928. subMesh = sortedArray[subIndex];
  18929. if (transparent) {
  18930. var material = subMesh.getMaterial();
  18931. if (material && material.needDepthPrePass) {
  18932. var engine = material.getScene().getEngine();
  18933. engine.setColorWrite(false);
  18934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18935. subMesh.render(false);
  18936. engine.setColorWrite(true);
  18937. }
  18938. }
  18939. subMesh.render(transparent);
  18940. }
  18941. };
  18942. /**
  18943. * Renders the submeshes in the order they were dispatched (no sort applied).
  18944. * @param subMeshes The submeshes to render
  18945. */
  18946. RenderingGroup.renderUnsorted = function (subMeshes) {
  18947. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18948. var submesh = subMeshes.data[subIndex];
  18949. submesh.render(false);
  18950. }
  18951. };
  18952. /**
  18953. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18954. * are rendered back to front if in the same alpha index.
  18955. *
  18956. * @param a The first submesh
  18957. * @param b The second submesh
  18958. * @returns The result of the comparison
  18959. */
  18960. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18961. // Alpha index first
  18962. if (a._alphaIndex > b._alphaIndex) {
  18963. return 1;
  18964. }
  18965. if (a._alphaIndex < b._alphaIndex) {
  18966. return -1;
  18967. }
  18968. // Then distance to camera
  18969. return RenderingGroup.backToFrontSortCompare(a, b);
  18970. };
  18971. /**
  18972. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18973. * are rendered back to front.
  18974. *
  18975. * @param a The first submesh
  18976. * @param b The second submesh
  18977. * @returns The result of the comparison
  18978. */
  18979. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18980. // Then distance to camera
  18981. if (a._distanceToCamera < b._distanceToCamera) {
  18982. return 1;
  18983. }
  18984. if (a._distanceToCamera > b._distanceToCamera) {
  18985. return -1;
  18986. }
  18987. return 0;
  18988. };
  18989. /**
  18990. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18991. * are rendered front to back (prevent overdraw).
  18992. *
  18993. * @param a The first submesh
  18994. * @param b The second submesh
  18995. * @returns The result of the comparison
  18996. */
  18997. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18998. // Then distance to camera
  18999. if (a._distanceToCamera < b._distanceToCamera) {
  19000. return -1;
  19001. }
  19002. if (a._distanceToCamera > b._distanceToCamera) {
  19003. return 1;
  19004. }
  19005. return 0;
  19006. };
  19007. /**
  19008. * Resets the different lists of submeshes to prepare a new frame.
  19009. */
  19010. RenderingGroup.prototype.prepare = function () {
  19011. this._opaqueSubMeshes.reset();
  19012. this._transparentSubMeshes.reset();
  19013. this._alphaTestSubMeshes.reset();
  19014. this._depthOnlySubMeshes.reset();
  19015. this._particleSystems.reset();
  19016. this._spriteManagers.reset();
  19017. this._edgesRenderers.reset();
  19018. };
  19019. RenderingGroup.prototype.dispose = function () {
  19020. this._opaqueSubMeshes.dispose();
  19021. this._transparentSubMeshes.dispose();
  19022. this._alphaTestSubMeshes.dispose();
  19023. this._depthOnlySubMeshes.dispose();
  19024. this._particleSystems.dispose();
  19025. this._spriteManagers.dispose();
  19026. this._edgesRenderers.dispose();
  19027. };
  19028. /**
  19029. * Inserts the submesh in its correct queue depending on its material.
  19030. * @param subMesh The submesh to dispatch
  19031. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19032. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19033. */
  19034. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19035. // Get mesh and materials if not provided
  19036. if (mesh === undefined) {
  19037. mesh = subMesh.getMesh();
  19038. }
  19039. if (material === undefined) {
  19040. material = subMesh.getMaterial();
  19041. }
  19042. if (material === null || material === undefined) {
  19043. return;
  19044. }
  19045. if (material.needAlphaBlendingForMesh(mesh)) {
  19046. this._transparentSubMeshes.push(subMesh);
  19047. }
  19048. else if (material.needAlphaTesting()) {
  19049. if (material.needDepthPrePass) {
  19050. this._depthOnlySubMeshes.push(subMesh);
  19051. }
  19052. this._alphaTestSubMeshes.push(subMesh);
  19053. }
  19054. else {
  19055. if (material.needDepthPrePass) {
  19056. this._depthOnlySubMeshes.push(subMesh);
  19057. }
  19058. this._opaqueSubMeshes.push(subMesh); // Opaque
  19059. }
  19060. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19061. this._edgesRenderers.push(mesh._edgesRenderer);
  19062. }
  19063. };
  19064. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19065. this._spriteManagers.push(spriteManager);
  19066. };
  19067. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19068. this._particleSystems.push(particleSystem);
  19069. };
  19070. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19071. if (this._particleSystems.length === 0) {
  19072. return;
  19073. }
  19074. // Particles
  19075. var activeCamera = this._scene.activeCamera;
  19076. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19077. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19078. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19079. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19080. continue;
  19081. }
  19082. var emitter = particleSystem.emitter;
  19083. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19084. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19085. }
  19086. }
  19087. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19088. };
  19089. RenderingGroup.prototype._renderSprites = function () {
  19090. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19091. return;
  19092. }
  19093. // Sprites
  19094. var activeCamera = this._scene.activeCamera;
  19095. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19096. for (var id = 0; id < this._spriteManagers.length; id++) {
  19097. var spriteManager = this._spriteManagers.data[id];
  19098. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19099. spriteManager.render();
  19100. }
  19101. }
  19102. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19103. };
  19104. return RenderingGroup;
  19105. }());
  19106. BABYLON.RenderingGroup = RenderingGroup;
  19107. })(BABYLON || (BABYLON = {}));
  19108. //# sourceMappingURL=babylon.renderingGroup.js.map
  19109. var BABYLON;
  19110. (function (BABYLON) {
  19111. var ClickInfo = /** @class */ (function () {
  19112. function ClickInfo() {
  19113. this._singleClick = false;
  19114. this._doubleClick = false;
  19115. this._hasSwiped = false;
  19116. this._ignore = false;
  19117. }
  19118. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19119. get: function () {
  19120. return this._singleClick;
  19121. },
  19122. set: function (b) {
  19123. this._singleClick = b;
  19124. },
  19125. enumerable: true,
  19126. configurable: true
  19127. });
  19128. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19129. get: function () {
  19130. return this._doubleClick;
  19131. },
  19132. set: function (b) {
  19133. this._doubleClick = b;
  19134. },
  19135. enumerable: true,
  19136. configurable: true
  19137. });
  19138. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19139. get: function () {
  19140. return this._hasSwiped;
  19141. },
  19142. set: function (b) {
  19143. this._hasSwiped = b;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19149. get: function () {
  19150. return this._ignore;
  19151. },
  19152. set: function (b) {
  19153. this._ignore = b;
  19154. },
  19155. enumerable: true,
  19156. configurable: true
  19157. });
  19158. return ClickInfo;
  19159. }());
  19160. /**
  19161. * This class is used by the onRenderingGroupObservable
  19162. */
  19163. var RenderingGroupInfo = /** @class */ (function () {
  19164. function RenderingGroupInfo() {
  19165. }
  19166. /**
  19167. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19168. * This stage will be fired no matter what
  19169. */
  19170. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19171. /**
  19172. * Called before opaque object are rendered.
  19173. * This stage will be fired only if there's 3D Opaque content to render
  19174. */
  19175. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19176. /**
  19177. * Called after the opaque objects are rendered and before the transparent ones
  19178. * This stage will be fired only if there's 3D transparent content to render
  19179. */
  19180. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19181. /**
  19182. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19183. * This stage will be fired no matter what
  19184. */
  19185. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19186. return RenderingGroupInfo;
  19187. }());
  19188. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19189. /**
  19190. * Represents a scene to be rendered by the engine.
  19191. * @see http://doc.babylonjs.com/page.php?p=21911
  19192. */
  19193. var Scene = /** @class */ (function () {
  19194. /**
  19195. * @constructor
  19196. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19197. */
  19198. function Scene(engine) {
  19199. // Members
  19200. this.autoClear = true;
  19201. this.autoClearDepthAndStencil = true;
  19202. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19203. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19204. this.forceWireframe = false;
  19205. this._forcePointsCloud = false;
  19206. this.forceShowBoundingBoxes = false;
  19207. this.animationsEnabled = true;
  19208. this.useConstantAnimationDeltaTime = false;
  19209. this.constantlyUpdateMeshUnderPointer = false;
  19210. this.hoverCursor = "pointer";
  19211. this.defaultCursor = "";
  19212. /**
  19213. * This is used to call preventDefault() on pointer down
  19214. * in order to block unwanted artifacts like system double clicks
  19215. */
  19216. this.preventDefaultOnPointerDown = true;
  19217. // Metadata
  19218. this.metadata = null;
  19219. /**
  19220. * An event triggered when the scene is disposed.
  19221. * @type {BABYLON.Observable}
  19222. */
  19223. this.onDisposeObservable = new BABYLON.Observable();
  19224. /**
  19225. * An event triggered before rendering the scene (right after animations and physics)
  19226. * @type {BABYLON.Observable}
  19227. */
  19228. this.onBeforeRenderObservable = new BABYLON.Observable();
  19229. /**
  19230. * An event triggered after rendering the scene
  19231. * @type {BABYLON.Observable}
  19232. */
  19233. this.onAfterRenderObservable = new BABYLON.Observable();
  19234. /**
  19235. * An event triggered before animating the scene
  19236. * @type {BABYLON.Observable}
  19237. */
  19238. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19239. /**
  19240. * An event triggered after animations processing
  19241. * @type {BABYLON.Observable}
  19242. */
  19243. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19244. /**
  19245. * An event triggered before draw calls are ready to be sent
  19246. * @type {BABYLON.Observable}
  19247. */
  19248. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19249. /**
  19250. * An event triggered after draw calls have been sent
  19251. * @type {BABYLON.Observable}
  19252. */
  19253. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19254. /**
  19255. * An event triggered when physic simulation is about to be run
  19256. * @type {BABYLON.Observable}
  19257. */
  19258. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19259. /**
  19260. * An event triggered when physic simulation has been done
  19261. * @type {BABYLON.Observable}
  19262. */
  19263. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19264. /**
  19265. * An event triggered when the scene is ready
  19266. * @type {BABYLON.Observable}
  19267. */
  19268. this.onReadyObservable = new BABYLON.Observable();
  19269. /**
  19270. * An event triggered before rendering a camera
  19271. * @type {BABYLON.Observable}
  19272. */
  19273. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered after rendering a camera
  19276. * @type {BABYLON.Observable}
  19277. */
  19278. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19279. /**
  19280. * An event triggered when active meshes evaluation is about to start
  19281. * @type {BABYLON.Observable}
  19282. */
  19283. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19284. /**
  19285. * An event triggered when active meshes evaluation is done
  19286. * @type {BABYLON.Observable}
  19287. */
  19288. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19289. /**
  19290. * An event triggered when particles rendering is about to start
  19291. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19292. * @type {BABYLON.Observable}
  19293. */
  19294. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19295. /**
  19296. * An event triggered when particles rendering is done
  19297. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19298. * @type {BABYLON.Observable}
  19299. */
  19300. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19301. /**
  19302. * An event triggered when sprites rendering is about to start
  19303. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19307. /**
  19308. * An event triggered when sprites rendering is done
  19309. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19310. * @type {BABYLON.Observable}
  19311. */
  19312. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19313. /**
  19314. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19315. * @type {BABYLON.Observable}
  19316. */
  19317. this.onDataLoadedObservable = new BABYLON.Observable();
  19318. /**
  19319. * An event triggered when a camera is created
  19320. * @type {BABYLON.Observable}
  19321. */
  19322. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19323. /**
  19324. * An event triggered when a camera is removed
  19325. * @type {BABYLON.Observable}
  19326. */
  19327. this.onCameraRemovedObservable = new BABYLON.Observable();
  19328. /**
  19329. * An event triggered when a light is created
  19330. * @type {BABYLON.Observable}
  19331. */
  19332. this.onNewLightAddedObservable = new BABYLON.Observable();
  19333. /**
  19334. * An event triggered when a light is removed
  19335. * @type {BABYLON.Observable}
  19336. */
  19337. this.onLightRemovedObservable = new BABYLON.Observable();
  19338. /**
  19339. * An event triggered when a geometry is created
  19340. * @type {BABYLON.Observable}
  19341. */
  19342. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19343. /**
  19344. * An event triggered when a geometry is removed
  19345. * @type {BABYLON.Observable}
  19346. */
  19347. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19348. /**
  19349. * An event triggered when a transform node is created
  19350. * @type {BABYLON.Observable}
  19351. */
  19352. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19353. /**
  19354. * An event triggered when a transform node is removed
  19355. * @type {BABYLON.Observable}
  19356. */
  19357. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19358. /**
  19359. * An event triggered when a mesh is created
  19360. * @type {BABYLON.Observable}
  19361. */
  19362. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19363. /**
  19364. * An event triggered when a mesh is removed
  19365. * @type {BABYLON.Observable}
  19366. */
  19367. this.onMeshRemovedObservable = new BABYLON.Observable();
  19368. /**
  19369. * An event triggered when render targets are about to be rendered
  19370. * Can happen multiple times per frame.
  19371. * @type {BABYLON.Observable}
  19372. */
  19373. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19374. /**
  19375. * An event triggered when render targets were rendered.
  19376. * Can happen multiple times per frame.
  19377. * @type {BABYLON.Observable}
  19378. */
  19379. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19380. /**
  19381. * An event triggered before calculating deterministic simulation step
  19382. * @type {BABYLON.Observable}
  19383. */
  19384. this.onBeforeStepObservable = new BABYLON.Observable();
  19385. /**
  19386. * An event triggered after calculating deterministic simulation step
  19387. * @type {BABYLON.Observable}
  19388. */
  19389. this.onAfterStepObservable = new BABYLON.Observable();
  19390. /**
  19391. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19392. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19393. * 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)
  19394. */
  19395. this.onRenderingGroupObservable = new BABYLON.Observable();
  19396. // Animations
  19397. this.animations = [];
  19398. /**
  19399. * 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).
  19400. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19401. */
  19402. this.onPrePointerObservable = new BABYLON.Observable();
  19403. /**
  19404. * Observable event triggered each time an input event is received from the rendering canvas
  19405. */
  19406. this.onPointerObservable = new BABYLON.Observable();
  19407. this._meshPickProceed = false;
  19408. this._currentPickResult = null;
  19409. this._previousPickResult = null;
  19410. this._totalPointersPressed = 0;
  19411. this._doubleClickOccured = false;
  19412. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19413. this.cameraToUseForPointers = null;
  19414. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19415. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19416. this._startingPointerTime = 0;
  19417. this._previousStartingPointerTime = 0;
  19418. // Deterministic lockstep
  19419. this._timeAccumulator = 0;
  19420. this._currentStepId = 0;
  19421. this._currentInternalStep = 0;
  19422. // Keyboard
  19423. /**
  19424. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19425. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19426. */
  19427. this.onPreKeyboardObservable = new BABYLON.Observable();
  19428. /**
  19429. * Observable event triggered each time an keyboard event is received from the hosting window
  19430. */
  19431. this.onKeyboardObservable = new BABYLON.Observable();
  19432. // Coordinate system
  19433. /**
  19434. * use right-handed coordinate system on this scene.
  19435. * @type {boolean}
  19436. */
  19437. this._useRightHandedSystem = false;
  19438. // Fog
  19439. this._fogEnabled = true;
  19440. this._fogMode = Scene.FOGMODE_NONE;
  19441. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19442. this.fogDensity = 0.1;
  19443. this.fogStart = 0;
  19444. this.fogEnd = 1000.0;
  19445. // Lights
  19446. /**
  19447. * is shadow enabled on this scene.
  19448. * @type {boolean}
  19449. */
  19450. this._shadowsEnabled = true;
  19451. /**
  19452. * is light enabled on this scene.
  19453. * @type {boolean}
  19454. */
  19455. this._lightsEnabled = true;
  19456. /**
  19457. * All of the lights added to this scene.
  19458. * @see BABYLON.Light
  19459. * @type {BABYLON.Light[]}
  19460. */
  19461. this.lights = new Array();
  19462. // Cameras
  19463. /** All of the cameras added to this scene. */
  19464. this.cameras = new Array();
  19465. /** All of the active cameras added to this scene. */
  19466. this.activeCameras = new Array();
  19467. // Meshes
  19468. /**
  19469. * All of the tranform nodes added to this scene.
  19470. * @see BABYLON.TransformNode
  19471. * @type {BABYLON.TransformNode[]}
  19472. */
  19473. this.transformNodes = new Array();
  19474. /**
  19475. * All of the (abstract) meshes added to this scene.
  19476. * @see BABYLON.AbstractMesh
  19477. * @type {BABYLON.AbstractMesh[]}
  19478. */
  19479. this.meshes = new Array();
  19480. /**
  19481. * All of the animation groups added to this scene.
  19482. * @see BABYLON.AnimationGroup
  19483. * @type {BABYLON.AnimationGroup[]}
  19484. */
  19485. this.animationGroups = new Array();
  19486. // Geometries
  19487. this._geometries = new Array();
  19488. this.materials = new Array();
  19489. this.multiMaterials = new Array();
  19490. // Textures
  19491. this._texturesEnabled = true;
  19492. this.textures = new Array();
  19493. // Particles
  19494. this.particlesEnabled = true;
  19495. this.particleSystems = new Array();
  19496. // Sprites
  19497. this.spritesEnabled = true;
  19498. this.spriteManagers = new Array();
  19499. // Layers
  19500. this.layers = new Array();
  19501. this.highlightLayers = new Array();
  19502. // Skeletons
  19503. this._skeletonsEnabled = true;
  19504. this.skeletons = new Array();
  19505. // Morph targets
  19506. this.morphTargetManagers = new Array();
  19507. // Lens flares
  19508. this.lensFlaresEnabled = true;
  19509. this.lensFlareSystems = new Array();
  19510. // Collisions
  19511. this.collisionsEnabled = true;
  19512. /** Defines the gravity applied to this scene */
  19513. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19514. // Postprocesses
  19515. this.postProcesses = new Array();
  19516. this.postProcessesEnabled = true;
  19517. // Customs render targets
  19518. this.renderTargetsEnabled = true;
  19519. this.dumpNextRenderTargets = false;
  19520. this.customRenderTargets = new Array();
  19521. // Imported meshes
  19522. this.importedMeshesFiles = new Array();
  19523. // Probes
  19524. this.probesEnabled = true;
  19525. this.reflectionProbes = new Array();
  19526. this._actionManagers = new Array();
  19527. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19528. // Procedural textures
  19529. this.proceduralTexturesEnabled = true;
  19530. this._proceduralTextures = new Array();
  19531. this.soundTracks = new Array();
  19532. this._audioEnabled = true;
  19533. this._headphone = false;
  19534. // Performance counters
  19535. this._totalVertices = new BABYLON.PerfCounter();
  19536. this._activeIndices = new BABYLON.PerfCounter();
  19537. this._activeParticles = new BABYLON.PerfCounter();
  19538. this._activeBones = new BABYLON.PerfCounter();
  19539. this._animationTime = 0;
  19540. this.animationTimeScale = 1;
  19541. this._renderId = 0;
  19542. this._executeWhenReadyTimeoutId = -1;
  19543. this._intermediateRendering = false;
  19544. this._viewUpdateFlag = -1;
  19545. this._projectionUpdateFlag = -1;
  19546. this._alternateViewUpdateFlag = -1;
  19547. this._alternateProjectionUpdateFlag = -1;
  19548. this._toBeDisposed = new BABYLON.SmartArray(256);
  19549. this._activeRequests = new Array();
  19550. this._pendingData = new Array();
  19551. this._isDisposed = false;
  19552. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19553. this._activeMeshes = new BABYLON.SmartArray(256);
  19554. this._processedMaterials = new BABYLON.SmartArray(256);
  19555. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19556. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19557. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19558. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19559. this._activeAnimatables = new Array();
  19560. this._transformMatrix = BABYLON.Matrix.Zero();
  19561. this._useAlternateCameraConfiguration = false;
  19562. this._alternateRendering = false;
  19563. this.requireLightSorting = false;
  19564. this._activeMeshesFrozen = false;
  19565. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19566. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19567. this._engine.scenes.push(this);
  19568. this._uid = null;
  19569. this._renderingManager = new BABYLON.RenderingManager(this);
  19570. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19571. if (BABYLON.OutlineRenderer) {
  19572. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19573. }
  19574. if (BABYLON.Tools.IsWindowObjectExist()) {
  19575. this.attachControl();
  19576. }
  19577. //simplification queue
  19578. if (BABYLON.SimplificationQueue) {
  19579. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19580. }
  19581. //collision coordinator initialization. For now legacy per default.
  19582. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19583. // Uniform Buffer
  19584. this._createUbo();
  19585. // Default Image processing definition.
  19586. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19587. }
  19588. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19589. /** The fog is deactivated */
  19590. get: function () {
  19591. return Scene._FOGMODE_NONE;
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19597. /** The fog density is following an exponential function */
  19598. get: function () {
  19599. return Scene._FOGMODE_EXP;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19605. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19606. get: function () {
  19607. return Scene._FOGMODE_EXP2;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19613. /** The fog density is following a linear function. */
  19614. get: function () {
  19615. return Scene._FOGMODE_LINEAR;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19621. /**
  19622. * Texture used in all pbr material as the reflection texture.
  19623. * As in the majority of the scene they are the same (exception for multi room and so on),
  19624. * this is easier to reference from here than from all the materials.
  19625. */
  19626. get: function () {
  19627. return this._environmentTexture;
  19628. },
  19629. /**
  19630. * Texture used in all pbr material as the reflection texture.
  19631. * As in the majority of the scene they are the same (exception for multi room and so on),
  19632. * this is easier to set here than in all the materials.
  19633. */
  19634. set: function (value) {
  19635. if (this._environmentTexture === value) {
  19636. return;
  19637. }
  19638. this._environmentTexture = value;
  19639. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19640. },
  19641. enumerable: true,
  19642. configurable: true
  19643. });
  19644. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19645. /**
  19646. * Default image processing configuration used either in the rendering
  19647. * Forward main pass or through the imageProcessingPostProcess if present.
  19648. * As in the majority of the scene they are the same (exception for multi camera),
  19649. * this is easier to reference from here than from all the materials and post process.
  19650. *
  19651. * No setter as we it is a shared configuration, you can set the values instead.
  19652. */
  19653. get: function () {
  19654. return this._imageProcessingConfiguration;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19660. get: function () {
  19661. return this._forcePointsCloud;
  19662. },
  19663. set: function (value) {
  19664. if (this._forcePointsCloud === value) {
  19665. return;
  19666. }
  19667. this._forcePointsCloud = value;
  19668. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(Scene.prototype, "onDispose", {
  19674. /** A function to be executed when this scene is disposed. */
  19675. set: function (callback) {
  19676. if (this._onDisposeObserver) {
  19677. this.onDisposeObservable.remove(this._onDisposeObserver);
  19678. }
  19679. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Scene.prototype, "beforeRender", {
  19685. /** A function to be executed before rendering this scene */
  19686. set: function (callback) {
  19687. if (this._onBeforeRenderObserver) {
  19688. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19689. }
  19690. if (callback) {
  19691. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19692. }
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(Scene.prototype, "afterRender", {
  19698. /** A function to be executed after rendering this scene */
  19699. set: function (callback) {
  19700. if (this._onAfterRenderObserver) {
  19701. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19702. }
  19703. if (callback) {
  19704. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19705. }
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19711. set: function (callback) {
  19712. if (this._onBeforeCameraRenderObserver) {
  19713. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19714. }
  19715. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19721. set: function (callback) {
  19722. if (this._onAfterCameraRenderObserver) {
  19723. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19724. }
  19725. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19731. get: function () {
  19732. if (!this._gamepadManager) {
  19733. this._gamepadManager = new BABYLON.GamepadManager(this);
  19734. }
  19735. return this._gamepadManager;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19741. get: function () {
  19742. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19748. get: function () {
  19749. return this._useRightHandedSystem;
  19750. },
  19751. set: function (value) {
  19752. if (this._useRightHandedSystem === value) {
  19753. return;
  19754. }
  19755. this._useRightHandedSystem = value;
  19756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Scene.prototype.setStepId = function (newStepId) {
  19762. this._currentStepId = newStepId;
  19763. };
  19764. ;
  19765. Scene.prototype.getStepId = function () {
  19766. return this._currentStepId;
  19767. };
  19768. ;
  19769. Scene.prototype.getInternalStep = function () {
  19770. return this._currentInternalStep;
  19771. };
  19772. ;
  19773. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19774. get: function () {
  19775. return this._fogEnabled;
  19776. },
  19777. /**
  19778. * is fog enabled on this scene.
  19779. */
  19780. set: function (value) {
  19781. if (this._fogEnabled === value) {
  19782. return;
  19783. }
  19784. this._fogEnabled = value;
  19785. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(Scene.prototype, "fogMode", {
  19791. get: function () {
  19792. return this._fogMode;
  19793. },
  19794. set: function (value) {
  19795. if (this._fogMode === value) {
  19796. return;
  19797. }
  19798. this._fogMode = value;
  19799. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19805. get: function () {
  19806. return this._shadowsEnabled;
  19807. },
  19808. set: function (value) {
  19809. if (this._shadowsEnabled === value) {
  19810. return;
  19811. }
  19812. this._shadowsEnabled = value;
  19813. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19819. get: function () {
  19820. return this._lightsEnabled;
  19821. },
  19822. set: function (value) {
  19823. if (this._lightsEnabled === value) {
  19824. return;
  19825. }
  19826. this._lightsEnabled = value;
  19827. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19833. /** The default material used on meshes when no material is affected */
  19834. get: function () {
  19835. if (!this._defaultMaterial) {
  19836. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19837. }
  19838. return this._defaultMaterial;
  19839. },
  19840. /** The default material used on meshes when no material is affected */
  19841. set: function (value) {
  19842. this._defaultMaterial = value;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19848. get: function () {
  19849. return this._texturesEnabled;
  19850. },
  19851. set: function (value) {
  19852. if (this._texturesEnabled === value) {
  19853. return;
  19854. }
  19855. this._texturesEnabled = value;
  19856. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19862. get: function () {
  19863. return this._skeletonsEnabled;
  19864. },
  19865. set: function (value) {
  19866. if (this._skeletonsEnabled === value) {
  19867. return;
  19868. }
  19869. this._skeletonsEnabled = value;
  19870. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19876. get: function () {
  19877. if (!this._postProcessRenderPipelineManager) {
  19878. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19879. }
  19880. return this._postProcessRenderPipelineManager;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19886. get: function () {
  19887. if (!this._mainSoundTrack) {
  19888. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19889. }
  19890. return this._mainSoundTrack;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19896. get: function () {
  19897. return this._alternateRendering;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19903. get: function () {
  19904. return this._frustumPlanes;
  19905. },
  19906. enumerable: true,
  19907. configurable: true
  19908. });
  19909. Object.defineProperty(Scene.prototype, "debugLayer", {
  19910. // Properties
  19911. get: function () {
  19912. if (!this._debugLayer) {
  19913. this._debugLayer = new BABYLON.DebugLayer(this);
  19914. }
  19915. return this._debugLayer;
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19921. get: function () {
  19922. return this._workerCollisions;
  19923. },
  19924. set: function (enabled) {
  19925. if (!BABYLON.CollisionCoordinatorLegacy) {
  19926. return;
  19927. }
  19928. enabled = (enabled && !!Worker);
  19929. this._workerCollisions = enabled;
  19930. if (this.collisionCoordinator) {
  19931. this.collisionCoordinator.destroy();
  19932. }
  19933. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19934. this.collisionCoordinator.init(this);
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19940. get: function () {
  19941. return this._selectionOctree;
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19947. /**
  19948. * The mesh that is currently under the pointer.
  19949. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19950. */
  19951. get: function () {
  19952. return this._pointerOverMesh;
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(Scene.prototype, "pointerX", {
  19958. /**
  19959. * Current on-screen X position of the pointer
  19960. * @return {number} X position of the pointer
  19961. */
  19962. get: function () {
  19963. return this._pointerX;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(Scene.prototype, "pointerY", {
  19969. /**
  19970. * Current on-screen Y position of the pointer
  19971. * @return {number} Y position of the pointer
  19972. */
  19973. get: function () {
  19974. return this._pointerY;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Scene.prototype.getCachedMaterial = function () {
  19980. return this._cachedMaterial;
  19981. };
  19982. Scene.prototype.getCachedEffect = function () {
  19983. return this._cachedEffect;
  19984. };
  19985. Scene.prototype.getCachedVisibility = function () {
  19986. return this._cachedVisibility;
  19987. };
  19988. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19989. if (visibility === void 0) { visibility = 1; }
  19990. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19991. };
  19992. Scene.prototype.getBoundingBoxRenderer = function () {
  19993. if (!this._boundingBoxRenderer) {
  19994. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19995. }
  19996. return this._boundingBoxRenderer;
  19997. };
  19998. Scene.prototype.getOutlineRenderer = function () {
  19999. return this._outlineRenderer;
  20000. };
  20001. Scene.prototype.getEngine = function () {
  20002. return this._engine;
  20003. };
  20004. Scene.prototype.getTotalVertices = function () {
  20005. return this._totalVertices.current;
  20006. };
  20007. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20008. get: function () {
  20009. return this._totalVertices;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Scene.prototype.getActiveIndices = function () {
  20015. return this._activeIndices.current;
  20016. };
  20017. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20018. get: function () {
  20019. return this._activeIndices;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Scene.prototype.getActiveParticles = function () {
  20025. return this._activeParticles.current;
  20026. };
  20027. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20028. get: function () {
  20029. return this._activeParticles;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Scene.prototype.getActiveBones = function () {
  20035. return this._activeBones.current;
  20036. };
  20037. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20038. get: function () {
  20039. return this._activeBones;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. // Stats
  20045. Scene.prototype.getInterFramePerfCounter = function () {
  20046. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20047. return 0;
  20048. };
  20049. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20050. get: function () {
  20051. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20052. return null;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Scene.prototype.getLastFrameDuration = function () {
  20058. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20059. return 0;
  20060. };
  20061. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20062. get: function () {
  20063. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20064. return null;
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20070. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20071. return 0;
  20072. };
  20073. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20074. get: function () {
  20075. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20076. return null;
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. Scene.prototype.getActiveMeshes = function () {
  20082. return this._activeMeshes;
  20083. };
  20084. Scene.prototype.getRenderTargetsDuration = function () {
  20085. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20086. return 0;
  20087. };
  20088. Scene.prototype.getRenderDuration = function () {
  20089. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20090. return 0;
  20091. };
  20092. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20093. get: function () {
  20094. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20095. return null;
  20096. },
  20097. enumerable: true,
  20098. configurable: true
  20099. });
  20100. Scene.prototype.getParticlesDuration = function () {
  20101. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20102. return 0;
  20103. };
  20104. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20105. get: function () {
  20106. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20107. return null;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Scene.prototype.getSpritesDuration = function () {
  20113. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20114. return 0;
  20115. };
  20116. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20117. get: function () {
  20118. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20119. return null;
  20120. },
  20121. enumerable: true,
  20122. configurable: true
  20123. });
  20124. Scene.prototype.getAnimationRatio = function () {
  20125. return this._animationRatio;
  20126. };
  20127. Scene.prototype.getRenderId = function () {
  20128. return this._renderId;
  20129. };
  20130. Scene.prototype.incrementRenderId = function () {
  20131. this._renderId++;
  20132. };
  20133. Scene.prototype._updatePointerPosition = function (evt) {
  20134. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20135. if (!canvasRect) {
  20136. return;
  20137. }
  20138. this._pointerX = evt.clientX - canvasRect.left;
  20139. this._pointerY = evt.clientY - canvasRect.top;
  20140. this._unTranslatedPointerX = this._pointerX;
  20141. this._unTranslatedPointerY = this._pointerY;
  20142. };
  20143. Scene.prototype._createUbo = function () {
  20144. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20145. this._sceneUbo.addUniform("viewProjection", 16);
  20146. this._sceneUbo.addUniform("view", 16);
  20147. };
  20148. Scene.prototype._createAlternateUbo = function () {
  20149. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20150. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20151. this._alternateSceneUbo.addUniform("view", 16);
  20152. };
  20153. // Pointers handling
  20154. /**
  20155. * Use this method to simulate a pointer move on a mesh
  20156. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20157. */
  20158. Scene.prototype.simulatePointerMove = function (pickResult) {
  20159. var evt = new PointerEvent("pointermove");
  20160. return this._processPointerMove(pickResult, evt);
  20161. };
  20162. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20163. var canvas = this._engine.getRenderingCanvas();
  20164. if (!canvas) {
  20165. return this;
  20166. }
  20167. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20168. this.setPointerOverSprite(null);
  20169. this.setPointerOverMesh(pickResult.pickedMesh);
  20170. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20171. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20172. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20173. }
  20174. else {
  20175. canvas.style.cursor = this.hoverCursor;
  20176. }
  20177. }
  20178. else {
  20179. canvas.style.cursor = this.defaultCursor;
  20180. }
  20181. }
  20182. else {
  20183. this.setPointerOverMesh(null);
  20184. // Sprites
  20185. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20186. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20187. this.setPointerOverSprite(pickResult.pickedSprite);
  20188. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20189. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20190. }
  20191. else {
  20192. canvas.style.cursor = this.hoverCursor;
  20193. }
  20194. }
  20195. else {
  20196. this.setPointerOverSprite(null);
  20197. // Restore pointer
  20198. canvas.style.cursor = this.defaultCursor;
  20199. }
  20200. }
  20201. if (pickResult) {
  20202. if (this.onPointerMove) {
  20203. this.onPointerMove(evt, pickResult);
  20204. }
  20205. if (this.onPointerObservable.hasObservers()) {
  20206. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20207. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20208. this.onPointerObservable.notifyObservers(pi, type);
  20209. }
  20210. }
  20211. return this;
  20212. };
  20213. /**
  20214. * Use this method to simulate a pointer down on a mesh
  20215. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20216. */
  20217. Scene.prototype.simulatePointerDown = function (pickResult) {
  20218. var evt = new PointerEvent("pointerdown");
  20219. return this._processPointerDown(pickResult, evt);
  20220. };
  20221. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20222. var _this = this;
  20223. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20224. this._pickedDownMesh = pickResult.pickedMesh;
  20225. var actionManager = pickResult.pickedMesh.actionManager;
  20226. if (actionManager) {
  20227. if (actionManager.hasPickTriggers) {
  20228. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20229. switch (evt.button) {
  20230. case 0:
  20231. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20232. break;
  20233. case 1:
  20234. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20235. break;
  20236. case 2:
  20237. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20238. break;
  20239. }
  20240. }
  20241. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20242. window.setTimeout(function () {
  20243. 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);
  20244. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20245. if (_this._totalPointersPressed !== 0 &&
  20246. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20247. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20248. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20249. _this._startingPointerTime = 0;
  20250. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20251. }
  20252. }
  20253. }, Scene.LongPressDelay);
  20254. }
  20255. }
  20256. }
  20257. if (pickResult) {
  20258. if (this.onPointerDown) {
  20259. this.onPointerDown(evt, pickResult);
  20260. }
  20261. if (this.onPointerObservable.hasObservers()) {
  20262. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20263. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20264. this.onPointerObservable.notifyObservers(pi, type);
  20265. }
  20266. }
  20267. return this;
  20268. };
  20269. /**
  20270. * Use this method to simulate a pointer up on a mesh
  20271. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20272. */
  20273. Scene.prototype.simulatePointerUp = function (pickResult) {
  20274. var evt = new PointerEvent("pointerup");
  20275. var clickInfo = new ClickInfo();
  20276. clickInfo.singleClick = true;
  20277. clickInfo.ignore = true;
  20278. return this._processPointerUp(pickResult, evt, clickInfo);
  20279. };
  20280. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20281. if (pickResult && pickResult && pickResult.pickedMesh) {
  20282. this._pickedUpMesh = pickResult.pickedMesh;
  20283. if (this._pickedDownMesh === this._pickedUpMesh) {
  20284. if (this.onPointerPick) {
  20285. this.onPointerPick(evt, pickResult);
  20286. }
  20287. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20288. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20289. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20290. this.onPointerObservable.notifyObservers(pi, type);
  20291. }
  20292. }
  20293. if (pickResult.pickedMesh.actionManager) {
  20294. if (clickInfo.ignore) {
  20295. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20296. }
  20297. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20298. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20299. }
  20300. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20301. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20302. }
  20303. }
  20304. }
  20305. if (this._pickedDownMesh &&
  20306. this._pickedDownMesh.actionManager &&
  20307. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20308. this._pickedDownMesh !== this._pickedUpMesh) {
  20309. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20310. }
  20311. if (this.onPointerUp) {
  20312. this.onPointerUp(evt, pickResult);
  20313. }
  20314. if (this.onPointerObservable.hasObservers()) {
  20315. if (!clickInfo.ignore) {
  20316. if (!clickInfo.hasSwiped) {
  20317. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20318. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20319. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20320. this.onPointerObservable.notifyObservers(pi, type);
  20321. }
  20322. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20323. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20324. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20325. this.onPointerObservable.notifyObservers(pi, type);
  20326. }
  20327. }
  20328. }
  20329. else {
  20330. var type = BABYLON.PointerEventTypes.POINTERUP;
  20331. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20332. this.onPointerObservable.notifyObservers(pi, type);
  20333. }
  20334. }
  20335. return this;
  20336. };
  20337. /**
  20338. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20339. * @param attachUp defines if you want to attach events to pointerup
  20340. * @param attachDown defines if you want to attach events to pointerdown
  20341. * @param attachMove defines if you want to attach events to pointermove
  20342. */
  20343. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20344. var _this = this;
  20345. if (attachUp === void 0) { attachUp = true; }
  20346. if (attachDown === void 0) { attachDown = true; }
  20347. if (attachMove === void 0) { attachMove = true; }
  20348. this._initActionManager = function (act, clickInfo) {
  20349. if (!_this._meshPickProceed) {
  20350. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20351. _this._currentPickResult = pickResult;
  20352. if (pickResult) {
  20353. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20354. }
  20355. _this._meshPickProceed = true;
  20356. }
  20357. return act;
  20358. };
  20359. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20360. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20361. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20362. btn !== _this._previousButtonPressed) {
  20363. _this._doubleClickOccured = false;
  20364. clickInfo.singleClick = true;
  20365. clickInfo.ignore = false;
  20366. cb(clickInfo, _this._currentPickResult);
  20367. }
  20368. };
  20369. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20370. var clickInfo = new ClickInfo();
  20371. _this._currentPickResult = null;
  20372. var act = null;
  20373. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20374. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20375. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20376. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20377. act = _this._initActionManager(act, clickInfo);
  20378. if (act)
  20379. checkPicking = act.hasPickTriggers;
  20380. }
  20381. if (checkPicking) {
  20382. var btn = evt.button;
  20383. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20384. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20385. if (!clickInfo.hasSwiped) {
  20386. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20387. if (!checkSingleClickImmediately) {
  20388. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20389. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20390. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20391. act = _this._initActionManager(act, clickInfo);
  20392. if (act)
  20393. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20394. }
  20395. }
  20396. if (checkSingleClickImmediately) {
  20397. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20398. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20399. btn !== _this._previousButtonPressed) {
  20400. clickInfo.singleClick = true;
  20401. cb(clickInfo, _this._currentPickResult);
  20402. }
  20403. }
  20404. else {
  20405. // wait that no double click has been raised during the double click delay
  20406. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20407. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20408. }
  20409. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20410. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20411. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20412. act = _this._initActionManager(act, clickInfo);
  20413. if (act)
  20414. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20415. }
  20416. if (checkDoubleClick) {
  20417. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20418. if (btn === _this._previousButtonPressed &&
  20419. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20420. !_this._doubleClickOccured) {
  20421. // pointer has not moved for 2 clicks, it's a double click
  20422. if (!clickInfo.hasSwiped &&
  20423. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20424. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20425. _this._previousStartingPointerTime = 0;
  20426. _this._doubleClickOccured = true;
  20427. clickInfo.doubleClick = true;
  20428. clickInfo.ignore = false;
  20429. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20430. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20431. }
  20432. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20433. cb(clickInfo, _this._currentPickResult);
  20434. }
  20435. else {
  20436. _this._doubleClickOccured = false;
  20437. _this._previousStartingPointerTime = _this._startingPointerTime;
  20438. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20439. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20440. _this._previousButtonPressed = btn;
  20441. if (Scene.ExclusiveDoubleClickMode) {
  20442. if (_this._previousDelayedSimpleClickTimeout) {
  20443. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20444. }
  20445. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20446. cb(clickInfo, _this._previousPickResult);
  20447. }
  20448. else {
  20449. cb(clickInfo, _this._currentPickResult);
  20450. }
  20451. }
  20452. }
  20453. else {
  20454. _this._doubleClickOccured = false;
  20455. _this._previousStartingPointerTime = _this._startingPointerTime;
  20456. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20457. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20458. _this._previousButtonPressed = btn;
  20459. }
  20460. }
  20461. }
  20462. }
  20463. clickInfo.ignore = true;
  20464. cb(clickInfo, _this._currentPickResult);
  20465. };
  20466. this._spritePredicate = function (sprite) {
  20467. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20468. };
  20469. this._onPointerMove = function (evt) {
  20470. _this._updatePointerPosition(evt);
  20471. // PreObservable support
  20472. if (_this.onPrePointerObservable.hasObservers()) {
  20473. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20474. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20475. _this.onPrePointerObservable.notifyObservers(pi, type);
  20476. if (pi.skipOnPointerObservable) {
  20477. return;
  20478. }
  20479. }
  20480. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20481. return;
  20482. }
  20483. if (!_this.pointerMovePredicate) {
  20484. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20485. }
  20486. // Meshes
  20487. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20488. _this._processPointerMove(pickResult, evt);
  20489. };
  20490. this._onPointerDown = function (evt) {
  20491. _this._totalPointersPressed++;
  20492. _this._pickedDownMesh = null;
  20493. _this._meshPickProceed = false;
  20494. _this._updatePointerPosition(evt);
  20495. if (_this.preventDefaultOnPointerDown && canvas) {
  20496. evt.preventDefault();
  20497. canvas.focus();
  20498. }
  20499. // PreObservable support
  20500. if (_this.onPrePointerObservable.hasObservers()) {
  20501. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20502. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20503. _this.onPrePointerObservable.notifyObservers(pi, type);
  20504. if (pi.skipOnPointerObservable) {
  20505. return;
  20506. }
  20507. }
  20508. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20509. return;
  20510. }
  20511. _this._startingPointerPosition.x = _this._pointerX;
  20512. _this._startingPointerPosition.y = _this._pointerY;
  20513. _this._startingPointerTime = new Date().getTime();
  20514. if (!_this.pointerDownPredicate) {
  20515. _this.pointerDownPredicate = function (mesh) {
  20516. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20517. };
  20518. }
  20519. // Meshes
  20520. _this._pickedDownMesh = null;
  20521. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20522. _this._processPointerDown(pickResult, evt);
  20523. // Sprites
  20524. _this._pickedDownSprite = null;
  20525. if (_this.spriteManagers.length > 0) {
  20526. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20527. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20528. if (pickResult.pickedSprite.actionManager) {
  20529. _this._pickedDownSprite = pickResult.pickedSprite;
  20530. switch (evt.button) {
  20531. case 0:
  20532. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20533. break;
  20534. case 1:
  20535. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20536. break;
  20537. case 2:
  20538. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20539. break;
  20540. }
  20541. if (pickResult.pickedSprite.actionManager) {
  20542. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20543. }
  20544. }
  20545. }
  20546. }
  20547. };
  20548. this._onPointerUp = function (evt) {
  20549. if (_this._totalPointersPressed === 0) {
  20550. return; // So we need to test it the pointer down was pressed before.
  20551. }
  20552. _this._totalPointersPressed--;
  20553. _this._pickedUpMesh = null;
  20554. _this._meshPickProceed = false;
  20555. _this._updatePointerPosition(evt);
  20556. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20557. // PreObservable support
  20558. if (_this.onPrePointerObservable.hasObservers()) {
  20559. if (!clickInfo.ignore) {
  20560. if (!clickInfo.hasSwiped) {
  20561. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20562. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20563. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20564. _this.onPrePointerObservable.notifyObservers(pi, type);
  20565. if (pi.skipOnPointerObservable) {
  20566. return;
  20567. }
  20568. }
  20569. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20570. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20571. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20572. _this.onPrePointerObservable.notifyObservers(pi, type);
  20573. if (pi.skipOnPointerObservable) {
  20574. return;
  20575. }
  20576. }
  20577. }
  20578. }
  20579. else {
  20580. var type = BABYLON.PointerEventTypes.POINTERUP;
  20581. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20582. _this.onPrePointerObservable.notifyObservers(pi, type);
  20583. if (pi.skipOnPointerObservable) {
  20584. return;
  20585. }
  20586. }
  20587. }
  20588. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20589. return;
  20590. }
  20591. if (!_this.pointerUpPredicate) {
  20592. _this.pointerUpPredicate = function (mesh) {
  20593. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20594. };
  20595. }
  20596. // Meshes
  20597. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20598. _this._initActionManager(null, clickInfo);
  20599. }
  20600. if (!pickResult) {
  20601. pickResult = _this._currentPickResult;
  20602. }
  20603. _this._processPointerUp(pickResult, evt, clickInfo);
  20604. // Sprites
  20605. if (_this.spriteManagers.length > 0) {
  20606. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20607. if (spritePickResult) {
  20608. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20609. if (spritePickResult.pickedSprite.actionManager) {
  20610. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20611. if (spritePickResult.pickedSprite.actionManager) {
  20612. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20613. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20614. }
  20615. }
  20616. }
  20617. }
  20618. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20619. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20620. }
  20621. }
  20622. }
  20623. _this._previousPickResult = _this._currentPickResult;
  20624. });
  20625. };
  20626. this._onKeyDown = function (evt) {
  20627. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20628. if (_this.onPreKeyboardObservable.hasObservers()) {
  20629. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20630. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20631. if (pi.skipOnPointerObservable) {
  20632. return;
  20633. }
  20634. }
  20635. if (_this.onKeyboardObservable.hasObservers()) {
  20636. var pi = new BABYLON.KeyboardInfo(type, evt);
  20637. _this.onKeyboardObservable.notifyObservers(pi, type);
  20638. }
  20639. if (_this.actionManager) {
  20640. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20641. }
  20642. };
  20643. this._onKeyUp = function (evt) {
  20644. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20645. if (_this.onPreKeyboardObservable.hasObservers()) {
  20646. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20647. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20648. if (pi.skipOnPointerObservable) {
  20649. return;
  20650. }
  20651. }
  20652. if (_this.onKeyboardObservable.hasObservers()) {
  20653. var pi = new BABYLON.KeyboardInfo(type, evt);
  20654. _this.onKeyboardObservable.notifyObservers(pi, type);
  20655. }
  20656. if (_this.actionManager) {
  20657. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20658. }
  20659. };
  20660. var engine = this.getEngine();
  20661. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20662. if (!canvas) {
  20663. return;
  20664. }
  20665. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20666. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20667. });
  20668. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20669. if (!canvas) {
  20670. return;
  20671. }
  20672. canvas.removeEventListener("keydown", _this._onKeyDown);
  20673. canvas.removeEventListener("keyup", _this._onKeyUp);
  20674. });
  20675. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20676. var canvas = this._engine.getRenderingCanvas();
  20677. if (!canvas) {
  20678. return;
  20679. }
  20680. if (attachMove) {
  20681. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20682. // Wheel
  20683. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20684. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20685. }
  20686. if (attachDown) {
  20687. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20688. }
  20689. if (attachUp) {
  20690. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20691. }
  20692. canvas.tabIndex = 1;
  20693. };
  20694. Scene.prototype.detachControl = function () {
  20695. var engine = this.getEngine();
  20696. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20697. var canvas = engine.getRenderingCanvas();
  20698. if (!canvas) {
  20699. return;
  20700. }
  20701. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20702. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20703. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20704. if (this._onCanvasBlurObserver) {
  20705. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20706. }
  20707. if (this._onCanvasFocusObserver) {
  20708. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20709. }
  20710. // Wheel
  20711. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20712. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20713. // Keyboard
  20714. canvas.removeEventListener("keydown", this._onKeyDown);
  20715. canvas.removeEventListener("keyup", this._onKeyUp);
  20716. // Observables
  20717. this.onKeyboardObservable.clear();
  20718. this.onPreKeyboardObservable.clear();
  20719. this.onPointerObservable.clear();
  20720. this.onPrePointerObservable.clear();
  20721. };
  20722. /**
  20723. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20724. * Delay loaded resources are not taking in account
  20725. * @return true if all required resources are ready
  20726. */
  20727. Scene.prototype.isReady = function () {
  20728. if (this._isDisposed) {
  20729. return false;
  20730. }
  20731. if (this._pendingData.length > 0) {
  20732. return false;
  20733. }
  20734. var index;
  20735. var engine = this.getEngine();
  20736. // Geometries
  20737. for (index = 0; index < this._geometries.length; index++) {
  20738. var geometry = this._geometries[index];
  20739. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20740. return false;
  20741. }
  20742. }
  20743. // Meshes
  20744. for (index = 0; index < this.meshes.length; index++) {
  20745. var mesh = this.meshes[index];
  20746. if (!mesh.isEnabled()) {
  20747. continue;
  20748. }
  20749. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20750. continue;
  20751. }
  20752. if (!mesh.isReady()) {
  20753. return false;
  20754. }
  20755. // Highlight layers
  20756. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20757. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20758. var layer = _a[_i];
  20759. if (!layer.hasMesh(mesh)) {
  20760. continue;
  20761. }
  20762. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20763. var subMesh = _c[_b];
  20764. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20765. return false;
  20766. }
  20767. }
  20768. }
  20769. }
  20770. return true;
  20771. };
  20772. Scene.prototype.resetCachedMaterial = function () {
  20773. this._cachedMaterial = null;
  20774. this._cachedEffect = null;
  20775. this._cachedVisibility = null;
  20776. };
  20777. Scene.prototype.registerBeforeRender = function (func) {
  20778. this.onBeforeRenderObservable.add(func);
  20779. };
  20780. Scene.prototype.unregisterBeforeRender = function (func) {
  20781. this.onBeforeRenderObservable.removeCallback(func);
  20782. };
  20783. Scene.prototype.registerAfterRender = function (func) {
  20784. this.onAfterRenderObservable.add(func);
  20785. };
  20786. Scene.prototype.unregisterAfterRender = function (func) {
  20787. this.onAfterRenderObservable.removeCallback(func);
  20788. };
  20789. Scene.prototype._executeOnceBeforeRender = function (func) {
  20790. var _this = this;
  20791. var execFunc = function () {
  20792. func();
  20793. setTimeout(function () {
  20794. _this.unregisterBeforeRender(execFunc);
  20795. });
  20796. };
  20797. this.registerBeforeRender(execFunc);
  20798. };
  20799. /**
  20800. * The provided function will run before render once and will be disposed afterwards.
  20801. * A timeout delay can be provided so that the function will be executed in N ms.
  20802. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20803. * @param func The function to be executed.
  20804. * @param timeout optional delay in ms
  20805. */
  20806. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20807. var _this = this;
  20808. if (timeout !== undefined) {
  20809. setTimeout(function () {
  20810. _this._executeOnceBeforeRender(func);
  20811. }, timeout);
  20812. }
  20813. else {
  20814. this._executeOnceBeforeRender(func);
  20815. }
  20816. };
  20817. Scene.prototype._addPendingData = function (data) {
  20818. this._pendingData.push(data);
  20819. };
  20820. Scene.prototype._removePendingData = function (data) {
  20821. var wasLoading = this.isLoading;
  20822. var index = this._pendingData.indexOf(data);
  20823. if (index !== -1) {
  20824. this._pendingData.splice(index, 1);
  20825. }
  20826. if (wasLoading && !this.isLoading) {
  20827. this.onDataLoadedObservable.notifyObservers(this);
  20828. }
  20829. };
  20830. Scene.prototype.getWaitingItemsCount = function () {
  20831. return this._pendingData.length;
  20832. };
  20833. Object.defineProperty(Scene.prototype, "isLoading", {
  20834. get: function () {
  20835. return this._pendingData.length > 0;
  20836. },
  20837. enumerable: true,
  20838. configurable: true
  20839. });
  20840. /**
  20841. * Registers a function to be executed when the scene is ready.
  20842. * @param {Function} func - the function to be executed.
  20843. */
  20844. Scene.prototype.executeWhenReady = function (func) {
  20845. var _this = this;
  20846. this.onReadyObservable.add(func);
  20847. if (this._executeWhenReadyTimeoutId !== -1) {
  20848. return;
  20849. }
  20850. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20851. _this._checkIsReady();
  20852. }, 150);
  20853. };
  20854. Scene.prototype._checkIsReady = function () {
  20855. var _this = this;
  20856. if (this.isReady()) {
  20857. this.onReadyObservable.notifyObservers(this);
  20858. this.onReadyObservable.clear();
  20859. this._executeWhenReadyTimeoutId = -1;
  20860. return;
  20861. }
  20862. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20863. _this._checkIsReady();
  20864. }, 150);
  20865. };
  20866. // Animations
  20867. /**
  20868. * Will start the animation sequence of a given target
  20869. * @param target - the target
  20870. * @param {number} from - from which frame should animation start
  20871. * @param {number} to - till which frame should animation run.
  20872. * @param {boolean} [loop] - should the animation loop
  20873. * @param {number} [speedRatio] - the speed in which to run the animation
  20874. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20875. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20876. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20877. * See BABYLON.Animatable
  20878. */
  20879. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20880. if (speedRatio === void 0) { speedRatio = 1.0; }
  20881. if (from > to && speedRatio > 0) {
  20882. speedRatio *= -1;
  20883. }
  20884. this.stopAnimation(target);
  20885. if (!animatable) {
  20886. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20887. }
  20888. // Local animations
  20889. if (target.animations) {
  20890. animatable.appendAnimations(target, target.animations);
  20891. }
  20892. // Children animations
  20893. if (target.getAnimatables) {
  20894. var animatables = target.getAnimatables();
  20895. for (var index = 0; index < animatables.length; index++) {
  20896. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20897. }
  20898. }
  20899. animatable.reset();
  20900. return animatable;
  20901. };
  20902. /**
  20903. * Begin a new animation on a given node
  20904. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20905. * @param {BABYLON.Animation[]} defines the list of animations to start
  20906. * @param {number} from defines the initial value
  20907. * @param {number} to defines the final value
  20908. * @param {boolean} loop defines if you want animation to loop (off by default)
  20909. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20910. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20911. * @returns the list of created animatables
  20912. */
  20913. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20914. if (speedRatio === undefined) {
  20915. speedRatio = 1.0;
  20916. }
  20917. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20918. return animatable;
  20919. };
  20920. /**
  20921. * Begin a new animation on a given node and its hierarchy
  20922. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20923. * @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.
  20924. * @param {BABYLON.Animation[]} defines the list of animations to start
  20925. * @param {number} from defines the initial value
  20926. * @param {number} to defines the final value
  20927. * @param {boolean} loop defines if you want animation to loop (off by default)
  20928. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20929. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20930. * @returns the list of animatables created for all nodes
  20931. */
  20932. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20933. var children = target.getDescendants(directDescendantsOnly);
  20934. var result = [];
  20935. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20936. var child = children_1[_i];
  20937. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20938. }
  20939. return result;
  20940. };
  20941. Scene.prototype.getAnimatableByTarget = function (target) {
  20942. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20943. if (this._activeAnimatables[index].target === target) {
  20944. return this._activeAnimatables[index];
  20945. }
  20946. }
  20947. return null;
  20948. };
  20949. Object.defineProperty(Scene.prototype, "animatables", {
  20950. get: function () {
  20951. return this._activeAnimatables;
  20952. },
  20953. enumerable: true,
  20954. configurable: true
  20955. });
  20956. /**
  20957. * Will stop the animation of the given target
  20958. * @param target - the target
  20959. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20960. * @see beginAnimation
  20961. */
  20962. Scene.prototype.stopAnimation = function (target, animationName) {
  20963. var animatable = this.getAnimatableByTarget(target);
  20964. if (animatable) {
  20965. animatable.stop(animationName);
  20966. }
  20967. };
  20968. /**
  20969. * Stops and removes all animations that have been applied to the scene
  20970. */
  20971. Scene.prototype.stopAllAnimations = function () {
  20972. if (this._activeAnimatables) {
  20973. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20974. this._activeAnimatables[i].stop();
  20975. }
  20976. this._activeAnimatables = [];
  20977. }
  20978. };
  20979. Scene.prototype._animate = function () {
  20980. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20981. return;
  20982. }
  20983. // Getting time
  20984. var now = BABYLON.Tools.Now;
  20985. if (!this._animationTimeLast) {
  20986. if (this._pendingData.length > 0) {
  20987. return;
  20988. }
  20989. this._animationTimeLast = now;
  20990. }
  20991. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20992. this._animationTime += deltaTime;
  20993. this._animationTimeLast = now;
  20994. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20995. this._activeAnimatables[index]._animate(this._animationTime);
  20996. }
  20997. };
  20998. // Matrix
  20999. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21000. this._useAlternateCameraConfiguration = active;
  21001. };
  21002. Scene.prototype.getViewMatrix = function () {
  21003. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21004. };
  21005. Scene.prototype.getProjectionMatrix = function () {
  21006. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21007. };
  21008. Scene.prototype.getTransformMatrix = function () {
  21009. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21010. };
  21011. Scene.prototype.setTransformMatrix = function (view, projection) {
  21012. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21013. return;
  21014. }
  21015. this._viewUpdateFlag = view.updateFlag;
  21016. this._projectionUpdateFlag = projection.updateFlag;
  21017. this._viewMatrix = view;
  21018. this._projectionMatrix = projection;
  21019. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21020. // Update frustum
  21021. if (!this._frustumPlanes) {
  21022. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21023. }
  21024. else {
  21025. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21026. }
  21027. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21028. var otherCamera = this.activeCamera._alternateCamera;
  21029. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21030. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21031. }
  21032. if (this._sceneUbo.useUbo) {
  21033. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21034. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21035. this._sceneUbo.update();
  21036. }
  21037. };
  21038. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21039. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21040. return;
  21041. }
  21042. this._alternateViewUpdateFlag = view.updateFlag;
  21043. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21044. this._alternateViewMatrix = view;
  21045. this._alternateProjectionMatrix = projection;
  21046. if (!this._alternateTransformMatrix) {
  21047. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21048. }
  21049. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21050. if (!this._alternateSceneUbo) {
  21051. this._createAlternateUbo();
  21052. }
  21053. if (this._alternateSceneUbo.useUbo) {
  21054. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21055. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21056. this._alternateSceneUbo.update();
  21057. }
  21058. };
  21059. Scene.prototype.getSceneUniformBuffer = function () {
  21060. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21061. };
  21062. // Methods
  21063. Scene.prototype.getUniqueId = function () {
  21064. var result = Scene._uniqueIdCounter;
  21065. Scene._uniqueIdCounter++;
  21066. return result;
  21067. };
  21068. Scene.prototype.addMesh = function (newMesh) {
  21069. this.meshes.push(newMesh);
  21070. //notify the collision coordinator
  21071. if (this.collisionCoordinator) {
  21072. this.collisionCoordinator.onMeshAdded(newMesh);
  21073. }
  21074. newMesh._resyncLightSources();
  21075. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21076. };
  21077. Scene.prototype.removeMesh = function (toRemove) {
  21078. var index = this.meshes.indexOf(toRemove);
  21079. if (index !== -1) {
  21080. // Remove from the scene if mesh found
  21081. this.meshes.splice(index, 1);
  21082. }
  21083. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21084. return index;
  21085. };
  21086. Scene.prototype.addTransformNode = function (newTransformNode) {
  21087. this.transformNodes.push(newTransformNode);
  21088. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21089. };
  21090. Scene.prototype.removeTransformNode = function (toRemove) {
  21091. var index = this.transformNodes.indexOf(toRemove);
  21092. if (index !== -1) {
  21093. // Remove from the scene if found
  21094. this.transformNodes.splice(index, 1);
  21095. }
  21096. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21097. return index;
  21098. };
  21099. Scene.prototype.removeSkeleton = function (toRemove) {
  21100. var index = this.skeletons.indexOf(toRemove);
  21101. if (index !== -1) {
  21102. // Remove from the scene if found
  21103. this.skeletons.splice(index, 1);
  21104. }
  21105. return index;
  21106. };
  21107. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21108. var index = this.morphTargetManagers.indexOf(toRemove);
  21109. if (index !== -1) {
  21110. // Remove from the scene if found
  21111. this.morphTargetManagers.splice(index, 1);
  21112. }
  21113. return index;
  21114. };
  21115. Scene.prototype.removeLight = function (toRemove) {
  21116. var index = this.lights.indexOf(toRemove);
  21117. if (index !== -1) {
  21118. // Remove from meshes
  21119. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21120. var mesh = _a[_i];
  21121. mesh._removeLightSource(toRemove);
  21122. }
  21123. // Remove from the scene if mesh found
  21124. this.lights.splice(index, 1);
  21125. this.sortLightsByPriority();
  21126. }
  21127. this.onLightRemovedObservable.notifyObservers(toRemove);
  21128. return index;
  21129. };
  21130. Scene.prototype.removeCamera = function (toRemove) {
  21131. var index = this.cameras.indexOf(toRemove);
  21132. if (index !== -1) {
  21133. // Remove from the scene if mesh found
  21134. this.cameras.splice(index, 1);
  21135. }
  21136. // Remove from activeCameras
  21137. var index2 = this.activeCameras.indexOf(toRemove);
  21138. if (index2 !== -1) {
  21139. // Remove from the scene if mesh found
  21140. this.activeCameras.splice(index2, 1);
  21141. }
  21142. // Reset the activeCamera
  21143. if (this.activeCamera === toRemove) {
  21144. if (this.cameras.length > 0) {
  21145. this.activeCamera = this.cameras[0];
  21146. }
  21147. else {
  21148. this.activeCamera = null;
  21149. }
  21150. }
  21151. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21152. return index;
  21153. };
  21154. Scene.prototype.removeParticleSystem = function (toRemove) {
  21155. var index = this.particleSystems.indexOf(toRemove);
  21156. if (index !== -1) {
  21157. this.particleSystems.splice(index, 1);
  21158. }
  21159. return index;
  21160. };
  21161. ;
  21162. Scene.prototype.removeAnimation = function (toRemove) {
  21163. var index = this.animations.indexOf(toRemove);
  21164. if (index !== -1) {
  21165. this.animations.splice(index, 1);
  21166. }
  21167. return index;
  21168. };
  21169. ;
  21170. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21171. var index = this.multiMaterials.indexOf(toRemove);
  21172. if (index !== -1) {
  21173. this.multiMaterials.splice(index, 1);
  21174. }
  21175. return index;
  21176. };
  21177. ;
  21178. Scene.prototype.removeMaterial = function (toRemove) {
  21179. var index = this.materials.indexOf(toRemove);
  21180. if (index !== -1) {
  21181. this.materials.splice(index, 1);
  21182. }
  21183. return index;
  21184. };
  21185. ;
  21186. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21187. var index = this.lensFlareSystems.indexOf(toRemove);
  21188. if (index !== -1) {
  21189. this.lensFlareSystems.splice(index, 1);
  21190. }
  21191. return index;
  21192. };
  21193. ;
  21194. Scene.prototype.removeActionManager = function (toRemove) {
  21195. var index = this._actionManagers.indexOf(toRemove);
  21196. if (index !== -1) {
  21197. this._actionManagers.splice(index, 1);
  21198. }
  21199. return index;
  21200. };
  21201. ;
  21202. Scene.prototype.addLight = function (newLight) {
  21203. this.lights.push(newLight);
  21204. this.sortLightsByPriority();
  21205. // Add light to all meshes (To support if the light is removed and then readded)
  21206. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21207. var mesh = _a[_i];
  21208. if (mesh._lightSources.indexOf(newLight) === -1) {
  21209. mesh._lightSources.push(newLight);
  21210. mesh._resyncLightSources();
  21211. }
  21212. }
  21213. this.onNewLightAddedObservable.notifyObservers(newLight);
  21214. };
  21215. Scene.prototype.sortLightsByPriority = function () {
  21216. if (this.requireLightSorting) {
  21217. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21218. }
  21219. };
  21220. Scene.prototype.addCamera = function (newCamera) {
  21221. this.cameras.push(newCamera);
  21222. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21223. };
  21224. Scene.prototype.addSkeleton = function (newSkeleton) {
  21225. this.skeletons.push(newSkeleton);
  21226. };
  21227. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21228. this.particleSystems.push(newParticleSystem);
  21229. };
  21230. Scene.prototype.addAnimation = function (newAnimation) {
  21231. this.animations.push(newAnimation);
  21232. };
  21233. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21234. this.multiMaterials.push(newMultiMaterial);
  21235. };
  21236. Scene.prototype.addMaterial = function (newMaterial) {
  21237. this.materials.push(newMaterial);
  21238. };
  21239. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21240. this.morphTargetManagers.push(newMorphTargetManager);
  21241. };
  21242. Scene.prototype.addGeometry = function (newGeometrie) {
  21243. this._geometries.push(newGeometrie);
  21244. };
  21245. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21246. this.lensFlareSystems.push(newLensFlareSystem);
  21247. };
  21248. Scene.prototype.addActionManager = function (newActionManager) {
  21249. this._actionManagers.push(newActionManager);
  21250. };
  21251. /**
  21252. * Switch active camera
  21253. * @param {Camera} newCamera - new active camera
  21254. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21255. */
  21256. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21257. if (attachControl === void 0) { attachControl = true; }
  21258. var canvas = this._engine.getRenderingCanvas();
  21259. if (!canvas) {
  21260. return;
  21261. }
  21262. if (this.activeCamera) {
  21263. this.activeCamera.detachControl(canvas);
  21264. }
  21265. this.activeCamera = newCamera;
  21266. if (attachControl) {
  21267. newCamera.attachControl(canvas);
  21268. }
  21269. };
  21270. /**
  21271. * sets the active camera of the scene using its ID
  21272. * @param {string} id - the camera's ID
  21273. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21274. * @see activeCamera
  21275. */
  21276. Scene.prototype.setActiveCameraByID = function (id) {
  21277. var camera = this.getCameraByID(id);
  21278. if (camera) {
  21279. this.activeCamera = camera;
  21280. return camera;
  21281. }
  21282. return null;
  21283. };
  21284. /**
  21285. * sets the active camera of the scene using its name
  21286. * @param {string} name - the camera's name
  21287. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21288. * @see activeCamera
  21289. */
  21290. Scene.prototype.setActiveCameraByName = function (name) {
  21291. var camera = this.getCameraByName(name);
  21292. if (camera) {
  21293. this.activeCamera = camera;
  21294. return camera;
  21295. }
  21296. return null;
  21297. };
  21298. /**
  21299. * get an animation group using its name
  21300. * @param {string} the material's name
  21301. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21302. */
  21303. Scene.prototype.getAnimationGroupByName = function (name) {
  21304. for (var index = 0; index < this.animationGroups.length; index++) {
  21305. if (this.animationGroups[index].name === name) {
  21306. return this.animationGroups[index];
  21307. }
  21308. }
  21309. return null;
  21310. };
  21311. /**
  21312. * get a material using its id
  21313. * @param {string} the material's ID
  21314. * @return {BABYLON.Material|null} the material or null if none found.
  21315. */
  21316. Scene.prototype.getMaterialByID = function (id) {
  21317. for (var index = 0; index < this.materials.length; index++) {
  21318. if (this.materials[index].id === id) {
  21319. return this.materials[index];
  21320. }
  21321. }
  21322. return null;
  21323. };
  21324. /**
  21325. * get a material using its name
  21326. * @param {string} the material's name
  21327. * @return {BABYLON.Material|null} the material or null if none found.
  21328. */
  21329. Scene.prototype.getMaterialByName = function (name) {
  21330. for (var index = 0; index < this.materials.length; index++) {
  21331. if (this.materials[index].name === name) {
  21332. return this.materials[index];
  21333. }
  21334. }
  21335. return null;
  21336. };
  21337. Scene.prototype.getLensFlareSystemByName = function (name) {
  21338. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21339. if (this.lensFlareSystems[index].name === name) {
  21340. return this.lensFlareSystems[index];
  21341. }
  21342. }
  21343. return null;
  21344. };
  21345. Scene.prototype.getLensFlareSystemByID = function (id) {
  21346. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21347. if (this.lensFlareSystems[index].id === id) {
  21348. return this.lensFlareSystems[index];
  21349. }
  21350. }
  21351. return null;
  21352. };
  21353. Scene.prototype.getCameraByID = function (id) {
  21354. for (var index = 0; index < this.cameras.length; index++) {
  21355. if (this.cameras[index].id === id) {
  21356. return this.cameras[index];
  21357. }
  21358. }
  21359. return null;
  21360. };
  21361. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21362. for (var index = 0; index < this.cameras.length; index++) {
  21363. if (this.cameras[index].uniqueId === uniqueId) {
  21364. return this.cameras[index];
  21365. }
  21366. }
  21367. return null;
  21368. };
  21369. /**
  21370. * get a camera using its name
  21371. * @param {string} the camera's name
  21372. * @return {BABYLON.Camera|null} the camera or null if none found.
  21373. */
  21374. Scene.prototype.getCameraByName = function (name) {
  21375. for (var index = 0; index < this.cameras.length; index++) {
  21376. if (this.cameras[index].name === name) {
  21377. return this.cameras[index];
  21378. }
  21379. }
  21380. return null;
  21381. };
  21382. /**
  21383. * get a bone using its id
  21384. * @param {string} the bone's id
  21385. * @return {BABYLON.Bone|null} the bone or null if not found
  21386. */
  21387. Scene.prototype.getBoneByID = function (id) {
  21388. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21389. var skeleton = this.skeletons[skeletonIndex];
  21390. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21391. if (skeleton.bones[boneIndex].id === id) {
  21392. return skeleton.bones[boneIndex];
  21393. }
  21394. }
  21395. }
  21396. return null;
  21397. };
  21398. /**
  21399. * get a bone using its id
  21400. * @param {string} the bone's name
  21401. * @return {BABYLON.Bone|null} the bone or null if not found
  21402. */
  21403. Scene.prototype.getBoneByName = function (name) {
  21404. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21405. var skeleton = this.skeletons[skeletonIndex];
  21406. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21407. if (skeleton.bones[boneIndex].name === name) {
  21408. return skeleton.bones[boneIndex];
  21409. }
  21410. }
  21411. }
  21412. return null;
  21413. };
  21414. /**
  21415. * get a light node using its name
  21416. * @param {string} the light's name
  21417. * @return {BABYLON.Light|null} the light or null if none found.
  21418. */
  21419. Scene.prototype.getLightByName = function (name) {
  21420. for (var index = 0; index < this.lights.length; index++) {
  21421. if (this.lights[index].name === name) {
  21422. return this.lights[index];
  21423. }
  21424. }
  21425. return null;
  21426. };
  21427. /**
  21428. * get a light node using its ID
  21429. * @param {string} the light's id
  21430. * @return {BABYLON.Light|null} the light or null if none found.
  21431. */
  21432. Scene.prototype.getLightByID = function (id) {
  21433. for (var index = 0; index < this.lights.length; index++) {
  21434. if (this.lights[index].id === id) {
  21435. return this.lights[index];
  21436. }
  21437. }
  21438. return null;
  21439. };
  21440. /**
  21441. * get a light node using its scene-generated unique ID
  21442. * @param {number} the light's unique id
  21443. * @return {BABYLON.Light|null} the light or null if none found.
  21444. */
  21445. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21446. for (var index = 0; index < this.lights.length; index++) {
  21447. if (this.lights[index].uniqueId === uniqueId) {
  21448. return this.lights[index];
  21449. }
  21450. }
  21451. return null;
  21452. };
  21453. /**
  21454. * get a particle system by id
  21455. * @param id {number} the particle system id
  21456. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21457. */
  21458. Scene.prototype.getParticleSystemByID = function (id) {
  21459. for (var index = 0; index < this.particleSystems.length; index++) {
  21460. if (this.particleSystems[index].id === id) {
  21461. return this.particleSystems[index];
  21462. }
  21463. }
  21464. return null;
  21465. };
  21466. /**
  21467. * get a geometry using its ID
  21468. * @param {string} the geometry's id
  21469. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21470. */
  21471. Scene.prototype.getGeometryByID = function (id) {
  21472. for (var index = 0; index < this._geometries.length; index++) {
  21473. if (this._geometries[index].id === id) {
  21474. return this._geometries[index];
  21475. }
  21476. }
  21477. return null;
  21478. };
  21479. /**
  21480. * add a new geometry to this scene.
  21481. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21482. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21483. * @return {boolean} was the geometry added or not
  21484. */
  21485. Scene.prototype.pushGeometry = function (geometry, force) {
  21486. if (!force && this.getGeometryByID(geometry.id)) {
  21487. return false;
  21488. }
  21489. this._geometries.push(geometry);
  21490. //notify the collision coordinator
  21491. if (this.collisionCoordinator) {
  21492. this.collisionCoordinator.onGeometryAdded(geometry);
  21493. }
  21494. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21495. return true;
  21496. };
  21497. /**
  21498. * Removes an existing geometry
  21499. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21500. * @return {boolean} was the geometry removed or not
  21501. */
  21502. Scene.prototype.removeGeometry = function (geometry) {
  21503. var index = this._geometries.indexOf(geometry);
  21504. if (index > -1) {
  21505. this._geometries.splice(index, 1);
  21506. //notify the collision coordinator
  21507. if (this.collisionCoordinator) {
  21508. this.collisionCoordinator.onGeometryDeleted(geometry);
  21509. }
  21510. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21511. return true;
  21512. }
  21513. return false;
  21514. };
  21515. Scene.prototype.getGeometries = function () {
  21516. return this._geometries;
  21517. };
  21518. /**
  21519. * Get the first added mesh found of a given ID
  21520. * @param {string} id - the id to search for
  21521. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21522. */
  21523. Scene.prototype.getMeshByID = function (id) {
  21524. for (var index = 0; index < this.meshes.length; index++) {
  21525. if (this.meshes[index].id === id) {
  21526. return this.meshes[index];
  21527. }
  21528. }
  21529. return null;
  21530. };
  21531. Scene.prototype.getMeshesByID = function (id) {
  21532. return this.meshes.filter(function (m) {
  21533. return m.id === id;
  21534. });
  21535. };
  21536. /**
  21537. * Get the first added transform node found of a given ID
  21538. * @param {string} id - the id to search for
  21539. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21540. */
  21541. Scene.prototype.getTransformNodeByID = function (id) {
  21542. for (var index = 0; index < this.transformNodes.length; index++) {
  21543. if (this.transformNodes[index].id === id) {
  21544. return this.transformNodes[index];
  21545. }
  21546. }
  21547. return null;
  21548. };
  21549. Scene.prototype.getTransformNodesByID = function (id) {
  21550. return this.transformNodes.filter(function (m) {
  21551. return m.id === id;
  21552. });
  21553. };
  21554. /**
  21555. * Get a mesh with its auto-generated unique id
  21556. * @param {number} uniqueId - the unique id to search for
  21557. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21558. */
  21559. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21560. for (var index = 0; index < this.meshes.length; index++) {
  21561. if (this.meshes[index].uniqueId === uniqueId) {
  21562. return this.meshes[index];
  21563. }
  21564. }
  21565. return null;
  21566. };
  21567. /**
  21568. * Get a the last added mesh found of a given ID
  21569. * @param {string} id - the id to search for
  21570. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21571. */
  21572. Scene.prototype.getLastMeshByID = function (id) {
  21573. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21574. if (this.meshes[index].id === id) {
  21575. return this.meshes[index];
  21576. }
  21577. }
  21578. return null;
  21579. };
  21580. /**
  21581. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21582. * @param {string} id - the id to search for
  21583. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21584. */
  21585. Scene.prototype.getLastEntryByID = function (id) {
  21586. var index;
  21587. for (index = this.meshes.length - 1; index >= 0; index--) {
  21588. if (this.meshes[index].id === id) {
  21589. return this.meshes[index];
  21590. }
  21591. }
  21592. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21593. if (this.transformNodes[index].id === id) {
  21594. return this.transformNodes[index];
  21595. }
  21596. }
  21597. for (index = this.cameras.length - 1; index >= 0; index--) {
  21598. if (this.cameras[index].id === id) {
  21599. return this.cameras[index];
  21600. }
  21601. }
  21602. for (index = this.lights.length - 1; index >= 0; index--) {
  21603. if (this.lights[index].id === id) {
  21604. return this.lights[index];
  21605. }
  21606. }
  21607. return null;
  21608. };
  21609. Scene.prototype.getNodeByID = function (id) {
  21610. var mesh = this.getMeshByID(id);
  21611. if (mesh) {
  21612. return mesh;
  21613. }
  21614. var light = this.getLightByID(id);
  21615. if (light) {
  21616. return light;
  21617. }
  21618. var camera = this.getCameraByID(id);
  21619. if (camera) {
  21620. return camera;
  21621. }
  21622. var bone = this.getBoneByID(id);
  21623. return bone;
  21624. };
  21625. Scene.prototype.getNodeByName = function (name) {
  21626. var mesh = this.getMeshByName(name);
  21627. if (mesh) {
  21628. return mesh;
  21629. }
  21630. var light = this.getLightByName(name);
  21631. if (light) {
  21632. return light;
  21633. }
  21634. var camera = this.getCameraByName(name);
  21635. if (camera) {
  21636. return camera;
  21637. }
  21638. var bone = this.getBoneByName(name);
  21639. return bone;
  21640. };
  21641. Scene.prototype.getMeshByName = function (name) {
  21642. for (var index = 0; index < this.meshes.length; index++) {
  21643. if (this.meshes[index].name === name) {
  21644. return this.meshes[index];
  21645. }
  21646. }
  21647. return null;
  21648. };
  21649. Scene.prototype.getTransformNodeByName = function (name) {
  21650. for (var index = 0; index < this.transformNodes.length; index++) {
  21651. if (this.transformNodes[index].name === name) {
  21652. return this.transformNodes[index];
  21653. }
  21654. }
  21655. return null;
  21656. };
  21657. Scene.prototype.getSoundByName = function (name) {
  21658. var index;
  21659. if (BABYLON.AudioEngine) {
  21660. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21661. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21662. return this.mainSoundTrack.soundCollection[index];
  21663. }
  21664. }
  21665. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21666. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21667. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21668. return this.soundTracks[sdIndex].soundCollection[index];
  21669. }
  21670. }
  21671. }
  21672. }
  21673. return null;
  21674. };
  21675. Scene.prototype.getLastSkeletonByID = function (id) {
  21676. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21677. if (this.skeletons[index].id === id) {
  21678. return this.skeletons[index];
  21679. }
  21680. }
  21681. return null;
  21682. };
  21683. Scene.prototype.getSkeletonById = function (id) {
  21684. for (var index = 0; index < this.skeletons.length; index++) {
  21685. if (this.skeletons[index].id === id) {
  21686. return this.skeletons[index];
  21687. }
  21688. }
  21689. return null;
  21690. };
  21691. Scene.prototype.getSkeletonByName = function (name) {
  21692. for (var index = 0; index < this.skeletons.length; index++) {
  21693. if (this.skeletons[index].name === name) {
  21694. return this.skeletons[index];
  21695. }
  21696. }
  21697. return null;
  21698. };
  21699. Scene.prototype.getMorphTargetManagerById = function (id) {
  21700. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21701. if (this.morphTargetManagers[index].uniqueId === id) {
  21702. return this.morphTargetManagers[index];
  21703. }
  21704. }
  21705. return null;
  21706. };
  21707. Scene.prototype.isActiveMesh = function (mesh) {
  21708. return (this._activeMeshes.indexOf(mesh) !== -1);
  21709. };
  21710. /**
  21711. * Return a the first highlight layer of the scene with a given name.
  21712. * @param name The name of the highlight layer to look for.
  21713. * @return The highlight layer if found otherwise null.
  21714. */
  21715. Scene.prototype.getHighlightLayerByName = function (name) {
  21716. for (var index = 0; index < this.highlightLayers.length; index++) {
  21717. if (this.highlightLayers[index].name === name) {
  21718. return this.highlightLayers[index];
  21719. }
  21720. }
  21721. return null;
  21722. };
  21723. Object.defineProperty(Scene.prototype, "uid", {
  21724. /**
  21725. * Return a unique id as a string which can serve as an identifier for the scene
  21726. */
  21727. get: function () {
  21728. if (!this._uid) {
  21729. this._uid = BABYLON.Tools.RandomId();
  21730. }
  21731. return this._uid;
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. /**
  21737. * Add an externaly attached data from its key.
  21738. * This method call will fail and return false, if such key already exists.
  21739. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21740. * @param key the unique key that identifies the data
  21741. * @param data the data object to associate to the key for this Engine instance
  21742. * @return true if no such key were already present and the data was added successfully, false otherwise
  21743. */
  21744. Scene.prototype.addExternalData = function (key, data) {
  21745. if (!this._externalData) {
  21746. this._externalData = new BABYLON.StringDictionary();
  21747. }
  21748. return this._externalData.add(key, data);
  21749. };
  21750. /**
  21751. * Get an externaly attached data from its key
  21752. * @param key the unique key that identifies the data
  21753. * @return the associated data, if present (can be null), or undefined if not present
  21754. */
  21755. Scene.prototype.getExternalData = function (key) {
  21756. if (!this._externalData) {
  21757. return null;
  21758. }
  21759. return this._externalData.get(key);
  21760. };
  21761. /**
  21762. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21763. * @param key the unique key that identifies the data
  21764. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21765. * @return the associated data, can be null if the factory returned null.
  21766. */
  21767. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21768. if (!this._externalData) {
  21769. this._externalData = new BABYLON.StringDictionary();
  21770. }
  21771. return this._externalData.getOrAddWithFactory(key, factory);
  21772. };
  21773. /**
  21774. * Remove an externaly attached data from the Engine instance
  21775. * @param key the unique key that identifies the data
  21776. * @return true if the data was successfully removed, false if it doesn't exist
  21777. */
  21778. Scene.prototype.removeExternalData = function (key) {
  21779. return this._externalData.remove(key);
  21780. };
  21781. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21782. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21783. if (mesh.showSubMeshesBoundingBox) {
  21784. var boundingInfo = subMesh.getBoundingInfo();
  21785. if (boundingInfo !== null && boundingInfo !== undefined) {
  21786. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21787. }
  21788. }
  21789. var material = subMesh.getMaterial();
  21790. if (material !== null && material !== undefined) {
  21791. // Render targets
  21792. if (material.getRenderTargetTextures !== undefined) {
  21793. if (this._processedMaterials.indexOf(material) === -1) {
  21794. this._processedMaterials.push(material);
  21795. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21796. }
  21797. }
  21798. // Dispatch
  21799. this._activeIndices.addCount(subMesh.indexCount, false);
  21800. this._renderingManager.dispatch(subMesh, mesh, material);
  21801. }
  21802. }
  21803. };
  21804. Scene.prototype._isInIntermediateRendering = function () {
  21805. return this._intermediateRendering;
  21806. };
  21807. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21808. this._activeMeshCandidateProvider = provider;
  21809. };
  21810. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21811. return this._activeMeshCandidateProvider;
  21812. };
  21813. /**
  21814. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21815. */
  21816. Scene.prototype.freezeActiveMeshes = function () {
  21817. this._evaluateActiveMeshes();
  21818. this._activeMeshesFrozen = true;
  21819. return this;
  21820. };
  21821. /**
  21822. * Use this function to restart evaluating active meshes on every frame
  21823. */
  21824. Scene.prototype.unfreezeActiveMeshes = function () {
  21825. this._activeMeshesFrozen = false;
  21826. return this;
  21827. };
  21828. Scene.prototype._evaluateActiveMeshes = function () {
  21829. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21830. return;
  21831. }
  21832. if (!this.activeCamera) {
  21833. return;
  21834. }
  21835. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21836. this.activeCamera._activeMeshes.reset();
  21837. this._activeMeshes.reset();
  21838. this._renderingManager.reset();
  21839. this._processedMaterials.reset();
  21840. this._activeParticleSystems.reset();
  21841. this._activeSkeletons.reset();
  21842. this._softwareSkinnedMeshes.reset();
  21843. if (this._boundingBoxRenderer) {
  21844. this._boundingBoxRenderer.reset();
  21845. }
  21846. // Meshes
  21847. var meshes;
  21848. var len;
  21849. var checkIsEnabled = true;
  21850. // Determine mesh candidates
  21851. if (this._activeMeshCandidateProvider !== undefined) {
  21852. // Use _activeMeshCandidateProvider
  21853. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21854. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21855. if (meshes !== undefined) {
  21856. len = meshes.length;
  21857. }
  21858. else {
  21859. len = 0;
  21860. }
  21861. }
  21862. else if (this._selectionOctree !== undefined) {
  21863. // Octree
  21864. var selection = this._selectionOctree.select(this._frustumPlanes);
  21865. meshes = selection.data;
  21866. len = selection.length;
  21867. }
  21868. else {
  21869. // Full scene traversal
  21870. len = this.meshes.length;
  21871. meshes = this.meshes;
  21872. }
  21873. // Check each mesh
  21874. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21875. mesh = meshes[meshIndex];
  21876. if (mesh.isBlocked) {
  21877. continue;
  21878. }
  21879. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21880. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21881. continue;
  21882. }
  21883. mesh.computeWorldMatrix();
  21884. // Intersections
  21885. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21886. this._meshesForIntersections.pushNoDuplicate(mesh);
  21887. }
  21888. // Switch to current LOD
  21889. meshLOD = mesh.getLOD(this.activeCamera);
  21890. if (meshLOD === undefined || meshLOD === null) {
  21891. continue;
  21892. }
  21893. mesh._preActivate();
  21894. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21895. this._activeMeshes.push(mesh);
  21896. this.activeCamera._activeMeshes.push(mesh);
  21897. mesh._activate(this._renderId);
  21898. if (meshLOD !== mesh) {
  21899. meshLOD._activate(this._renderId);
  21900. }
  21901. this._activeMesh(mesh, meshLOD);
  21902. }
  21903. }
  21904. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21905. // Particle systems
  21906. if (this.particlesEnabled) {
  21907. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21908. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21909. var particleSystem = this.particleSystems[particleIndex];
  21910. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21911. continue;
  21912. }
  21913. var emitter = particleSystem.emitter;
  21914. if (!emitter.position || emitter.isEnabled()) {
  21915. this._activeParticleSystems.push(particleSystem);
  21916. particleSystem.animate();
  21917. this._renderingManager.dispatchParticles(particleSystem);
  21918. }
  21919. }
  21920. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21921. }
  21922. };
  21923. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21924. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21925. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21926. mesh.skeleton.prepare();
  21927. }
  21928. if (!mesh.computeBonesUsingShaders) {
  21929. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21930. }
  21931. }
  21932. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21933. var boundingInfo = sourceMesh.getBoundingInfo();
  21934. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21935. }
  21936. if (mesh !== undefined && mesh !== null
  21937. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21938. // Submeshes Octrees
  21939. var len;
  21940. var subMeshes;
  21941. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21942. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21943. len = intersections.length;
  21944. subMeshes = intersections.data;
  21945. }
  21946. else {
  21947. subMeshes = mesh.subMeshes;
  21948. len = subMeshes.length;
  21949. }
  21950. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21951. subMesh = subMeshes[subIndex];
  21952. this._evaluateSubMesh(subMesh, mesh);
  21953. }
  21954. }
  21955. };
  21956. Scene.prototype.updateTransformMatrix = function (force) {
  21957. if (!this.activeCamera) {
  21958. return;
  21959. }
  21960. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21961. };
  21962. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21963. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21964. };
  21965. Scene.prototype._renderForCamera = function (camera) {
  21966. if (camera && camera._skipRendering) {
  21967. return;
  21968. }
  21969. var engine = this._engine;
  21970. this.activeCamera = camera;
  21971. if (!this.activeCamera)
  21972. throw new Error("Active camera not set");
  21973. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21974. // Viewport
  21975. engine.setViewport(this.activeCamera.viewport);
  21976. // Camera
  21977. this.resetCachedMaterial();
  21978. this._renderId++;
  21979. this.activeCamera.update();
  21980. this.updateTransformMatrix();
  21981. if (camera._alternateCamera) {
  21982. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21983. this._alternateRendering = true;
  21984. }
  21985. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21986. // Meshes
  21987. this._evaluateActiveMeshes();
  21988. // Software skinning
  21989. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21990. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21991. mesh.applySkeleton(mesh.skeleton);
  21992. }
  21993. // Render targets
  21994. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21995. var needsRestoreFrameBuffer = false;
  21996. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21997. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21998. }
  21999. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22000. this._intermediateRendering = true;
  22001. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22002. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22003. var renderTarget = this._renderTargets.data[renderIndex];
  22004. if (renderTarget._shouldRender()) {
  22005. this._renderId++;
  22006. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22007. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22008. }
  22009. }
  22010. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22011. this._intermediateRendering = false;
  22012. this._renderId++;
  22013. needsRestoreFrameBuffer = true; // Restore back buffer
  22014. }
  22015. // Render HighlightLayer Texture
  22016. var stencilState = this._engine.getStencilBuffer();
  22017. var renderhighlights = false;
  22018. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22019. this._intermediateRendering = true;
  22020. for (var i = 0; i < this.highlightLayers.length; i++) {
  22021. var highlightLayer = this.highlightLayers[i];
  22022. if (highlightLayer.shouldRender() &&
  22023. (!highlightLayer.camera ||
  22024. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22025. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22026. renderhighlights = true;
  22027. var renderTarget = highlightLayer._mainTexture;
  22028. if (renderTarget._shouldRender()) {
  22029. this._renderId++;
  22030. renderTarget.render(false, false);
  22031. needsRestoreFrameBuffer = true;
  22032. }
  22033. }
  22034. }
  22035. this._intermediateRendering = false;
  22036. this._renderId++;
  22037. }
  22038. if (needsRestoreFrameBuffer) {
  22039. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22040. }
  22041. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22042. // Prepare Frame
  22043. this.postProcessManager._prepareFrame();
  22044. // Backgrounds
  22045. var layerIndex;
  22046. var layer;
  22047. if (this.layers.length) {
  22048. engine.setDepthBuffer(false);
  22049. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22050. layer = this.layers[layerIndex];
  22051. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22052. layer.render();
  22053. }
  22054. }
  22055. engine.setDepthBuffer(true);
  22056. }
  22057. // Activate HighlightLayer stencil
  22058. if (renderhighlights) {
  22059. this._engine.setStencilBuffer(true);
  22060. }
  22061. // Render
  22062. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22063. this._renderingManager.render(null, null, true, true);
  22064. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22065. // Restore HighlightLayer stencil
  22066. if (renderhighlights) {
  22067. this._engine.setStencilBuffer(stencilState);
  22068. }
  22069. // Bounding boxes
  22070. if (this._boundingBoxRenderer) {
  22071. this._boundingBoxRenderer.render();
  22072. }
  22073. // Lens flares
  22074. if (this.lensFlaresEnabled) {
  22075. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22076. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22077. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22078. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22079. lensFlareSystem.render();
  22080. }
  22081. }
  22082. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22083. }
  22084. // Foregrounds
  22085. if (this.layers.length) {
  22086. engine.setDepthBuffer(false);
  22087. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22088. layer = this.layers[layerIndex];
  22089. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22090. layer.render();
  22091. }
  22092. }
  22093. engine.setDepthBuffer(true);
  22094. }
  22095. // Highlight Layer
  22096. if (renderhighlights) {
  22097. engine.setDepthBuffer(false);
  22098. for (var i = 0; i < this.highlightLayers.length; i++) {
  22099. if (this.highlightLayers[i].shouldRender()) {
  22100. this.highlightLayers[i].render();
  22101. }
  22102. }
  22103. engine.setDepthBuffer(true);
  22104. }
  22105. // Finalize frame
  22106. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22107. // Reset some special arrays
  22108. this._renderTargets.reset();
  22109. this._alternateRendering = false;
  22110. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22111. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22112. };
  22113. Scene.prototype._processSubCameras = function (camera) {
  22114. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22115. this._renderForCamera(camera);
  22116. return;
  22117. }
  22118. // Update camera
  22119. if (this.activeCamera) {
  22120. this.activeCamera.update();
  22121. }
  22122. // rig cameras
  22123. for (var index = 0; index < camera._rigCameras.length; index++) {
  22124. this._renderForCamera(camera._rigCameras[index]);
  22125. }
  22126. this.activeCamera = camera;
  22127. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22128. };
  22129. Scene.prototype._checkIntersections = function () {
  22130. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22131. var sourceMesh = this._meshesForIntersections.data[index];
  22132. if (!sourceMesh.actionManager) {
  22133. continue;
  22134. }
  22135. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22136. var action = sourceMesh.actionManager.actions[actionIndex];
  22137. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22138. var parameters = action.getTriggerParameter();
  22139. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22140. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22141. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22142. if (areIntersecting && currentIntersectionInProgress === -1) {
  22143. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22144. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22145. sourceMesh._intersectionsInProgress.push(otherMesh);
  22146. }
  22147. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22148. sourceMesh._intersectionsInProgress.push(otherMesh);
  22149. }
  22150. }
  22151. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22152. //They intersected, and now they don't.
  22153. //is this trigger an exit trigger? execute an event.
  22154. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22155. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22156. }
  22157. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22158. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22159. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22160. }
  22161. }
  22162. }
  22163. }
  22164. }
  22165. };
  22166. Scene.prototype.render = function () {
  22167. if (this.isDisposed) {
  22168. return;
  22169. }
  22170. this._activeParticles.fetchNewFrame();
  22171. this._totalVertices.fetchNewFrame();
  22172. this._activeIndices.fetchNewFrame();
  22173. this._activeBones.fetchNewFrame();
  22174. this._meshesForIntersections.reset();
  22175. this.resetCachedMaterial();
  22176. this.onBeforeAnimationsObservable.notifyObservers(this);
  22177. // Actions
  22178. if (this.actionManager) {
  22179. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22180. }
  22181. //Simplification Queue
  22182. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22183. this.simplificationQueue.executeNext();
  22184. }
  22185. if (this._engine.isDeterministicLockStep()) {
  22186. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22187. var defaultFPS = (60.0 / 1000.0);
  22188. var defaultFrameTime = 1000 / 60; // frame time in MS
  22189. if (this._physicsEngine) {
  22190. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22191. }
  22192. var stepsTaken = 0;
  22193. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22194. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22195. internalSteps = Math.min(internalSteps, maxSubSteps);
  22196. do {
  22197. this.onBeforeStepObservable.notifyObservers(this);
  22198. // Animations
  22199. this._animationRatio = defaultFrameTime * defaultFPS;
  22200. this._animate();
  22201. this.onAfterAnimationsObservable.notifyObservers(this);
  22202. // Physics
  22203. if (this._physicsEngine) {
  22204. this.onBeforePhysicsObservable.notifyObservers(this);
  22205. this._physicsEngine._step(defaultFrameTime / 1000);
  22206. this.onAfterPhysicsObservable.notifyObservers(this);
  22207. }
  22208. this.onAfterStepObservable.notifyObservers(this);
  22209. this._currentStepId++;
  22210. stepsTaken++;
  22211. deltaTime -= defaultFrameTime;
  22212. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22213. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22214. }
  22215. else {
  22216. // Animations
  22217. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22218. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22219. this._animate();
  22220. this.onAfterAnimationsObservable.notifyObservers(this);
  22221. // Physics
  22222. if (this._physicsEngine) {
  22223. this.onBeforePhysicsObservable.notifyObservers(this);
  22224. this._physicsEngine._step(deltaTime / 1000.0);
  22225. this.onAfterPhysicsObservable.notifyObservers(this);
  22226. }
  22227. }
  22228. // update gamepad manager
  22229. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22230. this._gamepadManager._checkGamepadsStatus();
  22231. }
  22232. // Before render
  22233. this.onBeforeRenderObservable.notifyObservers(this);
  22234. // Customs render targets
  22235. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22236. var engine = this.getEngine();
  22237. var currentActiveCamera = this.activeCamera;
  22238. if (this.renderTargetsEnabled) {
  22239. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22240. this._intermediateRendering = true;
  22241. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22242. var renderTarget = this.customRenderTargets[customIndex];
  22243. if (renderTarget._shouldRender()) {
  22244. this._renderId++;
  22245. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22246. if (!this.activeCamera)
  22247. throw new Error("Active camera not set");
  22248. // Viewport
  22249. engine.setViewport(this.activeCamera.viewport);
  22250. // Camera
  22251. this.updateTransformMatrix();
  22252. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22253. }
  22254. }
  22255. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22256. this._intermediateRendering = false;
  22257. this._renderId++;
  22258. }
  22259. // Restore back buffer
  22260. if (this.customRenderTargets.length > 0) {
  22261. engine.restoreDefaultFramebuffer();
  22262. }
  22263. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22264. this.activeCamera = currentActiveCamera;
  22265. // Procedural textures
  22266. if (this.proceduralTexturesEnabled) {
  22267. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22268. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22269. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22270. if (proceduralTexture._shouldRender()) {
  22271. proceduralTexture.render();
  22272. }
  22273. }
  22274. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22275. }
  22276. // Clear
  22277. if (this.autoClearDepthAndStencil || this.autoClear) {
  22278. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22279. }
  22280. // Shadows
  22281. if (this.shadowsEnabled) {
  22282. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22283. var light = this.lights[lightIndex];
  22284. var shadowGenerator = light.getShadowGenerator();
  22285. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22286. var shadowMap = (shadowGenerator.getShadowMap());
  22287. if (this.textures.indexOf(shadowMap) !== -1) {
  22288. this._renderTargets.push(shadowMap);
  22289. }
  22290. }
  22291. }
  22292. }
  22293. // Depth renderer
  22294. if (this._depthRenderer) {
  22295. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22296. }
  22297. // Geometry renderer
  22298. if (this._geometryBufferRenderer) {
  22299. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22300. }
  22301. // RenderPipeline
  22302. if (this._postProcessRenderPipelineManager) {
  22303. this._postProcessRenderPipelineManager.update();
  22304. }
  22305. // Multi-cameras?
  22306. if (this.activeCameras.length > 0) {
  22307. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22308. if (cameraIndex > 0) {
  22309. this._engine.clear(null, false, true, true);
  22310. }
  22311. this._processSubCameras(this.activeCameras[cameraIndex]);
  22312. }
  22313. }
  22314. else {
  22315. if (!this.activeCamera) {
  22316. throw new Error("No camera defined");
  22317. }
  22318. this._processSubCameras(this.activeCamera);
  22319. }
  22320. // Intersection checks
  22321. this._checkIntersections();
  22322. // Update the audio listener attached to the camera
  22323. if (BABYLON.AudioEngine) {
  22324. this._updateAudioParameters();
  22325. }
  22326. // After render
  22327. if (this.afterRender) {
  22328. this.afterRender();
  22329. }
  22330. this.onAfterRenderObservable.notifyObservers(this);
  22331. // Cleaning
  22332. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22333. var data = this._toBeDisposed.data[index];
  22334. if (data) {
  22335. data.dispose();
  22336. }
  22337. this._toBeDisposed[index] = null;
  22338. }
  22339. this._toBeDisposed.reset();
  22340. if (this.dumpNextRenderTargets) {
  22341. this.dumpNextRenderTargets = false;
  22342. }
  22343. this._activeBones.addCount(0, true);
  22344. this._activeIndices.addCount(0, true);
  22345. this._activeParticles.addCount(0, true);
  22346. };
  22347. Scene.prototype._updateAudioParameters = function () {
  22348. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22349. return;
  22350. }
  22351. var listeningCamera;
  22352. var audioEngine = BABYLON.Engine.audioEngine;
  22353. if (this.activeCameras.length > 0) {
  22354. listeningCamera = this.activeCameras[0];
  22355. }
  22356. else {
  22357. listeningCamera = this.activeCamera;
  22358. }
  22359. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22360. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22361. // for VR cameras
  22362. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22363. listeningCamera = listeningCamera.rigCameras[0];
  22364. }
  22365. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22366. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22367. cameraDirection.normalize();
  22368. // To avoid some errors on GearVR
  22369. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22370. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22371. }
  22372. var i;
  22373. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22374. var sound = this.mainSoundTrack.soundCollection[i];
  22375. if (sound.useCustomAttenuation) {
  22376. sound.updateDistanceFromListener();
  22377. }
  22378. }
  22379. for (i = 0; i < this.soundTracks.length; i++) {
  22380. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22381. sound = this.soundTracks[i].soundCollection[j];
  22382. if (sound.useCustomAttenuation) {
  22383. sound.updateDistanceFromListener();
  22384. }
  22385. }
  22386. }
  22387. }
  22388. };
  22389. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22390. // Audio
  22391. get: function () {
  22392. return this._audioEnabled;
  22393. },
  22394. set: function (value) {
  22395. this._audioEnabled = value;
  22396. if (BABYLON.AudioEngine) {
  22397. if (this._audioEnabled) {
  22398. this._enableAudio();
  22399. }
  22400. else {
  22401. this._disableAudio();
  22402. }
  22403. }
  22404. },
  22405. enumerable: true,
  22406. configurable: true
  22407. });
  22408. Scene.prototype._disableAudio = function () {
  22409. var i;
  22410. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22411. this.mainSoundTrack.soundCollection[i].pause();
  22412. }
  22413. for (i = 0; i < this.soundTracks.length; i++) {
  22414. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22415. this.soundTracks[i].soundCollection[j].pause();
  22416. }
  22417. }
  22418. };
  22419. Scene.prototype._enableAudio = function () {
  22420. var i;
  22421. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22422. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22423. this.mainSoundTrack.soundCollection[i].play();
  22424. }
  22425. }
  22426. for (i = 0; i < this.soundTracks.length; i++) {
  22427. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22428. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22429. this.soundTracks[i].soundCollection[j].play();
  22430. }
  22431. }
  22432. }
  22433. };
  22434. Object.defineProperty(Scene.prototype, "headphone", {
  22435. get: function () {
  22436. return this._headphone;
  22437. },
  22438. set: function (value) {
  22439. this._headphone = value;
  22440. if (BABYLON.AudioEngine) {
  22441. if (this._headphone) {
  22442. this._switchAudioModeForHeadphones();
  22443. }
  22444. else {
  22445. this._switchAudioModeForNormalSpeakers();
  22446. }
  22447. }
  22448. },
  22449. enumerable: true,
  22450. configurable: true
  22451. });
  22452. Scene.prototype._switchAudioModeForHeadphones = function () {
  22453. this.mainSoundTrack.switchPanningModelToHRTF();
  22454. for (var i = 0; i < this.soundTracks.length; i++) {
  22455. this.soundTracks[i].switchPanningModelToHRTF();
  22456. }
  22457. };
  22458. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22459. this.mainSoundTrack.switchPanningModelToEqualPower();
  22460. for (var i = 0; i < this.soundTracks.length; i++) {
  22461. this.soundTracks[i].switchPanningModelToEqualPower();
  22462. }
  22463. };
  22464. Scene.prototype.enableDepthRenderer = function () {
  22465. if (this._depthRenderer) {
  22466. return this._depthRenderer;
  22467. }
  22468. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22469. return this._depthRenderer;
  22470. };
  22471. Scene.prototype.disableDepthRenderer = function () {
  22472. if (!this._depthRenderer) {
  22473. return;
  22474. }
  22475. this._depthRenderer.dispose();
  22476. this._depthRenderer = null;
  22477. };
  22478. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22479. if (ratio === void 0) { ratio = 1; }
  22480. if (this._geometryBufferRenderer) {
  22481. return this._geometryBufferRenderer;
  22482. }
  22483. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22484. if (!this._geometryBufferRenderer.isSupported) {
  22485. this._geometryBufferRenderer = null;
  22486. }
  22487. return this._geometryBufferRenderer;
  22488. };
  22489. Scene.prototype.disableGeometryBufferRenderer = function () {
  22490. if (!this._geometryBufferRenderer) {
  22491. return;
  22492. }
  22493. this._geometryBufferRenderer.dispose();
  22494. this._geometryBufferRenderer = null;
  22495. };
  22496. Scene.prototype.freezeMaterials = function () {
  22497. for (var i = 0; i < this.materials.length; i++) {
  22498. this.materials[i].freeze();
  22499. }
  22500. };
  22501. Scene.prototype.unfreezeMaterials = function () {
  22502. for (var i = 0; i < this.materials.length; i++) {
  22503. this.materials[i].unfreeze();
  22504. }
  22505. };
  22506. Scene.prototype.dispose = function () {
  22507. this.beforeRender = null;
  22508. this.afterRender = null;
  22509. this.skeletons = [];
  22510. this.morphTargetManagers = [];
  22511. this.importedMeshesFiles = new Array();
  22512. this.stopAllAnimations();
  22513. this.resetCachedMaterial();
  22514. if (this._depthRenderer) {
  22515. this._depthRenderer.dispose();
  22516. }
  22517. if (this._gamepadManager) {
  22518. this._gamepadManager.dispose();
  22519. this._gamepadManager = null;
  22520. }
  22521. // Smart arrays
  22522. if (this.activeCamera) {
  22523. this.activeCamera._activeMeshes.dispose();
  22524. this.activeCamera = null;
  22525. }
  22526. this._activeMeshes.dispose();
  22527. this._renderingManager.dispose();
  22528. this._processedMaterials.dispose();
  22529. this._activeParticleSystems.dispose();
  22530. this._activeSkeletons.dispose();
  22531. this._softwareSkinnedMeshes.dispose();
  22532. this._renderTargets.dispose();
  22533. if (this._boundingBoxRenderer) {
  22534. this._boundingBoxRenderer.dispose();
  22535. }
  22536. this._meshesForIntersections.dispose();
  22537. this._toBeDisposed.dispose();
  22538. // Abort active requests
  22539. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22540. var request = _a[_i];
  22541. request.abort();
  22542. }
  22543. // Debug layer
  22544. if (this._debugLayer) {
  22545. this._debugLayer.hide();
  22546. }
  22547. // Events
  22548. this.onDisposeObservable.notifyObservers(this);
  22549. this.onDisposeObservable.clear();
  22550. this.onBeforeRenderObservable.clear();
  22551. this.onAfterRenderObservable.clear();
  22552. this.OnBeforeRenderTargetsRenderObservable.clear();
  22553. this.OnAfterRenderTargetsRenderObservable.clear();
  22554. this.onAfterStepObservable.clear();
  22555. this.onBeforeStepObservable.clear();
  22556. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22557. this.onAfterActiveMeshesEvaluationObservable.clear();
  22558. this.onBeforeParticlesRenderingObservable.clear();
  22559. this.onAfterParticlesRenderingObservable.clear();
  22560. this.onBeforeSpritesRenderingObservable.clear();
  22561. this.onAfterSpritesRenderingObservable.clear();
  22562. this.onBeforeDrawPhaseObservable.clear();
  22563. this.onAfterDrawPhaseObservable.clear();
  22564. this.onBeforePhysicsObservable.clear();
  22565. this.onAfterPhysicsObservable.clear();
  22566. this.onBeforeAnimationsObservable.clear();
  22567. this.onAfterAnimationsObservable.clear();
  22568. this.onDataLoadedObservable.clear();
  22569. this.detachControl();
  22570. // Release sounds & sounds tracks
  22571. if (BABYLON.AudioEngine) {
  22572. this.disposeSounds();
  22573. }
  22574. // VR Helper
  22575. if (this.VRHelper) {
  22576. this.VRHelper.dispose();
  22577. }
  22578. // Detach cameras
  22579. var canvas = this._engine.getRenderingCanvas();
  22580. if (canvas) {
  22581. var index;
  22582. for (index = 0; index < this.cameras.length; index++) {
  22583. this.cameras[index].detachControl(canvas);
  22584. }
  22585. }
  22586. // Release animation groups
  22587. while (this.animationGroups.length) {
  22588. this.animationGroups[0].dispose();
  22589. }
  22590. // Release lights
  22591. while (this.lights.length) {
  22592. this.lights[0].dispose();
  22593. }
  22594. // Release meshes
  22595. while (this.meshes.length) {
  22596. this.meshes[0].dispose(true);
  22597. }
  22598. while (this.transformNodes.length) {
  22599. this.removeTransformNode(this.transformNodes[0]);
  22600. }
  22601. // Release cameras
  22602. while (this.cameras.length) {
  22603. this.cameras[0].dispose();
  22604. }
  22605. // Release materials
  22606. if (this.defaultMaterial) {
  22607. this.defaultMaterial.dispose();
  22608. }
  22609. while (this.multiMaterials.length) {
  22610. this.multiMaterials[0].dispose();
  22611. }
  22612. while (this.materials.length) {
  22613. this.materials[0].dispose();
  22614. }
  22615. // Release particles
  22616. while (this.particleSystems.length) {
  22617. this.particleSystems[0].dispose();
  22618. }
  22619. // Release sprites
  22620. while (this.spriteManagers.length) {
  22621. this.spriteManagers[0].dispose();
  22622. }
  22623. // Release postProcesses
  22624. while (this.postProcesses.length) {
  22625. this.postProcesses[0].dispose();
  22626. }
  22627. // Release layers
  22628. while (this.layers.length) {
  22629. this.layers[0].dispose();
  22630. }
  22631. while (this.highlightLayers.length) {
  22632. this.highlightLayers[0].dispose();
  22633. }
  22634. // Release textures
  22635. while (this.textures.length) {
  22636. this.textures[0].dispose();
  22637. }
  22638. // Release UBO
  22639. this._sceneUbo.dispose();
  22640. if (this._alternateSceneUbo) {
  22641. this._alternateSceneUbo.dispose();
  22642. }
  22643. // Post-processes
  22644. this.postProcessManager.dispose();
  22645. if (this._postProcessRenderPipelineManager) {
  22646. this._postProcessRenderPipelineManager.dispose();
  22647. }
  22648. // Physics
  22649. if (this._physicsEngine) {
  22650. this.disablePhysicsEngine();
  22651. }
  22652. // Remove from engine
  22653. index = this._engine.scenes.indexOf(this);
  22654. if (index > -1) {
  22655. this._engine.scenes.splice(index, 1);
  22656. }
  22657. this._engine.wipeCaches(true);
  22658. this._isDisposed = true;
  22659. };
  22660. Object.defineProperty(Scene.prototype, "isDisposed", {
  22661. get: function () {
  22662. return this._isDisposed;
  22663. },
  22664. enumerable: true,
  22665. configurable: true
  22666. });
  22667. // Release sounds & sounds tracks
  22668. Scene.prototype.disposeSounds = function () {
  22669. if (!this._mainSoundTrack) {
  22670. return;
  22671. }
  22672. this.mainSoundTrack.dispose();
  22673. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22674. this.soundTracks[scIndex].dispose();
  22675. }
  22676. };
  22677. // Octrees
  22678. Scene.prototype.getWorldExtends = function () {
  22679. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22680. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22681. for (var index = 0; index < this.meshes.length; index++) {
  22682. var mesh = this.meshes[index];
  22683. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22684. continue;
  22685. }
  22686. mesh.computeWorldMatrix(true);
  22687. var boundingInfo = mesh.getBoundingInfo();
  22688. var minBox = boundingInfo.boundingBox.minimumWorld;
  22689. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22690. BABYLON.Tools.CheckExtends(minBox, min, max);
  22691. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22692. }
  22693. return {
  22694. min: min,
  22695. max: max
  22696. };
  22697. };
  22698. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22699. if (maxCapacity === void 0) { maxCapacity = 64; }
  22700. if (maxDepth === void 0) { maxDepth = 2; }
  22701. if (!this._selectionOctree) {
  22702. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22703. }
  22704. var worldExtends = this.getWorldExtends();
  22705. // Update octree
  22706. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22707. return this._selectionOctree;
  22708. };
  22709. // Picking
  22710. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22711. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22712. var result = BABYLON.Ray.Zero();
  22713. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22714. return result;
  22715. };
  22716. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22717. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22718. var engine = this._engine;
  22719. if (!camera) {
  22720. if (!this.activeCamera)
  22721. throw new Error("Active camera not set");
  22722. camera = this.activeCamera;
  22723. }
  22724. var cameraViewport = camera.viewport;
  22725. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22726. // Moving coordinates to local viewport world
  22727. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22728. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22729. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22730. return this;
  22731. };
  22732. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22733. var result = BABYLON.Ray.Zero();
  22734. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22735. return result;
  22736. };
  22737. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22738. if (!BABYLON.PickingInfo) {
  22739. return this;
  22740. }
  22741. var engine = this._engine;
  22742. if (!camera) {
  22743. if (!this.activeCamera)
  22744. throw new Error("Active camera not set");
  22745. camera = this.activeCamera;
  22746. }
  22747. var cameraViewport = camera.viewport;
  22748. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22749. var identity = BABYLON.Matrix.Identity();
  22750. // Moving coordinates to local viewport world
  22751. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22752. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22753. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22754. return this;
  22755. };
  22756. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22757. if (!BABYLON.PickingInfo) {
  22758. return null;
  22759. }
  22760. var pickingInfo = null;
  22761. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22762. var mesh = this.meshes[meshIndex];
  22763. if (predicate) {
  22764. if (!predicate(mesh)) {
  22765. continue;
  22766. }
  22767. }
  22768. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22769. continue;
  22770. }
  22771. var world = mesh.getWorldMatrix();
  22772. var ray = rayFunction(world);
  22773. var result = mesh.intersects(ray, fastCheck);
  22774. if (!result || !result.hit)
  22775. continue;
  22776. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22777. continue;
  22778. pickingInfo = result;
  22779. if (fastCheck) {
  22780. break;
  22781. }
  22782. }
  22783. return pickingInfo || new BABYLON.PickingInfo();
  22784. };
  22785. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22786. if (!BABYLON.PickingInfo) {
  22787. return null;
  22788. }
  22789. var pickingInfos = new Array();
  22790. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22791. var mesh = this.meshes[meshIndex];
  22792. if (predicate) {
  22793. if (!predicate(mesh)) {
  22794. continue;
  22795. }
  22796. }
  22797. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22798. continue;
  22799. }
  22800. var world = mesh.getWorldMatrix();
  22801. var ray = rayFunction(world);
  22802. var result = mesh.intersects(ray, false);
  22803. if (!result || !result.hit)
  22804. continue;
  22805. pickingInfos.push(result);
  22806. }
  22807. return pickingInfos;
  22808. };
  22809. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22810. if (!BABYLON.PickingInfo) {
  22811. return null;
  22812. }
  22813. var pickingInfo = null;
  22814. if (!camera) {
  22815. if (!this.activeCamera) {
  22816. return null;
  22817. }
  22818. camera = this.activeCamera;
  22819. }
  22820. if (this.spriteManagers.length > 0) {
  22821. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22822. var spriteManager = this.spriteManagers[spriteIndex];
  22823. if (!spriteManager.isPickable) {
  22824. continue;
  22825. }
  22826. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22827. if (!result || !result.hit)
  22828. continue;
  22829. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22830. continue;
  22831. pickingInfo = result;
  22832. if (fastCheck) {
  22833. break;
  22834. }
  22835. }
  22836. }
  22837. return pickingInfo || new BABYLON.PickingInfo();
  22838. };
  22839. /** Launch a ray to try to pick a mesh in the scene
  22840. * @param x position on screen
  22841. * @param y position on screen
  22842. * @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
  22843. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22844. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22845. */
  22846. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22847. var _this = this;
  22848. if (!BABYLON.PickingInfo) {
  22849. return null;
  22850. }
  22851. return this._internalPick(function (world) {
  22852. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22853. return _this._tempPickingRay;
  22854. }, predicate, fastCheck);
  22855. };
  22856. /** Launch a ray to try to pick a sprite in the scene
  22857. * @param x position on screen
  22858. * @param y position on screen
  22859. * @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
  22860. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22861. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22862. */
  22863. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22864. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22865. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22866. };
  22867. /** Use the given ray to pick a mesh in the scene
  22868. * @param ray The ray to use to pick meshes
  22869. * @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
  22870. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22871. */
  22872. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22873. var _this = this;
  22874. return this._internalPick(function (world) {
  22875. if (!_this._pickWithRayInverseMatrix) {
  22876. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22877. }
  22878. world.invertToRef(_this._pickWithRayInverseMatrix);
  22879. if (!_this._cachedRayForTransform) {
  22880. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22881. }
  22882. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22883. return _this._cachedRayForTransform;
  22884. }, predicate, fastCheck);
  22885. };
  22886. /**
  22887. * Launch a ray to try to pick a mesh in the scene
  22888. * @param x X position on screen
  22889. * @param y Y position on screen
  22890. * @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
  22891. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22892. */
  22893. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22894. var _this = this;
  22895. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22896. };
  22897. /**
  22898. * Launch a ray to try to pick a mesh in the scene
  22899. * @param ray Ray to use
  22900. * @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
  22901. */
  22902. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22903. var _this = this;
  22904. return this._internalMultiPick(function (world) {
  22905. if (!_this._pickWithRayInverseMatrix) {
  22906. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22907. }
  22908. world.invertToRef(_this._pickWithRayInverseMatrix);
  22909. if (!_this._cachedRayForTransform) {
  22910. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22911. }
  22912. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22913. return _this._cachedRayForTransform;
  22914. }, predicate);
  22915. };
  22916. Scene.prototype.setPointerOverMesh = function (mesh) {
  22917. if (this._pointerOverMesh === mesh) {
  22918. return;
  22919. }
  22920. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22921. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22922. }
  22923. this._pointerOverMesh = mesh;
  22924. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22925. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22926. }
  22927. };
  22928. Scene.prototype.getPointerOverMesh = function () {
  22929. return this._pointerOverMesh;
  22930. };
  22931. Scene.prototype.setPointerOverSprite = function (sprite) {
  22932. if (this._pointerOverSprite === sprite) {
  22933. return;
  22934. }
  22935. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22936. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22937. }
  22938. this._pointerOverSprite = sprite;
  22939. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22940. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22941. }
  22942. };
  22943. Scene.prototype.getPointerOverSprite = function () {
  22944. return this._pointerOverSprite;
  22945. };
  22946. // Physics
  22947. Scene.prototype.getPhysicsEngine = function () {
  22948. return this._physicsEngine;
  22949. };
  22950. /**
  22951. * Enables physics to the current scene
  22952. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22953. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22954. * @return {boolean} was the physics engine initialized
  22955. */
  22956. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22957. if (gravity === void 0) { gravity = null; }
  22958. if (this._physicsEngine) {
  22959. return true;
  22960. }
  22961. try {
  22962. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22963. return true;
  22964. }
  22965. catch (e) {
  22966. BABYLON.Tools.Error(e.message);
  22967. return false;
  22968. }
  22969. };
  22970. Scene.prototype.disablePhysicsEngine = function () {
  22971. if (!this._physicsEngine) {
  22972. return;
  22973. }
  22974. this._physicsEngine.dispose();
  22975. this._physicsEngine = null;
  22976. };
  22977. Scene.prototype.isPhysicsEnabled = function () {
  22978. return this._physicsEngine !== undefined;
  22979. };
  22980. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22981. var mesh = compound.parts[0].mesh;
  22982. if (mesh.physicsImpostor) {
  22983. mesh.physicsImpostor.dispose();
  22984. mesh.physicsImpostor = null;
  22985. }
  22986. };
  22987. // Misc.
  22988. Scene.prototype._rebuildGeometries = function () {
  22989. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22990. var geometry = _a[_i];
  22991. geometry._rebuild();
  22992. }
  22993. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22994. var mesh = _c[_b];
  22995. mesh._rebuild();
  22996. }
  22997. if (this.postProcessManager) {
  22998. this.postProcessManager._rebuild();
  22999. }
  23000. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23001. var layer = _e[_d];
  23002. layer._rebuild();
  23003. }
  23004. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23005. var highlightLayer = _g[_f];
  23006. highlightLayer._rebuild();
  23007. }
  23008. if (this._boundingBoxRenderer) {
  23009. this._boundingBoxRenderer._rebuild();
  23010. }
  23011. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23012. var system = _j[_h];
  23013. system.rebuild();
  23014. }
  23015. if (this._postProcessRenderPipelineManager) {
  23016. this._postProcessRenderPipelineManager._rebuild();
  23017. }
  23018. };
  23019. Scene.prototype._rebuildTextures = function () {
  23020. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23021. var texture = _a[_i];
  23022. texture._rebuild();
  23023. }
  23024. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23025. };
  23026. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23027. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23028. if (replace === void 0) { replace = false; }
  23029. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23030. // Dispose existing camera or light in replace mode.
  23031. if (replace) {
  23032. if (this.activeCamera) {
  23033. this.activeCamera.dispose();
  23034. this.activeCamera = null;
  23035. }
  23036. if (this.lights) {
  23037. for (var i = 0; i < this.lights.length; i++) {
  23038. this.lights[i].dispose();
  23039. }
  23040. }
  23041. }
  23042. // Light
  23043. if (this.lights.length === 0) {
  23044. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23045. }
  23046. // Camera
  23047. if (!this.activeCamera) {
  23048. var worldExtends = this.getWorldExtends();
  23049. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23050. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23051. var camera;
  23052. var radius = worldSize.length() * 1.5;
  23053. if (createArcRotateCamera) {
  23054. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23055. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23056. arcRotateCamera.wheelPrecision = 100 / radius;
  23057. camera = arcRotateCamera;
  23058. }
  23059. else {
  23060. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23061. freeCamera.setTarget(worldCenter);
  23062. camera = freeCamera;
  23063. }
  23064. camera.minZ = radius * 0.01;
  23065. camera.maxZ = radius * 1000;
  23066. camera.speed = radius * 0.2;
  23067. this.activeCamera = camera;
  23068. var canvas = this.getEngine().getRenderingCanvas();
  23069. if (attachCameraControls && canvas) {
  23070. camera.attachControl(canvas);
  23071. }
  23072. }
  23073. };
  23074. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23075. if (pbr === void 0) { pbr = false; }
  23076. if (scale === void 0) { scale = 1000; }
  23077. if (blur === void 0) { blur = 0; }
  23078. if (environmentTexture) {
  23079. this.environmentTexture = environmentTexture;
  23080. }
  23081. if (!this.environmentTexture) {
  23082. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23083. return null;
  23084. }
  23085. // Skybox
  23086. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23087. if (pbr) {
  23088. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23089. hdrSkyboxMaterial.backFaceCulling = false;
  23090. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23091. if (hdrSkyboxMaterial.reflectionTexture) {
  23092. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23093. }
  23094. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23095. hdrSkyboxMaterial.disableLighting = true;
  23096. hdrSkyboxMaterial.twoSidedLighting = true;
  23097. hdrSkybox.infiniteDistance = true;
  23098. hdrSkybox.material = hdrSkyboxMaterial;
  23099. }
  23100. else {
  23101. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23102. skyboxMaterial.backFaceCulling = false;
  23103. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23104. if (skyboxMaterial.reflectionTexture) {
  23105. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23106. }
  23107. skyboxMaterial.disableLighting = true;
  23108. hdrSkybox.infiniteDistance = true;
  23109. hdrSkybox.material = skyboxMaterial;
  23110. }
  23111. return hdrSkybox;
  23112. };
  23113. Scene.prototype.createDefaultEnvironment = function (options) {
  23114. if (BABYLON.EnvironmentHelper) {
  23115. return new BABYLON.EnvironmentHelper(options, this);
  23116. }
  23117. return null;
  23118. };
  23119. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23120. if (webVROptions === void 0) { webVROptions = {}; }
  23121. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23122. };
  23123. // Tags
  23124. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23125. if (tagsQuery === undefined) {
  23126. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23127. return list;
  23128. }
  23129. var listByTags = [];
  23130. forEach = forEach || (function (item) { return; });
  23131. for (var i in list) {
  23132. var item = list[i];
  23133. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23134. listByTags.push(item);
  23135. forEach(item);
  23136. }
  23137. }
  23138. return listByTags;
  23139. };
  23140. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23141. return this._getByTags(this.meshes, tagsQuery, forEach);
  23142. };
  23143. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23144. return this._getByTags(this.cameras, tagsQuery, forEach);
  23145. };
  23146. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23147. return this._getByTags(this.lights, tagsQuery, forEach);
  23148. };
  23149. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23150. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23151. };
  23152. /**
  23153. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23154. * This allowed control for front to back rendering or reversly depending of the special needs.
  23155. *
  23156. * @param renderingGroupId The rendering group id corresponding to its index
  23157. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23158. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23159. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23160. */
  23161. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23162. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23163. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23164. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23165. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23166. };
  23167. /**
  23168. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23169. *
  23170. * @param renderingGroupId The rendering group id corresponding to its index
  23171. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23172. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23173. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23174. */
  23175. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23176. if (depth === void 0) { depth = true; }
  23177. if (stencil === void 0) { stencil = true; }
  23178. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23179. };
  23180. /**
  23181. * Will flag all materials as dirty to trigger new shader compilation
  23182. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23183. */
  23184. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23185. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23186. var material = _a[_i];
  23187. if (predicate && !predicate(material)) {
  23188. continue;
  23189. }
  23190. material.markAsDirty(flag);
  23191. }
  23192. };
  23193. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23194. var _this = this;
  23195. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23196. this._activeRequests.push(request);
  23197. request.onCompleteObservable.add(function (request) {
  23198. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23199. });
  23200. return request;
  23201. };
  23202. // Statics
  23203. Scene._FOGMODE_NONE = 0;
  23204. Scene._FOGMODE_EXP = 1;
  23205. Scene._FOGMODE_EXP2 = 2;
  23206. Scene._FOGMODE_LINEAR = 3;
  23207. Scene._uniqueIdCounter = 0;
  23208. Scene.MinDeltaTime = 1.0;
  23209. Scene.MaxDeltaTime = 1000.0;
  23210. /** The distance in pixel that you have to move to prevent some events */
  23211. Scene.DragMovementThreshold = 10; // in pixels
  23212. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23213. Scene.LongPressDelay = 500; // in milliseconds
  23214. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23215. Scene.DoubleClickDelay = 300; // in milliseconds
  23216. /** If you need to check double click without raising a single click at first click, enable this flag */
  23217. Scene.ExclusiveDoubleClickMode = false;
  23218. return Scene;
  23219. }());
  23220. BABYLON.Scene = Scene;
  23221. })(BABYLON || (BABYLON = {}));
  23222. //# sourceMappingURL=babylon.scene.js.map
  23223. var BABYLON;
  23224. (function (BABYLON) {
  23225. var AssetContainer = /** @class */ (function () {
  23226. function AssetContainer(scene) {
  23227. // Objects
  23228. this.cameras = new Array();
  23229. this.lights = new Array();
  23230. this.meshes = new Array();
  23231. this.skeletons = new Array();
  23232. this.particleSystems = new Array();
  23233. this.animations = new Array();
  23234. this.multiMaterials = new Array();
  23235. this.materials = new Array();
  23236. this.morphTargetManagers = new Array();
  23237. this.geometries = new Array();
  23238. this.transformNodes = new Array();
  23239. this.lensFlareSystems = new Array();
  23240. this.shadowGenerators = new Array();
  23241. this.actionManagers = new Array();
  23242. this.sounds = new Array();
  23243. this.scene = scene;
  23244. }
  23245. AssetContainer.prototype.addAllToScene = function () {
  23246. var _this = this;
  23247. this.cameras.forEach(function (o) {
  23248. _this.scene.addCamera(o);
  23249. });
  23250. this.lights.forEach(function (o) {
  23251. _this.scene.addLight(o);
  23252. });
  23253. this.meshes.forEach(function (o) {
  23254. _this.scene.addMesh(o);
  23255. });
  23256. this.skeletons.forEach(function (o) {
  23257. _this.scene.addSkeleton(o);
  23258. });
  23259. this.particleSystems.forEach(function (o) {
  23260. _this.scene.addParticleSystem(o);
  23261. });
  23262. this.animations.forEach(function (o) {
  23263. _this.scene.addAnimation(o);
  23264. });
  23265. this.multiMaterials.forEach(function (o) {
  23266. _this.scene.addMultiMaterial(o);
  23267. });
  23268. this.materials.forEach(function (o) {
  23269. _this.scene.addMaterial(o);
  23270. });
  23271. this.morphTargetManagers.forEach(function (o) {
  23272. _this.scene.addMorphTargetManager(o);
  23273. });
  23274. this.geometries.forEach(function (o) {
  23275. _this.scene.addGeometry(o);
  23276. });
  23277. this.transformNodes.forEach(function (o) {
  23278. _this.scene.addTransformNode(o);
  23279. });
  23280. this.lensFlareSystems.forEach(function (o) {
  23281. _this.scene.addLensFlareSystem(o);
  23282. });
  23283. this.actionManagers.forEach(function (o) {
  23284. _this.scene.addActionManager(o);
  23285. });
  23286. this.sounds.forEach(function (o) {
  23287. o.play();
  23288. o.autoplay = true;
  23289. _this.scene.mainSoundTrack.AddSound(o);
  23290. });
  23291. };
  23292. AssetContainer.prototype.removeAllFromScene = function () {
  23293. var _this = this;
  23294. this.cameras.forEach(function (o) {
  23295. _this.scene.removeCamera(o);
  23296. });
  23297. this.lights.forEach(function (o) {
  23298. _this.scene.removeLight(o);
  23299. });
  23300. this.meshes.forEach(function (o) {
  23301. _this.scene.removeMesh(o);
  23302. });
  23303. this.skeletons.forEach(function (o) {
  23304. _this.scene.removeSkeleton(o);
  23305. });
  23306. this.particleSystems.forEach(function (o) {
  23307. _this.scene.removeParticleSystem(o);
  23308. });
  23309. this.animations.forEach(function (o) {
  23310. _this.scene.removeAnimation(o);
  23311. });
  23312. this.multiMaterials.forEach(function (o) {
  23313. _this.scene.removeMultiMaterial(o);
  23314. });
  23315. this.materials.forEach(function (o) {
  23316. _this.scene.removeMaterial(o);
  23317. });
  23318. this.morphTargetManagers.forEach(function (o) {
  23319. _this.scene.removeMorphTargetManager(o);
  23320. });
  23321. this.geometries.forEach(function (o) {
  23322. _this.scene.removeGeometry(o);
  23323. });
  23324. this.transformNodes.forEach(function (o) {
  23325. _this.scene.removeTransformNode(o);
  23326. });
  23327. this.lensFlareSystems.forEach(function (o) {
  23328. _this.scene.removeLensFlareSystem(o);
  23329. });
  23330. this.actionManagers.forEach(function (o) {
  23331. _this.scene.removeActionManager(o);
  23332. });
  23333. this.sounds.forEach(function (o) {
  23334. o.stop();
  23335. o.autoplay = false;
  23336. _this.scene.mainSoundTrack.RemoveSound(o);
  23337. });
  23338. };
  23339. return AssetContainer;
  23340. }());
  23341. BABYLON.AssetContainer = AssetContainer;
  23342. })(BABYLON || (BABYLON = {}));
  23343. //# sourceMappingURL=babylon.assetContainer.js.map
  23344. var BABYLON;
  23345. (function (BABYLON) {
  23346. var Buffer = /** @class */ (function () {
  23347. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23348. if (instanced === void 0) { instanced = false; }
  23349. if (engine instanceof BABYLON.Mesh) {
  23350. this._engine = engine.getScene().getEngine();
  23351. }
  23352. else {
  23353. this._engine = engine;
  23354. }
  23355. this._updatable = updatable;
  23356. this._data = data;
  23357. this._strideSize = stride;
  23358. if (!postponeInternalCreation) {
  23359. this.create();
  23360. }
  23361. this._instanced = instanced;
  23362. this._instanceDivisor = instanced ? 1 : 0;
  23363. }
  23364. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23365. // a lot of these parameters are ignored as they are overriden by the buffer
  23366. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23367. };
  23368. // Properties
  23369. Buffer.prototype.isUpdatable = function () {
  23370. return this._updatable;
  23371. };
  23372. Buffer.prototype.getData = function () {
  23373. return this._data;
  23374. };
  23375. Buffer.prototype.getBuffer = function () {
  23376. return this._buffer;
  23377. };
  23378. Buffer.prototype.getStrideSize = function () {
  23379. return this._strideSize;
  23380. };
  23381. Buffer.prototype.getIsInstanced = function () {
  23382. return this._instanced;
  23383. };
  23384. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23385. get: function () {
  23386. return this._instanceDivisor;
  23387. },
  23388. set: function (value) {
  23389. this._instanceDivisor = value;
  23390. if (value == 0) {
  23391. this._instanced = false;
  23392. }
  23393. else {
  23394. this._instanced = true;
  23395. }
  23396. },
  23397. enumerable: true,
  23398. configurable: true
  23399. });
  23400. // Methods
  23401. Buffer.prototype.create = function (data) {
  23402. if (data === void 0) { data = null; }
  23403. if (!data && this._buffer) {
  23404. return; // nothing to do
  23405. }
  23406. data = data || this._data;
  23407. if (!data) {
  23408. return;
  23409. }
  23410. if (!this._buffer) {
  23411. if (this._updatable) {
  23412. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23413. this._data = data;
  23414. }
  23415. else {
  23416. this._buffer = this._engine.createVertexBuffer(data);
  23417. }
  23418. }
  23419. else if (this._updatable) {
  23420. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23421. this._data = data;
  23422. }
  23423. };
  23424. Buffer.prototype._rebuild = function () {
  23425. this._buffer = null;
  23426. this.create(this._data);
  23427. };
  23428. Buffer.prototype.update = function (data) {
  23429. this.create(data);
  23430. };
  23431. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23432. if (!this._buffer) {
  23433. return;
  23434. }
  23435. if (this._updatable) {
  23436. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23437. this._data = null;
  23438. }
  23439. };
  23440. Buffer.prototype.dispose = function () {
  23441. if (!this._buffer) {
  23442. return;
  23443. }
  23444. if (this._engine._releaseBuffer(this._buffer)) {
  23445. this._buffer = null;
  23446. }
  23447. };
  23448. return Buffer;
  23449. }());
  23450. BABYLON.Buffer = Buffer;
  23451. })(BABYLON || (BABYLON = {}));
  23452. //# sourceMappingURL=babylon.buffer.js.map
  23453. var BABYLON;
  23454. (function (BABYLON) {
  23455. var VertexBuffer = /** @class */ (function () {
  23456. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23457. if (!stride) {
  23458. // Deduce stride from kind
  23459. switch (kind) {
  23460. case VertexBuffer.PositionKind:
  23461. stride = 3;
  23462. break;
  23463. case VertexBuffer.NormalKind:
  23464. stride = 3;
  23465. break;
  23466. case VertexBuffer.UVKind:
  23467. case VertexBuffer.UV2Kind:
  23468. case VertexBuffer.UV3Kind:
  23469. case VertexBuffer.UV4Kind:
  23470. case VertexBuffer.UV5Kind:
  23471. case VertexBuffer.UV6Kind:
  23472. stride = 2;
  23473. break;
  23474. case VertexBuffer.TangentKind:
  23475. case VertexBuffer.ColorKind:
  23476. stride = 4;
  23477. break;
  23478. case VertexBuffer.MatricesIndicesKind:
  23479. case VertexBuffer.MatricesIndicesExtraKind:
  23480. stride = 4;
  23481. break;
  23482. case VertexBuffer.MatricesWeightsKind:
  23483. case VertexBuffer.MatricesWeightsExtraKind:
  23484. default:
  23485. stride = 4;
  23486. break;
  23487. }
  23488. }
  23489. if (data instanceof BABYLON.Buffer) {
  23490. if (!stride) {
  23491. stride = data.getStrideSize();
  23492. }
  23493. this._buffer = data;
  23494. this._ownsBuffer = false;
  23495. }
  23496. else {
  23497. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23498. this._ownsBuffer = true;
  23499. }
  23500. this._stride = stride;
  23501. this._offset = offset ? offset : 0;
  23502. this._size = size ? size : stride;
  23503. this._kind = kind;
  23504. }
  23505. VertexBuffer.prototype._rebuild = function () {
  23506. if (!this._buffer) {
  23507. return;
  23508. }
  23509. this._buffer._rebuild();
  23510. };
  23511. /**
  23512. * Returns the kind of the VertexBuffer (string).
  23513. */
  23514. VertexBuffer.prototype.getKind = function () {
  23515. return this._kind;
  23516. };
  23517. // Properties
  23518. /**
  23519. * Boolean : is the VertexBuffer updatable ?
  23520. */
  23521. VertexBuffer.prototype.isUpdatable = function () {
  23522. return this._buffer.isUpdatable();
  23523. };
  23524. /**
  23525. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23526. */
  23527. VertexBuffer.prototype.getData = function () {
  23528. return this._buffer.getData();
  23529. };
  23530. /**
  23531. * Returns the WebGLBuffer associated to the VertexBuffer.
  23532. */
  23533. VertexBuffer.prototype.getBuffer = function () {
  23534. return this._buffer.getBuffer();
  23535. };
  23536. /**
  23537. * Returns the stride of the VertexBuffer (integer).
  23538. */
  23539. VertexBuffer.prototype.getStrideSize = function () {
  23540. return this._stride;
  23541. };
  23542. /**
  23543. * Returns the offset (integer).
  23544. */
  23545. VertexBuffer.prototype.getOffset = function () {
  23546. return this._offset;
  23547. };
  23548. /**
  23549. * Returns the VertexBuffer total size (integer).
  23550. */
  23551. VertexBuffer.prototype.getSize = function () {
  23552. return this._size;
  23553. };
  23554. /**
  23555. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23556. */
  23557. VertexBuffer.prototype.getIsInstanced = function () {
  23558. return this._buffer.getIsInstanced();
  23559. };
  23560. /**
  23561. * Returns the instancing divisor, zero for non-instanced (integer).
  23562. */
  23563. VertexBuffer.prototype.getInstanceDivisor = function () {
  23564. return this._buffer.instanceDivisor;
  23565. };
  23566. // Methods
  23567. /**
  23568. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23569. * Returns the created WebGLBuffer.
  23570. */
  23571. VertexBuffer.prototype.create = function (data) {
  23572. return this._buffer.create(data);
  23573. };
  23574. /**
  23575. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23576. * Returns the updated WebGLBuffer.
  23577. */
  23578. VertexBuffer.prototype.update = function (data) {
  23579. return this._buffer.update(data);
  23580. };
  23581. /**
  23582. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23583. * Returns the directly updated WebGLBuffer.
  23584. */
  23585. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23586. return this._buffer.updateDirectly(data, offset);
  23587. };
  23588. /**
  23589. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23590. */
  23591. VertexBuffer.prototype.dispose = function () {
  23592. if (this._ownsBuffer) {
  23593. this._buffer.dispose();
  23594. }
  23595. };
  23596. Object.defineProperty(VertexBuffer, "PositionKind", {
  23597. get: function () {
  23598. return VertexBuffer._PositionKind;
  23599. },
  23600. enumerable: true,
  23601. configurable: true
  23602. });
  23603. Object.defineProperty(VertexBuffer, "NormalKind", {
  23604. get: function () {
  23605. return VertexBuffer._NormalKind;
  23606. },
  23607. enumerable: true,
  23608. configurable: true
  23609. });
  23610. Object.defineProperty(VertexBuffer, "TangentKind", {
  23611. get: function () {
  23612. return VertexBuffer._TangentKind;
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. Object.defineProperty(VertexBuffer, "UVKind", {
  23618. get: function () {
  23619. return VertexBuffer._UVKind;
  23620. },
  23621. enumerable: true,
  23622. configurable: true
  23623. });
  23624. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23625. get: function () {
  23626. return VertexBuffer._UV2Kind;
  23627. },
  23628. enumerable: true,
  23629. configurable: true
  23630. });
  23631. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23632. get: function () {
  23633. return VertexBuffer._UV3Kind;
  23634. },
  23635. enumerable: true,
  23636. configurable: true
  23637. });
  23638. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23639. get: function () {
  23640. return VertexBuffer._UV4Kind;
  23641. },
  23642. enumerable: true,
  23643. configurable: true
  23644. });
  23645. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23646. get: function () {
  23647. return VertexBuffer._UV5Kind;
  23648. },
  23649. enumerable: true,
  23650. configurable: true
  23651. });
  23652. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23653. get: function () {
  23654. return VertexBuffer._UV6Kind;
  23655. },
  23656. enumerable: true,
  23657. configurable: true
  23658. });
  23659. Object.defineProperty(VertexBuffer, "ColorKind", {
  23660. get: function () {
  23661. return VertexBuffer._ColorKind;
  23662. },
  23663. enumerable: true,
  23664. configurable: true
  23665. });
  23666. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23667. get: function () {
  23668. return VertexBuffer._MatricesIndicesKind;
  23669. },
  23670. enumerable: true,
  23671. configurable: true
  23672. });
  23673. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23674. get: function () {
  23675. return VertexBuffer._MatricesWeightsKind;
  23676. },
  23677. enumerable: true,
  23678. configurable: true
  23679. });
  23680. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23681. get: function () {
  23682. return VertexBuffer._MatricesIndicesExtraKind;
  23683. },
  23684. enumerable: true,
  23685. configurable: true
  23686. });
  23687. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23688. get: function () {
  23689. return VertexBuffer._MatricesWeightsExtraKind;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. // Enums
  23695. VertexBuffer._PositionKind = "position";
  23696. VertexBuffer._NormalKind = "normal";
  23697. VertexBuffer._TangentKind = "tangent";
  23698. VertexBuffer._UVKind = "uv";
  23699. VertexBuffer._UV2Kind = "uv2";
  23700. VertexBuffer._UV3Kind = "uv3";
  23701. VertexBuffer._UV4Kind = "uv4";
  23702. VertexBuffer._UV5Kind = "uv5";
  23703. VertexBuffer._UV6Kind = "uv6";
  23704. VertexBuffer._ColorKind = "color";
  23705. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23706. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23707. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23708. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23709. return VertexBuffer;
  23710. }());
  23711. BABYLON.VertexBuffer = VertexBuffer;
  23712. })(BABYLON || (BABYLON = {}));
  23713. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23714. var BABYLON;
  23715. (function (BABYLON) {
  23716. /**
  23717. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  23718. */
  23719. var DummyInternalTextureTracker = /** @class */ (function () {
  23720. function DummyInternalTextureTracker() {
  23721. /**
  23722. * Gets or set the previous tracker in the list
  23723. */
  23724. this.previous = null;
  23725. /**
  23726. * Gets or set the next tracker in the list
  23727. */
  23728. this.next = null;
  23729. }
  23730. return DummyInternalTextureTracker;
  23731. }());
  23732. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  23733. })(BABYLON || (BABYLON = {}));
  23734. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  23735. var BABYLON;
  23736. (function (BABYLON) {
  23737. /**
  23738. * Class used to store data associated with WebGL texture data for the engine
  23739. * This class should not be used directly
  23740. */
  23741. var InternalTexture = /** @class */ (function () {
  23742. /**
  23743. * Creates a new InternalTexture
  23744. * @param engine defines the engine to use
  23745. * @param dataSource defines the type of data that will be used
  23746. */
  23747. function InternalTexture(engine, dataSource) {
  23748. /**
  23749. * Observable called when the texture is loaded
  23750. */
  23751. this.onLoadedObservable = new BABYLON.Observable();
  23752. /**
  23753. * Gets or set the previous tracker in the list
  23754. */
  23755. this.previous = null;
  23756. /**
  23757. * Gets or set the next tracker in the list
  23758. */
  23759. this.next = null;
  23760. // Private
  23761. /** @ignore */
  23762. this._initialSlot = -1;
  23763. /** @ignore */
  23764. this._designatedSlot = -1;
  23765. /** @ignore */
  23766. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23767. /** @ignore */
  23768. this._references = 1;
  23769. this._engine = engine;
  23770. this._dataSource = dataSource;
  23771. this._webGLTexture = engine._createTexture();
  23772. }
  23773. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23774. /**
  23775. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  23776. */
  23777. get: function () {
  23778. return this._dataSource;
  23779. },
  23780. enumerable: true,
  23781. configurable: true
  23782. });
  23783. /**
  23784. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  23785. */
  23786. InternalTexture.prototype.incrementReferences = function () {
  23787. this._references++;
  23788. };
  23789. /**
  23790. * Change the size of the texture (not the size of the content)
  23791. * @param width defines the new width
  23792. * @param height defines the new height
  23793. * @param depth defines the new depth (1 by default)
  23794. */
  23795. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23796. if (depth === void 0) { depth = 1; }
  23797. this.width = width;
  23798. this.height = height;
  23799. this.depth = depth;
  23800. this.baseWidth = width;
  23801. this.baseHeight = height;
  23802. this.baseDepth = depth;
  23803. this._size = width * height * depth;
  23804. };
  23805. /** @ignore */
  23806. InternalTexture.prototype._rebuild = function () {
  23807. var _this = this;
  23808. var proxy;
  23809. this.isReady = false;
  23810. this._cachedCoordinatesMode = null;
  23811. this._cachedWrapU = null;
  23812. this._cachedWrapV = null;
  23813. this._cachedAnisotropicFilteringLevel = null;
  23814. switch (this._dataSource) {
  23815. case InternalTexture.DATASOURCE_TEMP:
  23816. return;
  23817. case InternalTexture.DATASOURCE_URL:
  23818. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23819. _this.isReady = true;
  23820. }, null, this._buffer, undefined, this.format);
  23821. proxy._swapAndDie(this);
  23822. return;
  23823. case InternalTexture.DATASOURCE_RAW:
  23824. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23825. proxy._swapAndDie(this);
  23826. this.isReady = true;
  23827. return;
  23828. case InternalTexture.DATASOURCE_RAW3D:
  23829. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23830. proxy._swapAndDie(this);
  23831. this.isReady = true;
  23832. return;
  23833. case InternalTexture.DATASOURCE_DYNAMIC:
  23834. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23835. proxy._swapAndDie(this);
  23836. // The engine will make sure to update content so no need to flag it as isReady = true
  23837. return;
  23838. case InternalTexture.DATASOURCE_RENDERTARGET:
  23839. var options = new BABYLON.RenderTargetCreationOptions();
  23840. options.generateDepthBuffer = this._generateDepthBuffer;
  23841. options.generateMipMaps = this.generateMipMaps;
  23842. options.generateStencilBuffer = this._generateStencilBuffer;
  23843. options.samplingMode = this.samplingMode;
  23844. options.type = this.type;
  23845. if (this.isCube) {
  23846. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23847. }
  23848. else {
  23849. var size = {
  23850. width: this.width,
  23851. height: this.height
  23852. };
  23853. proxy = this._engine.createRenderTargetTexture(size, options);
  23854. }
  23855. proxy._swapAndDie(this);
  23856. this.isReady = true;
  23857. return;
  23858. case InternalTexture.DATASOURCE_CUBE:
  23859. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23860. _this.isReady = true;
  23861. }, null, this.format, this._extension);
  23862. proxy._swapAndDie(this);
  23863. return;
  23864. case InternalTexture.DATASOURCE_CUBERAW:
  23865. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23866. proxy._swapAndDie(this);
  23867. this.isReady = true;
  23868. return;
  23869. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23870. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23871. if (proxy) {
  23872. proxy._swapAndDie(_this);
  23873. }
  23874. _this.isReady = true;
  23875. }, null, this.format, this._extension);
  23876. return;
  23877. }
  23878. };
  23879. InternalTexture.prototype._swapAndDie = function (target) {
  23880. target._webGLTexture = this._webGLTexture;
  23881. if (this._framebuffer) {
  23882. target._framebuffer = this._framebuffer;
  23883. }
  23884. if (this._depthStencilBuffer) {
  23885. target._depthStencilBuffer = this._depthStencilBuffer;
  23886. }
  23887. if (this._lodTextureHigh) {
  23888. if (target._lodTextureHigh) {
  23889. target._lodTextureHigh.dispose();
  23890. }
  23891. target._lodTextureHigh = this._lodTextureHigh;
  23892. }
  23893. if (this._lodTextureMid) {
  23894. if (target._lodTextureMid) {
  23895. target._lodTextureMid.dispose();
  23896. }
  23897. target._lodTextureMid = this._lodTextureMid;
  23898. }
  23899. if (this._lodTextureLow) {
  23900. if (target._lodTextureLow) {
  23901. target._lodTextureLow.dispose();
  23902. }
  23903. target._lodTextureLow = this._lodTextureLow;
  23904. }
  23905. var cache = this._engine.getLoadedTexturesCache();
  23906. var index = cache.indexOf(this);
  23907. if (index !== -1) {
  23908. cache.splice(index, 1);
  23909. }
  23910. };
  23911. /**
  23912. * Dispose the current allocated resources
  23913. */
  23914. InternalTexture.prototype.dispose = function () {
  23915. if (!this._webGLTexture) {
  23916. return;
  23917. }
  23918. this._references--;
  23919. if (this._references === 0) {
  23920. this._engine._releaseTexture(this);
  23921. this._webGLTexture = null;
  23922. }
  23923. };
  23924. /**
  23925. * The source of the texture data is unknown
  23926. */
  23927. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23928. /**
  23929. * Texture data comes from an URL
  23930. */
  23931. InternalTexture.DATASOURCE_URL = 1;
  23932. /**
  23933. * Texture data is only used for temporary storage
  23934. */
  23935. InternalTexture.DATASOURCE_TEMP = 2;
  23936. /**
  23937. * Texture data comes from raw data (ArrayBuffer)
  23938. */
  23939. InternalTexture.DATASOURCE_RAW = 3;
  23940. /**
  23941. * Texture content is dynamic (video or dynamic texture)
  23942. */
  23943. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23944. /**
  23945. * Texture content is generated by rendering to it
  23946. */
  23947. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23948. /**
  23949. * Texture content is part of a multi render target process
  23950. */
  23951. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23952. /**
  23953. * Texture data comes from a cube data file
  23954. */
  23955. InternalTexture.DATASOURCE_CUBE = 7;
  23956. /**
  23957. * Texture data comes from a raw cube data
  23958. */
  23959. InternalTexture.DATASOURCE_CUBERAW = 8;
  23960. /**
  23961. * Texture data come from a prefiltered cube data file
  23962. */
  23963. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23964. /**
  23965. * Texture content is raw 3D data
  23966. */
  23967. InternalTexture.DATASOURCE_RAW3D = 10;
  23968. return InternalTexture;
  23969. }());
  23970. BABYLON.InternalTexture = InternalTexture;
  23971. })(BABYLON || (BABYLON = {}));
  23972. //# sourceMappingURL=babylon.internalTexture.js.map
  23973. var BABYLON;
  23974. (function (BABYLON) {
  23975. var BaseTexture = /** @class */ (function () {
  23976. function BaseTexture(scene) {
  23977. this._hasAlpha = false;
  23978. this.getAlphaFromRGB = false;
  23979. this.level = 1;
  23980. this.coordinatesIndex = 0;
  23981. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23982. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23983. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23984. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23985. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23986. this.isCube = false;
  23987. this.is3D = false;
  23988. this.gammaSpace = true;
  23989. this.invertZ = false;
  23990. this.lodLevelInAlpha = false;
  23991. this.lodGenerationOffset = 0.0;
  23992. this.lodGenerationScale = 0.8;
  23993. this.isRenderTarget = false;
  23994. this.animations = new Array();
  23995. /**
  23996. * An event triggered when the texture is disposed.
  23997. * @type {BABYLON.Observable}
  23998. */
  23999. this.onDisposeObservable = new BABYLON.Observable();
  24000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24001. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24002. if (this._scene) {
  24003. this._scene.textures.push(this);
  24004. }
  24005. this._uid = null;
  24006. }
  24007. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24008. get: function () {
  24009. return this._hasAlpha;
  24010. },
  24011. set: function (value) {
  24012. if (this._hasAlpha === value) {
  24013. return;
  24014. }
  24015. this._hasAlpha = value;
  24016. if (this._scene) {
  24017. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24018. }
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24024. get: function () {
  24025. return this._coordinatesMode;
  24026. },
  24027. set: function (value) {
  24028. if (this._coordinatesMode === value) {
  24029. return;
  24030. }
  24031. this._coordinatesMode = value;
  24032. if (this._scene) {
  24033. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24034. }
  24035. },
  24036. enumerable: true,
  24037. configurable: true
  24038. });
  24039. Object.defineProperty(BaseTexture.prototype, "uid", {
  24040. get: function () {
  24041. if (!this._uid) {
  24042. this._uid = BABYLON.Tools.RandomId();
  24043. }
  24044. return this._uid;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. BaseTexture.prototype.toString = function () {
  24050. return this.name;
  24051. };
  24052. BaseTexture.prototype.getClassName = function () {
  24053. return "BaseTexture";
  24054. };
  24055. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24056. set: function (callback) {
  24057. if (this._onDisposeObserver) {
  24058. this.onDisposeObservable.remove(this._onDisposeObserver);
  24059. }
  24060. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24066. get: function () {
  24067. return true;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. BaseTexture.prototype.getScene = function () {
  24073. return this._scene;
  24074. };
  24075. BaseTexture.prototype.getTextureMatrix = function () {
  24076. return BABYLON.Matrix.IdentityReadOnly;
  24077. };
  24078. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24079. return BABYLON.Matrix.IdentityReadOnly;
  24080. };
  24081. BaseTexture.prototype.getInternalTexture = function () {
  24082. return this._texture;
  24083. };
  24084. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24085. return !this.isBlocking || this.isReady();
  24086. };
  24087. BaseTexture.prototype.isReady = function () {
  24088. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24089. this.delayLoad();
  24090. return false;
  24091. }
  24092. if (this._texture) {
  24093. return this._texture.isReady;
  24094. }
  24095. return false;
  24096. };
  24097. BaseTexture.prototype.getSize = function () {
  24098. if (this._texture && this._texture.width) {
  24099. return new BABYLON.Size(this._texture.width, this._texture.height);
  24100. }
  24101. if (this._texture && this._texture._size) {
  24102. return new BABYLON.Size(this._texture._size, this._texture._size);
  24103. }
  24104. return BABYLON.Size.Zero();
  24105. };
  24106. BaseTexture.prototype.getBaseSize = function () {
  24107. if (!this.isReady() || !this._texture)
  24108. return BABYLON.Size.Zero();
  24109. if (this._texture._size) {
  24110. return new BABYLON.Size(this._texture._size, this._texture._size);
  24111. }
  24112. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24113. };
  24114. BaseTexture.prototype.scale = function (ratio) {
  24115. };
  24116. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24117. get: function () {
  24118. return false;
  24119. },
  24120. enumerable: true,
  24121. configurable: true
  24122. });
  24123. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24124. if (!this._scene) {
  24125. return null;
  24126. }
  24127. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24128. for (var index = 0; index < texturesCache.length; index++) {
  24129. var texturesCacheEntry = texturesCache[index];
  24130. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24131. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24132. texturesCacheEntry.incrementReferences();
  24133. return texturesCacheEntry;
  24134. }
  24135. }
  24136. }
  24137. return null;
  24138. };
  24139. BaseTexture.prototype._rebuild = function () {
  24140. };
  24141. BaseTexture.prototype.delayLoad = function () {
  24142. };
  24143. BaseTexture.prototype.clone = function () {
  24144. return null;
  24145. };
  24146. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24147. get: function () {
  24148. if (!this._texture) {
  24149. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24150. }
  24151. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24152. },
  24153. enumerable: true,
  24154. configurable: true
  24155. });
  24156. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24157. get: function () {
  24158. if (!this._texture) {
  24159. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24160. }
  24161. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. BaseTexture.prototype.readPixels = function (faceIndex) {
  24167. if (faceIndex === void 0) { faceIndex = 0; }
  24168. if (!this._texture) {
  24169. return null;
  24170. }
  24171. var size = this.getSize();
  24172. var scene = this.getScene();
  24173. if (!scene) {
  24174. return null;
  24175. }
  24176. var engine = scene.getEngine();
  24177. if (this._texture.isCube) {
  24178. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24179. }
  24180. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24181. };
  24182. BaseTexture.prototype.releaseInternalTexture = function () {
  24183. if (this._texture) {
  24184. this._texture.dispose();
  24185. this._texture = null;
  24186. }
  24187. };
  24188. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24189. get: function () {
  24190. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24191. return null;
  24192. }
  24193. if (!this._texture._sphericalPolynomial) {
  24194. this._texture._sphericalPolynomial =
  24195. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24196. }
  24197. return this._texture._sphericalPolynomial;
  24198. },
  24199. set: function (value) {
  24200. if (this._texture) {
  24201. this._texture._sphericalPolynomial = value;
  24202. }
  24203. },
  24204. enumerable: true,
  24205. configurable: true
  24206. });
  24207. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24208. get: function () {
  24209. if (this._texture) {
  24210. return this._texture._lodTextureHigh;
  24211. }
  24212. return null;
  24213. },
  24214. enumerable: true,
  24215. configurable: true
  24216. });
  24217. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24218. get: function () {
  24219. if (this._texture) {
  24220. return this._texture._lodTextureMid;
  24221. }
  24222. return null;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24228. get: function () {
  24229. if (this._texture) {
  24230. return this._texture._lodTextureLow;
  24231. }
  24232. return null;
  24233. },
  24234. enumerable: true,
  24235. configurable: true
  24236. });
  24237. BaseTexture.prototype.dispose = function () {
  24238. if (!this._scene) {
  24239. return;
  24240. }
  24241. // Animations
  24242. this._scene.stopAnimation(this);
  24243. // Remove from scene
  24244. this._scene._removePendingData(this);
  24245. var index = this._scene.textures.indexOf(this);
  24246. if (index >= 0) {
  24247. this._scene.textures.splice(index, 1);
  24248. }
  24249. if (this._texture === undefined) {
  24250. return;
  24251. }
  24252. // Release
  24253. this.releaseInternalTexture();
  24254. // Callback
  24255. this.onDisposeObservable.notifyObservers(this);
  24256. this.onDisposeObservable.clear();
  24257. };
  24258. BaseTexture.prototype.serialize = function () {
  24259. if (!this.name) {
  24260. return null;
  24261. }
  24262. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24263. // Animations
  24264. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24265. return serializationObject;
  24266. };
  24267. BaseTexture.WhenAllReady = function (textures, callback) {
  24268. var numRemaining = textures.length;
  24269. if (numRemaining === 0) {
  24270. callback();
  24271. return;
  24272. }
  24273. var _loop_1 = function () {
  24274. texture = textures[i];
  24275. if (texture.isReady()) {
  24276. if (--numRemaining === 0) {
  24277. callback();
  24278. }
  24279. }
  24280. else {
  24281. onLoadObservable = texture.onLoadObservable;
  24282. var onLoadCallback_1 = function () {
  24283. onLoadObservable.removeCallback(onLoadCallback_1);
  24284. if (--numRemaining === 0) {
  24285. callback();
  24286. }
  24287. };
  24288. onLoadObservable.add(onLoadCallback_1);
  24289. }
  24290. };
  24291. var texture, onLoadObservable;
  24292. for (var i = 0; i < textures.length; i++) {
  24293. _loop_1();
  24294. }
  24295. };
  24296. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24297. __decorate([
  24298. BABYLON.serialize()
  24299. ], BaseTexture.prototype, "name", void 0);
  24300. __decorate([
  24301. BABYLON.serialize("hasAlpha")
  24302. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24303. __decorate([
  24304. BABYLON.serialize()
  24305. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24306. __decorate([
  24307. BABYLON.serialize()
  24308. ], BaseTexture.prototype, "level", void 0);
  24309. __decorate([
  24310. BABYLON.serialize()
  24311. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24312. __decorate([
  24313. BABYLON.serialize("coordinatesMode")
  24314. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24315. __decorate([
  24316. BABYLON.serialize()
  24317. ], BaseTexture.prototype, "wrapU", void 0);
  24318. __decorate([
  24319. BABYLON.serialize()
  24320. ], BaseTexture.prototype, "wrapV", void 0);
  24321. __decorate([
  24322. BABYLON.serialize()
  24323. ], BaseTexture.prototype, "wrapR", void 0);
  24324. __decorate([
  24325. BABYLON.serialize()
  24326. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24327. __decorate([
  24328. BABYLON.serialize()
  24329. ], BaseTexture.prototype, "isCube", void 0);
  24330. __decorate([
  24331. BABYLON.serialize()
  24332. ], BaseTexture.prototype, "is3D", void 0);
  24333. __decorate([
  24334. BABYLON.serialize()
  24335. ], BaseTexture.prototype, "gammaSpace", void 0);
  24336. __decorate([
  24337. BABYLON.serialize()
  24338. ], BaseTexture.prototype, "invertZ", void 0);
  24339. __decorate([
  24340. BABYLON.serialize()
  24341. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24342. __decorate([
  24343. BABYLON.serialize()
  24344. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24345. __decorate([
  24346. BABYLON.serialize()
  24347. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24348. __decorate([
  24349. BABYLON.serialize()
  24350. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24351. return BaseTexture;
  24352. }());
  24353. BABYLON.BaseTexture = BaseTexture;
  24354. })(BABYLON || (BABYLON = {}));
  24355. //# sourceMappingURL=babylon.baseTexture.js.map
  24356. var BABYLON;
  24357. (function (BABYLON) {
  24358. var Texture = /** @class */ (function (_super) {
  24359. __extends(Texture, _super);
  24360. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24361. if (noMipmap === void 0) { noMipmap = false; }
  24362. if (invertY === void 0) { invertY = true; }
  24363. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24364. if (onLoad === void 0) { onLoad = null; }
  24365. if (onError === void 0) { onError = null; }
  24366. if (buffer === void 0) { buffer = null; }
  24367. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24368. var _this = _super.call(this, scene) || this;
  24369. _this.uOffset = 0;
  24370. _this.vOffset = 0;
  24371. _this.uScale = 1.0;
  24372. _this.vScale = 1.0;
  24373. _this.uAng = 0;
  24374. _this.vAng = 0;
  24375. _this.wAng = 0;
  24376. _this._isBlocking = true;
  24377. _this.name = url || "";
  24378. _this.url = url;
  24379. _this._noMipmap = noMipmap;
  24380. _this._invertY = invertY;
  24381. _this._samplingMode = samplingMode;
  24382. _this._buffer = buffer;
  24383. _this._deleteBuffer = deleteBuffer;
  24384. if (format) {
  24385. _this._format = format;
  24386. }
  24387. scene = _this.getScene();
  24388. if (!scene) {
  24389. return _this;
  24390. }
  24391. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24392. var load = function () {
  24393. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24394. _this.onLoadObservable.notifyObservers(_this);
  24395. }
  24396. if (onLoad) {
  24397. onLoad();
  24398. }
  24399. if (!_this.isBlocking && scene) {
  24400. scene.resetCachedMaterial();
  24401. }
  24402. };
  24403. if (!_this.url) {
  24404. _this._delayedOnLoad = load;
  24405. _this._delayedOnError = onError;
  24406. return _this;
  24407. }
  24408. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24409. if (!_this._texture) {
  24410. if (!scene.useDelayedTextureLoading) {
  24411. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24412. if (deleteBuffer) {
  24413. delete _this._buffer;
  24414. }
  24415. }
  24416. else {
  24417. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24418. _this._delayedOnLoad = load;
  24419. _this._delayedOnError = onError;
  24420. }
  24421. }
  24422. else {
  24423. if (_this._texture.isReady) {
  24424. BABYLON.Tools.SetImmediate(function () { return load(); });
  24425. }
  24426. else {
  24427. _this._texture.onLoadedObservable.add(load);
  24428. }
  24429. }
  24430. return _this;
  24431. }
  24432. Object.defineProperty(Texture.prototype, "noMipmap", {
  24433. get: function () {
  24434. return this._noMipmap;
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Object.defineProperty(Texture.prototype, "isBlocking", {
  24440. get: function () {
  24441. return this._isBlocking;
  24442. },
  24443. set: function (value) {
  24444. this._isBlocking = value;
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Texture.prototype, "samplingMode", {
  24450. get: function () {
  24451. return this._samplingMode;
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. Texture.prototype.updateURL = function (url) {
  24457. this.url = url;
  24458. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24459. this.delayLoad();
  24460. };
  24461. Texture.prototype.delayLoad = function () {
  24462. var _this = this;
  24463. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24464. return;
  24465. }
  24466. var scene = this.getScene();
  24467. if (!scene) {
  24468. return;
  24469. }
  24470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24471. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24472. if (!this._texture) {
  24473. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24474. if (this._deleteBuffer) {
  24475. delete this._buffer;
  24476. }
  24477. }
  24478. else {
  24479. if (this._texture.isReady) {
  24480. BABYLON.Tools.SetImmediate(function () {
  24481. if (!_this._delayedOnLoad) {
  24482. return;
  24483. }
  24484. _this._delayedOnLoad();
  24485. });
  24486. }
  24487. else {
  24488. if (this._delayedOnLoad) {
  24489. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24490. }
  24491. }
  24492. }
  24493. };
  24494. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24495. if (!this._texture) {
  24496. return;
  24497. }
  24498. var scene = this.getScene();
  24499. if (!scene) {
  24500. return;
  24501. }
  24502. this._samplingMode = samplingMode;
  24503. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24504. };
  24505. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24506. x *= this.uScale;
  24507. y *= this.vScale;
  24508. x -= 0.5 * this.uScale;
  24509. y -= 0.5 * this.vScale;
  24510. z -= 0.5;
  24511. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24512. t.x += 0.5 * this.uScale + this.uOffset;
  24513. t.y += 0.5 * this.vScale + this.vOffset;
  24514. t.z += 0.5;
  24515. };
  24516. Texture.prototype.getTextureMatrix = function () {
  24517. var _this = this;
  24518. if (this.uOffset === this._cachedUOffset &&
  24519. this.vOffset === this._cachedVOffset &&
  24520. this.uScale === this._cachedUScale &&
  24521. this.vScale === this._cachedVScale &&
  24522. this.uAng === this._cachedUAng &&
  24523. this.vAng === this._cachedVAng &&
  24524. this.wAng === this._cachedWAng) {
  24525. return this._cachedTextureMatrix;
  24526. }
  24527. this._cachedUOffset = this.uOffset;
  24528. this._cachedVOffset = this.vOffset;
  24529. this._cachedUScale = this.uScale;
  24530. this._cachedVScale = this.vScale;
  24531. this._cachedUAng = this.uAng;
  24532. this._cachedVAng = this.vAng;
  24533. this._cachedWAng = this.wAng;
  24534. if (!this._cachedTextureMatrix) {
  24535. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24536. this._rowGenerationMatrix = new BABYLON.Matrix();
  24537. this._t0 = BABYLON.Vector3.Zero();
  24538. this._t1 = BABYLON.Vector3.Zero();
  24539. this._t2 = BABYLON.Vector3.Zero();
  24540. }
  24541. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24542. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24543. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24544. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24545. this._t1.subtractInPlace(this._t0);
  24546. this._t2.subtractInPlace(this._t0);
  24547. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24548. this._cachedTextureMatrix.m[0] = this._t1.x;
  24549. this._cachedTextureMatrix.m[1] = this._t1.y;
  24550. this._cachedTextureMatrix.m[2] = this._t1.z;
  24551. this._cachedTextureMatrix.m[4] = this._t2.x;
  24552. this._cachedTextureMatrix.m[5] = this._t2.y;
  24553. this._cachedTextureMatrix.m[6] = this._t2.z;
  24554. this._cachedTextureMatrix.m[8] = this._t0.x;
  24555. this._cachedTextureMatrix.m[9] = this._t0.y;
  24556. this._cachedTextureMatrix.m[10] = this._t0.z;
  24557. var scene = this.getScene();
  24558. if (!scene) {
  24559. return this._cachedTextureMatrix;
  24560. }
  24561. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24562. return mat.hasTexture(_this);
  24563. });
  24564. return this._cachedTextureMatrix;
  24565. };
  24566. Texture.prototype.getReflectionTextureMatrix = function () {
  24567. var _this = this;
  24568. var scene = this.getScene();
  24569. if (!scene) {
  24570. return this._cachedTextureMatrix;
  24571. }
  24572. if (this.uOffset === this._cachedUOffset &&
  24573. this.vOffset === this._cachedVOffset &&
  24574. this.uScale === this._cachedUScale &&
  24575. this.vScale === this._cachedVScale &&
  24576. this.coordinatesMode === this._cachedCoordinatesMode) {
  24577. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24578. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24579. return this._cachedTextureMatrix;
  24580. }
  24581. }
  24582. else {
  24583. return this._cachedTextureMatrix;
  24584. }
  24585. }
  24586. if (!this._cachedTextureMatrix) {
  24587. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24588. }
  24589. if (!this._projectionModeMatrix) {
  24590. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24591. }
  24592. this._cachedUOffset = this.uOffset;
  24593. this._cachedVOffset = this.vOffset;
  24594. this._cachedUScale = this.uScale;
  24595. this._cachedVScale = this.vScale;
  24596. this._cachedCoordinatesMode = this.coordinatesMode;
  24597. switch (this.coordinatesMode) {
  24598. case Texture.PLANAR_MODE:
  24599. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24600. this._cachedTextureMatrix[0] = this.uScale;
  24601. this._cachedTextureMatrix[5] = this.vScale;
  24602. this._cachedTextureMatrix[12] = this.uOffset;
  24603. this._cachedTextureMatrix[13] = this.vOffset;
  24604. break;
  24605. case Texture.PROJECTION_MODE:
  24606. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24607. this._projectionModeMatrix.m[0] = 0.5;
  24608. this._projectionModeMatrix.m[5] = -0.5;
  24609. this._projectionModeMatrix.m[10] = 0.0;
  24610. this._projectionModeMatrix.m[12] = 0.5;
  24611. this._projectionModeMatrix.m[13] = 0.5;
  24612. this._projectionModeMatrix.m[14] = 1.0;
  24613. this._projectionModeMatrix.m[15] = 1.0;
  24614. var projectionMatrix = scene.getProjectionMatrix();
  24615. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24616. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24617. break;
  24618. default:
  24619. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24620. break;
  24621. }
  24622. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24623. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24624. });
  24625. return this._cachedTextureMatrix;
  24626. };
  24627. Texture.prototype.clone = function () {
  24628. var _this = this;
  24629. return BABYLON.SerializationHelper.Clone(function () {
  24630. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24631. }, this);
  24632. };
  24633. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24634. get: function () {
  24635. if (!this._onLoadObservable) {
  24636. this._onLoadObservable = new BABYLON.Observable();
  24637. }
  24638. return this._onLoadObservable;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Texture.prototype.serialize = function () {
  24644. var serializationObject = _super.prototype.serialize.call(this);
  24645. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24646. serializationObject.base64String = this._buffer;
  24647. serializationObject.name = serializationObject.name.replace("data:", "");
  24648. }
  24649. return serializationObject;
  24650. };
  24651. Texture.prototype.getClassName = function () {
  24652. return "Texture";
  24653. };
  24654. Texture.prototype.dispose = function () {
  24655. _super.prototype.dispose.call(this);
  24656. if (this.onLoadObservable) {
  24657. this.onLoadObservable.clear();
  24658. this._onLoadObservable = null;
  24659. }
  24660. this._delayedOnLoad = null;
  24661. this._delayedOnError = null;
  24662. };
  24663. // Statics
  24664. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24665. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24666. if (onLoad === void 0) { onLoad = null; }
  24667. if (onError === void 0) { onError = null; }
  24668. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24669. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24670. };
  24671. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24672. if (parsedTexture.customType) {
  24673. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24674. // Update Sampling Mode
  24675. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24676. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24677. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24678. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24679. }
  24680. }
  24681. return parsedCustomTexture;
  24682. }
  24683. if (parsedTexture.isCube) {
  24684. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24685. }
  24686. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24687. return null;
  24688. }
  24689. var texture = BABYLON.SerializationHelper.Parse(function () {
  24690. var generateMipMaps = true;
  24691. if (parsedTexture.noMipmap) {
  24692. generateMipMaps = false;
  24693. }
  24694. if (parsedTexture.mirrorPlane) {
  24695. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24696. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24697. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24698. return mirrorTexture;
  24699. }
  24700. else if (parsedTexture.isRenderTarget) {
  24701. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24702. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24703. return renderTargetTexture;
  24704. }
  24705. else {
  24706. var texture;
  24707. if (parsedTexture.base64String) {
  24708. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24709. }
  24710. else {
  24711. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24712. }
  24713. return texture;
  24714. }
  24715. }, parsedTexture, scene);
  24716. // Update Sampling Mode
  24717. if (parsedTexture.samplingMode) {
  24718. var sampling = parsedTexture.samplingMode;
  24719. if (texture._samplingMode !== sampling) {
  24720. texture.updateSamplingMode(sampling);
  24721. }
  24722. }
  24723. // Animations
  24724. if (parsedTexture.animations) {
  24725. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24726. var parsedAnimation = parsedTexture.animations[animationIndex];
  24727. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24728. }
  24729. }
  24730. return texture;
  24731. };
  24732. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24733. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24734. if (noMipmap === void 0) { noMipmap = false; }
  24735. if (invertY === void 0) { invertY = true; }
  24736. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24737. if (onLoad === void 0) { onLoad = null; }
  24738. if (onError === void 0) { onError = null; }
  24739. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24740. if (name.substr(0, 5) !== "data:") {
  24741. name = "data:" + name;
  24742. }
  24743. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24744. };
  24745. // Constants
  24746. Texture.NEAREST_SAMPLINGMODE = 1;
  24747. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24748. Texture.BILINEAR_SAMPLINGMODE = 2;
  24749. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24750. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24751. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24752. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24753. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24754. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24755. Texture.NEAREST_LINEAR = 7;
  24756. Texture.NEAREST_NEAREST = 8;
  24757. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24758. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24759. Texture.LINEAR_LINEAR = 11;
  24760. Texture.LINEAR_NEAREST = 12;
  24761. Texture.EXPLICIT_MODE = 0;
  24762. Texture.SPHERICAL_MODE = 1;
  24763. Texture.PLANAR_MODE = 2;
  24764. Texture.CUBIC_MODE = 3;
  24765. Texture.PROJECTION_MODE = 4;
  24766. Texture.SKYBOX_MODE = 5;
  24767. Texture.INVCUBIC_MODE = 6;
  24768. Texture.EQUIRECTANGULAR_MODE = 7;
  24769. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24770. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24771. Texture.CLAMP_ADDRESSMODE = 0;
  24772. Texture.WRAP_ADDRESSMODE = 1;
  24773. Texture.MIRROR_ADDRESSMODE = 2;
  24774. __decorate([
  24775. BABYLON.serialize()
  24776. ], Texture.prototype, "url", void 0);
  24777. __decorate([
  24778. BABYLON.serialize()
  24779. ], Texture.prototype, "uOffset", void 0);
  24780. __decorate([
  24781. BABYLON.serialize()
  24782. ], Texture.prototype, "vOffset", void 0);
  24783. __decorate([
  24784. BABYLON.serialize()
  24785. ], Texture.prototype, "uScale", void 0);
  24786. __decorate([
  24787. BABYLON.serialize()
  24788. ], Texture.prototype, "vScale", void 0);
  24789. __decorate([
  24790. BABYLON.serialize()
  24791. ], Texture.prototype, "uAng", void 0);
  24792. __decorate([
  24793. BABYLON.serialize()
  24794. ], Texture.prototype, "vAng", void 0);
  24795. __decorate([
  24796. BABYLON.serialize()
  24797. ], Texture.prototype, "wAng", void 0);
  24798. __decorate([
  24799. BABYLON.serialize()
  24800. ], Texture.prototype, "isBlocking", null);
  24801. return Texture;
  24802. }(BABYLON.BaseTexture));
  24803. BABYLON.Texture = Texture;
  24804. })(BABYLON || (BABYLON = {}));
  24805. //# sourceMappingURL=babylon.texture.js.map
  24806. var BABYLON;
  24807. (function (BABYLON) {
  24808. var _InstancesBatch = /** @class */ (function () {
  24809. function _InstancesBatch() {
  24810. this.mustReturn = false;
  24811. this.visibleInstances = new Array();
  24812. this.renderSelf = new Array();
  24813. }
  24814. return _InstancesBatch;
  24815. }());
  24816. BABYLON._InstancesBatch = _InstancesBatch;
  24817. var Mesh = /** @class */ (function (_super) {
  24818. __extends(Mesh, _super);
  24819. /**
  24820. * @constructor
  24821. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24822. * @param {Scene} scene The scene to add this mesh to.
  24823. * @param {Node} parent The parent of this mesh, if it has one
  24824. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24825. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24826. * When false, achieved by calling a clone(), also passing False.
  24827. * This will make creation of children, recursive.
  24828. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24829. */
  24830. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24831. if (scene === void 0) { scene = null; }
  24832. if (parent === void 0) { parent = null; }
  24833. if (source === void 0) { source = null; }
  24834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24835. var _this = _super.call(this, name, scene) || this;
  24836. // Events
  24837. /**
  24838. * An event triggered before rendering the mesh
  24839. * @type {BABYLON.Observable}
  24840. */
  24841. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24842. /**
  24843. * An event triggered after rendering the mesh
  24844. * @type {BABYLON.Observable}
  24845. */
  24846. _this.onAfterRenderObservable = new BABYLON.Observable();
  24847. /**
  24848. * An event triggered before drawing the mesh
  24849. * @type {BABYLON.Observable}
  24850. */
  24851. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24852. // Members
  24853. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24854. _this.instances = new Array();
  24855. _this._LODLevels = new Array();
  24856. _this._visibleInstances = {};
  24857. _this._renderIdForInstances = new Array();
  24858. _this._batchCache = new _InstancesBatch();
  24859. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24860. // Use by builder only to know what orientation were the mesh build in.
  24861. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24862. _this.overrideMaterialSideOrientation = null;
  24863. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24864. // Will be used to save a source mesh reference, If any
  24865. _this._source = null;
  24866. scene = _this.getScene();
  24867. if (source) {
  24868. // Source mesh
  24869. _this._source = source;
  24870. // Geometry
  24871. if (source._geometry) {
  24872. source._geometry.applyToMesh(_this);
  24873. }
  24874. // Deep copy
  24875. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24876. // Metadata
  24877. if (source.metadata && source.metadata.clone) {
  24878. _this.metadata = source.metadata.clone();
  24879. }
  24880. else {
  24881. _this.metadata = source.metadata;
  24882. }
  24883. // Tags
  24884. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24885. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24886. }
  24887. // Parent
  24888. _this.parent = source.parent;
  24889. // Pivot
  24890. _this.setPivotMatrix(source.getPivotMatrix());
  24891. _this.id = name + "." + source.id;
  24892. // Material
  24893. _this.material = source.material;
  24894. var index;
  24895. if (!doNotCloneChildren) {
  24896. // Children
  24897. var directDescendants = source.getDescendants(true);
  24898. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24899. var child = directDescendants[index_1];
  24900. if (child.clone) {
  24901. child.clone(name + "." + child.name, _this);
  24902. }
  24903. }
  24904. }
  24905. // Physics clone
  24906. var physicsEngine = _this.getScene().getPhysicsEngine();
  24907. if (clonePhysicsImpostor && physicsEngine) {
  24908. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24909. if (impostor) {
  24910. _this.physicsImpostor = impostor.clone(_this);
  24911. }
  24912. }
  24913. // Particles
  24914. for (index = 0; index < scene.particleSystems.length; index++) {
  24915. var system = scene.particleSystems[index];
  24916. if (system.emitter === source) {
  24917. system.clone(system.name, _this);
  24918. }
  24919. }
  24920. _this.computeWorldMatrix(true);
  24921. }
  24922. // Parent
  24923. if (parent !== null) {
  24924. _this.parent = parent;
  24925. }
  24926. return _this;
  24927. }
  24928. Object.defineProperty(Mesh, "FRONTSIDE", {
  24929. /**
  24930. * Mesh side orientation : usually the external or front surface
  24931. */
  24932. get: function () {
  24933. return Mesh._FRONTSIDE;
  24934. },
  24935. enumerable: true,
  24936. configurable: true
  24937. });
  24938. Object.defineProperty(Mesh, "BACKSIDE", {
  24939. /**
  24940. * Mesh side orientation : usually the internal or back surface
  24941. */
  24942. get: function () {
  24943. return Mesh._BACKSIDE;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24949. /**
  24950. * Mesh side orientation : both internal and external or front and back surfaces
  24951. */
  24952. get: function () {
  24953. return Mesh._DOUBLESIDE;
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24959. /**
  24960. * Mesh side orientation : by default, `FRONTSIDE`
  24961. */
  24962. get: function () {
  24963. return Mesh._DEFAULTSIDE;
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. Object.defineProperty(Mesh, "NO_CAP", {
  24969. /**
  24970. * Mesh cap setting : no cap
  24971. */
  24972. get: function () {
  24973. return Mesh._NO_CAP;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(Mesh, "CAP_START", {
  24979. /**
  24980. * Mesh cap setting : one cap at the beginning of the mesh
  24981. */
  24982. get: function () {
  24983. return Mesh._CAP_START;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. Object.defineProperty(Mesh, "CAP_END", {
  24989. /**
  24990. * Mesh cap setting : one cap at the end of the mesh
  24991. */
  24992. get: function () {
  24993. return Mesh._CAP_END;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. Object.defineProperty(Mesh, "CAP_ALL", {
  24999. /**
  25000. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25001. */
  25002. get: function () {
  25003. return Mesh._CAP_ALL;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25009. set: function (callback) {
  25010. if (this._onBeforeDrawObserver) {
  25011. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25012. }
  25013. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25019. get: function () {
  25020. return this._morphTargetManager;
  25021. },
  25022. set: function (value) {
  25023. if (this._morphTargetManager === value) {
  25024. return;
  25025. }
  25026. this._morphTargetManager = value;
  25027. this._syncGeometryWithMorphTargetManager();
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. Object.defineProperty(Mesh.prototype, "source", {
  25033. get: function () {
  25034. return this._source;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25040. get: function () {
  25041. return this._unIndexed;
  25042. },
  25043. set: function (value) {
  25044. if (this._unIndexed !== value) {
  25045. this._unIndexed = value;
  25046. this._markSubMeshesAsAttributesDirty();
  25047. }
  25048. },
  25049. enumerable: true,
  25050. configurable: true
  25051. });
  25052. // Methods
  25053. /**
  25054. * Returns the string "Mesh".
  25055. */
  25056. Mesh.prototype.getClassName = function () {
  25057. return "Mesh";
  25058. };
  25059. /**
  25060. * Returns a string.
  25061. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25062. */
  25063. Mesh.prototype.toString = function (fullDetails) {
  25064. var ret = _super.prototype.toString.call(this, fullDetails);
  25065. ret += ", n vertices: " + this.getTotalVertices();
  25066. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25067. if (this.animations) {
  25068. for (var i = 0; i < this.animations.length; i++) {
  25069. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25070. }
  25071. }
  25072. if (fullDetails) {
  25073. if (this._geometry) {
  25074. var ib = this.getIndices();
  25075. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25076. if (vb && ib) {
  25077. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25078. }
  25079. }
  25080. else {
  25081. ret += ", flat shading: UNKNOWN";
  25082. }
  25083. }
  25084. return ret;
  25085. };
  25086. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25087. /**
  25088. * True if the mesh has some Levels Of Details (LOD).
  25089. * Returns a boolean.
  25090. */
  25091. get: function () {
  25092. return this._LODLevels.length > 0;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. Mesh.prototype._sortLODLevels = function () {
  25098. this._LODLevels.sort(function (a, b) {
  25099. if (a.distance < b.distance) {
  25100. return 1;
  25101. }
  25102. if (a.distance > b.distance) {
  25103. return -1;
  25104. }
  25105. return 0;
  25106. });
  25107. };
  25108. /**
  25109. * Add a mesh as LOD level triggered at the given distance.
  25110. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25111. * @param {number} distance The distance from the center of the object to show this level
  25112. * @param {Mesh} mesh The mesh to be added as LOD level
  25113. * @return {Mesh} This mesh (for chaining)
  25114. */
  25115. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25116. if (mesh && mesh._masterMesh) {
  25117. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25118. return this;
  25119. }
  25120. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25121. this._LODLevels.push(level);
  25122. if (mesh) {
  25123. mesh._masterMesh = this;
  25124. }
  25125. this._sortLODLevels();
  25126. return this;
  25127. };
  25128. /**
  25129. * Returns the LOD level mesh at the passed distance or null if not found.
  25130. * It is related to the method `addLODLevel(distance, mesh)`.
  25131. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25132. * Returns an object Mesh or `null`.
  25133. */
  25134. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25135. for (var index = 0; index < this._LODLevels.length; index++) {
  25136. var level = this._LODLevels[index];
  25137. if (level.distance === distance) {
  25138. return level.mesh;
  25139. }
  25140. }
  25141. return null;
  25142. };
  25143. /**
  25144. * Remove a mesh from the LOD array
  25145. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25146. * @param {Mesh} mesh The mesh to be removed.
  25147. * @return {Mesh} This mesh (for chaining)
  25148. */
  25149. Mesh.prototype.removeLODLevel = function (mesh) {
  25150. for (var index = 0; index < this._LODLevels.length; index++) {
  25151. if (this._LODLevels[index].mesh === mesh) {
  25152. this._LODLevels.splice(index, 1);
  25153. if (mesh) {
  25154. mesh._masterMesh = null;
  25155. }
  25156. }
  25157. }
  25158. this._sortLODLevels();
  25159. return this;
  25160. };
  25161. /**
  25162. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25163. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25164. */
  25165. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25166. if (!this._LODLevels || this._LODLevels.length === 0) {
  25167. return this;
  25168. }
  25169. var bSphere;
  25170. if (boundingSphere) {
  25171. bSphere = boundingSphere;
  25172. }
  25173. else {
  25174. var boundingInfo = this.getBoundingInfo();
  25175. bSphere = boundingInfo.boundingSphere;
  25176. }
  25177. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25178. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25179. if (this.onLODLevelSelection) {
  25180. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25181. }
  25182. return this;
  25183. }
  25184. for (var index = 0; index < this._LODLevels.length; index++) {
  25185. var level = this._LODLevels[index];
  25186. if (level.distance < distanceToCamera) {
  25187. if (level.mesh) {
  25188. level.mesh._preActivate();
  25189. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25190. }
  25191. if (this.onLODLevelSelection) {
  25192. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25193. }
  25194. return level.mesh;
  25195. }
  25196. }
  25197. if (this.onLODLevelSelection) {
  25198. this.onLODLevelSelection(distanceToCamera, this, this);
  25199. }
  25200. return this;
  25201. };
  25202. Object.defineProperty(Mesh.prototype, "geometry", {
  25203. /**
  25204. * Returns the mesh internal Geometry object.
  25205. */
  25206. get: function () {
  25207. return this._geometry;
  25208. },
  25209. enumerable: true,
  25210. configurable: true
  25211. });
  25212. /**
  25213. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25214. */
  25215. Mesh.prototype.getTotalVertices = function () {
  25216. if (this._geometry === null || this._geometry === undefined) {
  25217. return 0;
  25218. }
  25219. return this._geometry.getTotalVertices();
  25220. };
  25221. /**
  25222. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25223. * 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.
  25224. * You can force the copy with forceCopy === true
  25225. * Returns null if the mesh has no geometry or no vertex buffer.
  25226. * Possible `kind` values :
  25227. * - BABYLON.VertexBuffer.PositionKind
  25228. * - BABYLON.VertexBuffer.UVKind
  25229. * - BABYLON.VertexBuffer.UV2Kind
  25230. * - BABYLON.VertexBuffer.UV3Kind
  25231. * - BABYLON.VertexBuffer.UV4Kind
  25232. * - BABYLON.VertexBuffer.UV5Kind
  25233. * - BABYLON.VertexBuffer.UV6Kind
  25234. * - BABYLON.VertexBuffer.ColorKind
  25235. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25236. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25237. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25238. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25239. */
  25240. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25241. if (!this._geometry) {
  25242. return null;
  25243. }
  25244. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25245. };
  25246. /**
  25247. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25248. * Returns `null` if the mesh has no geometry.
  25249. * Possible `kind` values :
  25250. * - BABYLON.VertexBuffer.PositionKind
  25251. * - BABYLON.VertexBuffer.UVKind
  25252. * - BABYLON.VertexBuffer.UV2Kind
  25253. * - BABYLON.VertexBuffer.UV3Kind
  25254. * - BABYLON.VertexBuffer.UV4Kind
  25255. * - BABYLON.VertexBuffer.UV5Kind
  25256. * - BABYLON.VertexBuffer.UV6Kind
  25257. * - BABYLON.VertexBuffer.ColorKind
  25258. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25259. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25260. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25261. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25262. */
  25263. Mesh.prototype.getVertexBuffer = function (kind) {
  25264. if (!this._geometry) {
  25265. return null;
  25266. }
  25267. return this._geometry.getVertexBuffer(kind);
  25268. };
  25269. /**
  25270. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25271. * Possible `kind` values :
  25272. * - BABYLON.VertexBuffer.PositionKind
  25273. * - BABYLON.VertexBuffer.UVKind
  25274. * - BABYLON.VertexBuffer.UV2Kind
  25275. * - BABYLON.VertexBuffer.UV3Kind
  25276. * - BABYLON.VertexBuffer.UV4Kind
  25277. * - BABYLON.VertexBuffer.UV5Kind
  25278. * - BABYLON.VertexBuffer.UV6Kind
  25279. * - BABYLON.VertexBuffer.ColorKind
  25280. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25281. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25282. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25283. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25284. */
  25285. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25286. if (!this._geometry) {
  25287. if (this._delayInfo) {
  25288. return this._delayInfo.indexOf(kind) !== -1;
  25289. }
  25290. return false;
  25291. }
  25292. return this._geometry.isVerticesDataPresent(kind);
  25293. };
  25294. /**
  25295. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25296. * Possible `kind` values :
  25297. * - BABYLON.VertexBuffer.PositionKind
  25298. * - BABYLON.VertexBuffer.UVKind
  25299. * - BABYLON.VertexBuffer.UV2Kind
  25300. * - BABYLON.VertexBuffer.UV3Kind
  25301. * - BABYLON.VertexBuffer.UV4Kind
  25302. * - BABYLON.VertexBuffer.UV5Kind
  25303. * - BABYLON.VertexBuffer.UV6Kind
  25304. * - BABYLON.VertexBuffer.ColorKind
  25305. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25306. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25307. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25308. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25309. */
  25310. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25311. if (!this._geometry) {
  25312. if (this._delayInfo) {
  25313. return this._delayInfo.indexOf(kind) !== -1;
  25314. }
  25315. return false;
  25316. }
  25317. return this._geometry.isVertexBufferUpdatable(kind);
  25318. };
  25319. /**
  25320. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25321. * Possible `kind` values :
  25322. * - BABYLON.VertexBuffer.PositionKind
  25323. * - BABYLON.VertexBuffer.UVKind
  25324. * - BABYLON.VertexBuffer.UV2Kind
  25325. * - BABYLON.VertexBuffer.UV3Kind
  25326. * - BABYLON.VertexBuffer.UV4Kind
  25327. * - BABYLON.VertexBuffer.UV5Kind
  25328. * - BABYLON.VertexBuffer.UV6Kind
  25329. * - BABYLON.VertexBuffer.ColorKind
  25330. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25331. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25332. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25333. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25334. */
  25335. Mesh.prototype.getVerticesDataKinds = function () {
  25336. if (!this._geometry) {
  25337. var result = new Array();
  25338. if (this._delayInfo) {
  25339. this._delayInfo.forEach(function (kind, index, array) {
  25340. result.push(kind);
  25341. });
  25342. }
  25343. return result;
  25344. }
  25345. return this._geometry.getVerticesDataKinds();
  25346. };
  25347. /**
  25348. * Returns a positive integer : the total number of indices in this mesh geometry.
  25349. * Returns zero if the mesh has no geometry.
  25350. */
  25351. Mesh.prototype.getTotalIndices = function () {
  25352. if (!this._geometry) {
  25353. return 0;
  25354. }
  25355. return this._geometry.getTotalIndices();
  25356. };
  25357. /**
  25358. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25359. * 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.
  25360. * Returns an empty array if the mesh has no geometry.
  25361. */
  25362. Mesh.prototype.getIndices = function (copyWhenShared) {
  25363. if (!this._geometry) {
  25364. return [];
  25365. }
  25366. return this._geometry.getIndices(copyWhenShared);
  25367. };
  25368. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25369. get: function () {
  25370. return this._masterMesh !== null && this._masterMesh !== undefined;
  25371. },
  25372. enumerable: true,
  25373. configurable: true
  25374. });
  25375. /**
  25376. * Determine if the current mesh is ready to be rendered
  25377. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25378. * @returns true if all associated assets are ready (material, textures, shaders)
  25379. */
  25380. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25381. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25383. return false;
  25384. }
  25385. if (!_super.prototype.isReady.call(this)) {
  25386. return false;
  25387. }
  25388. if (!this.subMeshes || this.subMeshes.length === 0) {
  25389. return true;
  25390. }
  25391. var engine = this.getEngine();
  25392. var scene = this.getScene();
  25393. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25394. this.computeWorldMatrix();
  25395. var mat = this.material || scene.defaultMaterial;
  25396. if (mat) {
  25397. if (mat.storeEffectOnSubMeshes) {
  25398. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25399. var subMesh = _a[_i];
  25400. var effectiveMaterial = subMesh.getMaterial();
  25401. if (effectiveMaterial) {
  25402. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25403. return false;
  25404. }
  25405. }
  25406. }
  25407. }
  25408. else {
  25409. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25410. return false;
  25411. }
  25412. }
  25413. }
  25414. // Shadows
  25415. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25416. var light = _c[_b];
  25417. var generator = light.getShadowGenerator();
  25418. if (generator) {
  25419. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25420. var subMesh = _e[_d];
  25421. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25422. return false;
  25423. }
  25424. }
  25425. }
  25426. }
  25427. // LOD
  25428. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25429. var lod = _g[_f];
  25430. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25431. return false;
  25432. }
  25433. }
  25434. return true;
  25435. };
  25436. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25437. /**
  25438. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25439. * This property is pertinent only for updatable parametric shapes.
  25440. */
  25441. get: function () {
  25442. return this._areNormalsFrozen;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. /**
  25448. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25449. * It has no effect at all on other shapes.
  25450. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25451. * Returns the Mesh.
  25452. */
  25453. Mesh.prototype.freezeNormals = function () {
  25454. this._areNormalsFrozen = true;
  25455. return this;
  25456. };
  25457. /**
  25458. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25459. * It has no effect at all on other shapes.
  25460. * It reactivates the mesh normals computation if it was previously frozen.
  25461. * Returns the Mesh.
  25462. */
  25463. Mesh.prototype.unfreezeNormals = function () {
  25464. this._areNormalsFrozen = false;
  25465. return this;
  25466. };
  25467. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25468. /**
  25469. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25470. */
  25471. set: function (count) {
  25472. this._overridenInstanceCount = count;
  25473. },
  25474. enumerable: true,
  25475. configurable: true
  25476. });
  25477. // Methods
  25478. Mesh.prototype._preActivate = function () {
  25479. var sceneRenderId = this.getScene().getRenderId();
  25480. if (this._preActivateId === sceneRenderId) {
  25481. return this;
  25482. }
  25483. this._preActivateId = sceneRenderId;
  25484. this._visibleInstances = null;
  25485. return this;
  25486. };
  25487. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25488. if (this._visibleInstances) {
  25489. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25490. }
  25491. return this;
  25492. };
  25493. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25494. if (!this._visibleInstances) {
  25495. this._visibleInstances = {};
  25496. this._visibleInstances.defaultRenderId = renderId;
  25497. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25498. }
  25499. if (!this._visibleInstances[renderId]) {
  25500. this._visibleInstances[renderId] = new Array();
  25501. }
  25502. this._visibleInstances[renderId].push(instance);
  25503. return this;
  25504. };
  25505. /**
  25506. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25507. * This means the mesh underlying bounding box and sphere are recomputed.
  25508. * Returns the Mesh.
  25509. */
  25510. Mesh.prototype.refreshBoundingInfo = function () {
  25511. return this._refreshBoundingInfo(false);
  25512. };
  25513. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25514. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25515. return this;
  25516. }
  25517. var data = this._getPositionData(applySkeleton);
  25518. if (data) {
  25519. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25520. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25521. }
  25522. if (this.subMeshes) {
  25523. for (var index = 0; index < this.subMeshes.length; index++) {
  25524. this.subMeshes[index].refreshBoundingInfo();
  25525. }
  25526. }
  25527. this._updateBoundingInfo();
  25528. return this;
  25529. };
  25530. Mesh.prototype._getPositionData = function (applySkeleton) {
  25531. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25532. if (data && applySkeleton && this.skeleton) {
  25533. data = data.slice();
  25534. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25535. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25536. if (matricesWeightsData && matricesIndicesData) {
  25537. var needExtras = this.numBoneInfluencers > 4;
  25538. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25539. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25540. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25541. var tempVector = BABYLON.Tmp.Vector3[0];
  25542. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25543. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25544. var matWeightIdx = 0;
  25545. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25546. finalMatrix.reset();
  25547. var inf;
  25548. var weight;
  25549. for (inf = 0; inf < 4; inf++) {
  25550. weight = matricesWeightsData[matWeightIdx + inf];
  25551. if (weight <= 0)
  25552. break;
  25553. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25554. finalMatrix.addToSelf(tempMatrix);
  25555. }
  25556. if (needExtras) {
  25557. for (inf = 0; inf < 4; inf++) {
  25558. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25559. if (weight <= 0)
  25560. break;
  25561. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25562. finalMatrix.addToSelf(tempMatrix);
  25563. }
  25564. }
  25565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25566. tempVector.toArray(data, index);
  25567. }
  25568. }
  25569. }
  25570. return data;
  25571. };
  25572. Mesh.prototype._createGlobalSubMesh = function (force) {
  25573. var totalVertices = this.getTotalVertices();
  25574. if (!totalVertices || !this.getIndices()) {
  25575. return null;
  25576. }
  25577. // Check if we need to recreate the submeshes
  25578. if (this.subMeshes && this.subMeshes.length > 0) {
  25579. var ib = this.getIndices();
  25580. if (!ib) {
  25581. return null;
  25582. }
  25583. var totalIndices = ib.length;
  25584. var needToRecreate = false;
  25585. if (force) {
  25586. needToRecreate = true;
  25587. }
  25588. else {
  25589. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25590. var submesh = _a[_i];
  25591. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25592. needToRecreate = true;
  25593. break;
  25594. }
  25595. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25596. needToRecreate = true;
  25597. break;
  25598. }
  25599. }
  25600. }
  25601. if (!needToRecreate) {
  25602. return this.subMeshes[0];
  25603. }
  25604. }
  25605. this.releaseSubMeshes();
  25606. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25607. };
  25608. Mesh.prototype.subdivide = function (count) {
  25609. if (count < 1) {
  25610. return;
  25611. }
  25612. var totalIndices = this.getTotalIndices();
  25613. var subdivisionSize = (totalIndices / count) | 0;
  25614. var offset = 0;
  25615. // Ensure that subdivisionSize is a multiple of 3
  25616. while (subdivisionSize % 3 !== 0) {
  25617. subdivisionSize++;
  25618. }
  25619. this.releaseSubMeshes();
  25620. for (var index = 0; index < count; index++) {
  25621. if (offset >= totalIndices) {
  25622. break;
  25623. }
  25624. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25625. offset += subdivisionSize;
  25626. }
  25627. this.synchronizeInstances();
  25628. };
  25629. /**
  25630. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25631. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25632. * The `data` are either a numeric array either a Float32Array.
  25633. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25634. * 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).
  25635. * Note that a new underlying VertexBuffer object is created each call.
  25636. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25637. *
  25638. * Possible `kind` values :
  25639. * - BABYLON.VertexBuffer.PositionKind
  25640. * - BABYLON.VertexBuffer.UVKind
  25641. * - BABYLON.VertexBuffer.UV2Kind
  25642. * - BABYLON.VertexBuffer.UV3Kind
  25643. * - BABYLON.VertexBuffer.UV4Kind
  25644. * - BABYLON.VertexBuffer.UV5Kind
  25645. * - BABYLON.VertexBuffer.UV6Kind
  25646. * - BABYLON.VertexBuffer.ColorKind
  25647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25651. *
  25652. * Returns the Mesh.
  25653. */
  25654. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25655. if (updatable === void 0) { updatable = false; }
  25656. if (!this._geometry) {
  25657. var vertexData = new BABYLON.VertexData();
  25658. vertexData.set(data, kind);
  25659. var scene = this.getScene();
  25660. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25661. }
  25662. else {
  25663. this._geometry.setVerticesData(kind, data, updatable, stride);
  25664. }
  25665. return this;
  25666. };
  25667. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25668. if (updatable === void 0) { updatable = true; }
  25669. var vb = this.getVertexBuffer(kind);
  25670. if (!vb || vb.isUpdatable() === updatable) {
  25671. return;
  25672. }
  25673. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25674. };
  25675. /**
  25676. * Sets the mesh VertexBuffer.
  25677. * Returns the Mesh.
  25678. */
  25679. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25680. if (!this._geometry) {
  25681. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25682. }
  25683. this._geometry.setVerticesBuffer(buffer);
  25684. return this;
  25685. };
  25686. /**
  25687. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25688. * If the mesh has no geometry, it is simply returned as it is.
  25689. * The `data` are either a numeric array either a Float32Array.
  25690. * No new underlying VertexBuffer object is created.
  25691. * 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.
  25692. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25693. *
  25694. * Possible `kind` values :
  25695. * - BABYLON.VertexBuffer.PositionKind
  25696. * - BABYLON.VertexBuffer.UVKind
  25697. * - BABYLON.VertexBuffer.UV2Kind
  25698. * - BABYLON.VertexBuffer.UV3Kind
  25699. * - BABYLON.VertexBuffer.UV4Kind
  25700. * - BABYLON.VertexBuffer.UV5Kind
  25701. * - BABYLON.VertexBuffer.UV6Kind
  25702. * - BABYLON.VertexBuffer.ColorKind
  25703. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25704. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25705. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25706. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25707. *
  25708. * Returns the Mesh.
  25709. */
  25710. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25711. if (!this._geometry) {
  25712. return this;
  25713. }
  25714. if (!makeItUnique) {
  25715. this._geometry.updateVerticesData(kind, data, updateExtends);
  25716. }
  25717. else {
  25718. this.makeGeometryUnique();
  25719. this.updateVerticesData(kind, data, updateExtends, false);
  25720. }
  25721. return this;
  25722. };
  25723. /**
  25724. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25725. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25726. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25727. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25728. * Returns the Mesh.
  25729. */
  25730. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25731. if (computeNormals === void 0) { computeNormals = true; }
  25732. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25733. if (!positions) {
  25734. return this;
  25735. }
  25736. positionFunction(positions);
  25737. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25738. if (computeNormals) {
  25739. var indices = this.getIndices();
  25740. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25741. if (!normals) {
  25742. return this;
  25743. }
  25744. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25745. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25746. }
  25747. return this;
  25748. };
  25749. /**
  25750. * Creates a un-shared specific occurence of the geometry for the mesh.
  25751. * Returns the Mesh.
  25752. */
  25753. Mesh.prototype.makeGeometryUnique = function () {
  25754. if (!this._geometry) {
  25755. return this;
  25756. }
  25757. var oldGeometry = this._geometry;
  25758. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25759. oldGeometry.releaseForMesh(this, true);
  25760. geometry.applyToMesh(this);
  25761. return this;
  25762. };
  25763. /**
  25764. * Sets the mesh indices.
  25765. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25766. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25767. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25768. * This method creates a new index buffer each call.
  25769. * Returns the Mesh.
  25770. */
  25771. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25772. if (totalVertices === void 0) { totalVertices = null; }
  25773. if (updatable === void 0) { updatable = false; }
  25774. if (!this._geometry) {
  25775. var vertexData = new BABYLON.VertexData();
  25776. vertexData.indices = indices;
  25777. var scene = this.getScene();
  25778. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25779. }
  25780. else {
  25781. this._geometry.setIndices(indices, totalVertices, updatable);
  25782. }
  25783. return this;
  25784. };
  25785. /**
  25786. * Update the current index buffer
  25787. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25788. * Returns the Mesh.
  25789. */
  25790. Mesh.prototype.updateIndices = function (indices, offset) {
  25791. if (!this._geometry) {
  25792. return this;
  25793. }
  25794. this._geometry.updateIndices(indices, offset);
  25795. return this;
  25796. };
  25797. /**
  25798. * Invert the geometry to move from a right handed system to a left handed one.
  25799. * Returns the Mesh.
  25800. */
  25801. Mesh.prototype.toLeftHanded = function () {
  25802. if (!this._geometry) {
  25803. return this;
  25804. }
  25805. this._geometry.toLeftHanded();
  25806. return this;
  25807. };
  25808. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25809. if (!this._geometry) {
  25810. return this;
  25811. }
  25812. var engine = this.getScene().getEngine();
  25813. // Wireframe
  25814. var indexToBind;
  25815. if (this._unIndexed) {
  25816. indexToBind = null;
  25817. }
  25818. else {
  25819. switch (fillMode) {
  25820. case BABYLON.Material.PointFillMode:
  25821. indexToBind = null;
  25822. break;
  25823. case BABYLON.Material.WireFrameFillMode:
  25824. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25825. break;
  25826. default:
  25827. case BABYLON.Material.TriangleFillMode:
  25828. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25829. break;
  25830. }
  25831. }
  25832. // VBOs
  25833. this._geometry._bind(effect, indexToBind);
  25834. return this;
  25835. };
  25836. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25837. if (alternate === void 0) { alternate = false; }
  25838. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25839. return this;
  25840. }
  25841. this.onBeforeDrawObservable.notifyObservers(this);
  25842. var scene = this.getScene();
  25843. var engine = scene.getEngine();
  25844. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25845. // or triangles as points
  25846. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25847. }
  25848. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25849. // Triangles as wireframe
  25850. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25851. }
  25852. else {
  25853. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25854. }
  25855. if (scene._isAlternateRenderingEnabled && !alternate) {
  25856. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25857. if (!effect || !scene.activeCamera) {
  25858. return this;
  25859. }
  25860. scene._switchToAlternateCameraConfiguration(true);
  25861. this._effectiveMaterial.bindView(effect);
  25862. this._effectiveMaterial.bindViewProjection(effect);
  25863. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25864. this._draw(subMesh, fillMode, instancesCount, true);
  25865. engine.setViewport(scene.activeCamera.viewport);
  25866. scene._switchToAlternateCameraConfiguration(false);
  25867. this._effectiveMaterial.bindView(effect);
  25868. this._effectiveMaterial.bindViewProjection(effect);
  25869. }
  25870. return this;
  25871. };
  25872. /**
  25873. * Registers for this mesh a javascript function called just before the rendering process.
  25874. * This function is passed the current mesh.
  25875. * Return the Mesh.
  25876. */
  25877. Mesh.prototype.registerBeforeRender = function (func) {
  25878. this.onBeforeRenderObservable.add(func);
  25879. return this;
  25880. };
  25881. /**
  25882. * Disposes a previously registered javascript function called before the rendering.
  25883. * This function is passed the current mesh.
  25884. * Returns the Mesh.
  25885. */
  25886. Mesh.prototype.unregisterBeforeRender = function (func) {
  25887. this.onBeforeRenderObservable.removeCallback(func);
  25888. return this;
  25889. };
  25890. /**
  25891. * Registers for this mesh a javascript function called just after the rendering is complete.
  25892. * This function is passed the current mesh.
  25893. * Returns the Mesh.
  25894. */
  25895. Mesh.prototype.registerAfterRender = function (func) {
  25896. this.onAfterRenderObservable.add(func);
  25897. return this;
  25898. };
  25899. /**
  25900. * Disposes a previously registered javascript function called after the rendering.
  25901. * This function is passed the current mesh.
  25902. * Return the Mesh.
  25903. */
  25904. Mesh.prototype.unregisterAfterRender = function (func) {
  25905. this.onAfterRenderObservable.removeCallback(func);
  25906. return this;
  25907. };
  25908. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25909. var scene = this.getScene();
  25910. this._batchCache.mustReturn = false;
  25911. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25912. this._batchCache.visibleInstances[subMeshId] = null;
  25913. if (this._visibleInstances) {
  25914. var currentRenderId = scene.getRenderId();
  25915. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25916. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25917. var selfRenderId = this._renderId;
  25918. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25919. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25920. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25921. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25922. }
  25923. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25924. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25925. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25926. this._batchCache.mustReturn = true;
  25927. return this._batchCache;
  25928. }
  25929. if (currentRenderId !== selfRenderId) {
  25930. this._batchCache.renderSelf[subMeshId] = false;
  25931. }
  25932. }
  25933. this._renderIdForInstances[subMeshId] = currentRenderId;
  25934. }
  25935. return this._batchCache;
  25936. };
  25937. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25938. var visibleInstances = batch.visibleInstances[subMesh._id];
  25939. if (!visibleInstances) {
  25940. return this;
  25941. }
  25942. var matricesCount = visibleInstances.length + 1;
  25943. var bufferSize = matricesCount * 16 * 4;
  25944. var currentInstancesBufferSize = this._instancesBufferSize;
  25945. var instancesBuffer = this._instancesBuffer;
  25946. while (this._instancesBufferSize < bufferSize) {
  25947. this._instancesBufferSize *= 2;
  25948. }
  25949. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25950. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25951. }
  25952. var offset = 0;
  25953. var instancesCount = 0;
  25954. var world = this.getWorldMatrix();
  25955. if (batch.renderSelf[subMesh._id]) {
  25956. world.copyToArray(this._instancesData, offset);
  25957. offset += 16;
  25958. instancesCount++;
  25959. }
  25960. if (visibleInstances) {
  25961. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25962. var instance = visibleInstances[instanceIndex];
  25963. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25964. offset += 16;
  25965. instancesCount++;
  25966. }
  25967. }
  25968. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25969. if (instancesBuffer) {
  25970. instancesBuffer.dispose();
  25971. }
  25972. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25973. this._instancesBuffer = instancesBuffer;
  25974. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25975. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25976. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25977. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25978. }
  25979. else {
  25980. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25981. }
  25982. this._bind(subMesh, effect, fillMode);
  25983. this._draw(subMesh, fillMode, instancesCount);
  25984. engine.unbindInstanceAttributes();
  25985. return this;
  25986. };
  25987. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25988. var scene = this.getScene();
  25989. var engine = scene.getEngine();
  25990. if (hardwareInstancedRendering) {
  25991. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25992. }
  25993. else {
  25994. if (batch.renderSelf[subMesh._id]) {
  25995. // Draw
  25996. if (onBeforeDraw) {
  25997. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25998. }
  25999. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26000. }
  26001. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26002. if (visibleInstancesForSubMesh) {
  26003. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26004. var instance = visibleInstancesForSubMesh[instanceIndex];
  26005. // World
  26006. var world = instance.getWorldMatrix();
  26007. if (onBeforeDraw) {
  26008. onBeforeDraw(true, world, effectiveMaterial);
  26009. }
  26010. // Draw
  26011. this._draw(subMesh, fillMode);
  26012. }
  26013. }
  26014. }
  26015. return this;
  26016. };
  26017. /**
  26018. * Triggers the draw call for the mesh.
  26019. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26020. * Returns the Mesh.
  26021. */
  26022. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26023. this.checkOcclusionQuery();
  26024. if (this._isOccluded) {
  26025. return this;
  26026. }
  26027. var scene = this.getScene();
  26028. // Managing instances
  26029. var batch = this._getInstancesRenderList(subMesh._id);
  26030. if (batch.mustReturn) {
  26031. return this;
  26032. }
  26033. // Checking geometry state
  26034. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26035. return this;
  26036. }
  26037. this.onBeforeRenderObservable.notifyObservers(this);
  26038. var engine = scene.getEngine();
  26039. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26040. // Material
  26041. var material = subMesh.getMaterial();
  26042. if (!material) {
  26043. return this;
  26044. }
  26045. this._effectiveMaterial = material;
  26046. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26047. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26048. return this;
  26049. }
  26050. }
  26051. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26052. return this;
  26053. }
  26054. // Alpha mode
  26055. if (enableAlphaMode) {
  26056. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26057. }
  26058. // Outline - step 1
  26059. var savedDepthWrite = engine.getDepthWrite();
  26060. if (this.renderOutline) {
  26061. engine.setDepthWrite(false);
  26062. scene.getOutlineRenderer().render(subMesh, batch);
  26063. engine.setDepthWrite(savedDepthWrite);
  26064. }
  26065. var effect;
  26066. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26067. effect = subMesh.effect;
  26068. }
  26069. else {
  26070. effect = this._effectiveMaterial.getEffect();
  26071. }
  26072. if (!effect) {
  26073. return this;
  26074. }
  26075. var sideOrientation = this.overrideMaterialSideOrientation;
  26076. if (sideOrientation == null) {
  26077. sideOrientation = this._effectiveMaterial.sideOrientation;
  26078. if (this._getWorldMatrixDeterminant() < 0) {
  26079. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26080. }
  26081. }
  26082. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26083. if (this._effectiveMaterial.forceDepthWrite) {
  26084. engine.setDepthWrite(true);
  26085. }
  26086. // Bind
  26087. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26088. if (!hardwareInstancedRendering) {
  26089. this._bind(subMesh, effect, fillMode);
  26090. }
  26091. var world = this.getWorldMatrix();
  26092. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26093. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26094. }
  26095. else {
  26096. this._effectiveMaterial.bind(world, this);
  26097. }
  26098. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26099. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26100. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26101. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26102. }
  26103. // Draw
  26104. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26105. // Unbind
  26106. this._effectiveMaterial.unbind();
  26107. // Outline - step 2
  26108. if (this.renderOutline && savedDepthWrite) {
  26109. engine.setDepthWrite(true);
  26110. engine.setColorWrite(false);
  26111. scene.getOutlineRenderer().render(subMesh, batch);
  26112. engine.setColorWrite(true);
  26113. }
  26114. // Overlay
  26115. if (this.renderOverlay) {
  26116. var currentMode = engine.getAlphaMode();
  26117. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26118. scene.getOutlineRenderer().render(subMesh, batch, true);
  26119. engine.setAlphaMode(currentMode);
  26120. }
  26121. this.onAfterRenderObservable.notifyObservers(this);
  26122. return this;
  26123. };
  26124. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26125. if (isInstance && effectiveMaterial) {
  26126. effectiveMaterial.bindOnlyWorldMatrix(world);
  26127. }
  26128. };
  26129. /**
  26130. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26131. */
  26132. Mesh.prototype.getEmittedParticleSystems = function () {
  26133. var results = new Array();
  26134. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26135. var particleSystem = this.getScene().particleSystems[index];
  26136. if (particleSystem.emitter === this) {
  26137. results.push(particleSystem);
  26138. }
  26139. }
  26140. return results;
  26141. };
  26142. /**
  26143. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26144. */
  26145. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26146. var results = new Array();
  26147. var descendants = this.getDescendants();
  26148. descendants.push(this);
  26149. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26150. var particleSystem = this.getScene().particleSystems[index];
  26151. var emitter = particleSystem.emitter;
  26152. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26153. results.push(particleSystem);
  26154. }
  26155. }
  26156. return results;
  26157. };
  26158. Mesh.prototype._checkDelayState = function () {
  26159. var scene = this.getScene();
  26160. if (this._geometry) {
  26161. this._geometry.load(scene);
  26162. }
  26163. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26165. this._queueLoad(scene);
  26166. }
  26167. return this;
  26168. };
  26169. Mesh.prototype._queueLoad = function (scene) {
  26170. var _this = this;
  26171. scene._addPendingData(this);
  26172. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26173. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26174. if (data instanceof ArrayBuffer) {
  26175. _this._delayLoadingFunction(data, _this);
  26176. }
  26177. else {
  26178. _this._delayLoadingFunction(JSON.parse(data), _this);
  26179. }
  26180. _this.instances.forEach(function (instance) {
  26181. instance._syncSubMeshes();
  26182. });
  26183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26184. scene._removePendingData(_this);
  26185. }, function () { }, scene.database, getBinaryData);
  26186. return this;
  26187. };
  26188. /**
  26189. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26190. */
  26191. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26192. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26193. return false;
  26194. }
  26195. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26196. return false;
  26197. }
  26198. this._checkDelayState();
  26199. return true;
  26200. };
  26201. /**
  26202. * Sets the mesh material by the material or multiMaterial `id` property.
  26203. * The material `id` is a string identifying the material or the multiMaterial.
  26204. * This method returns the Mesh.
  26205. */
  26206. Mesh.prototype.setMaterialByID = function (id) {
  26207. var materials = this.getScene().materials;
  26208. var index;
  26209. for (index = materials.length - 1; index > -1; index--) {
  26210. if (materials[index].id === id) {
  26211. this.material = materials[index];
  26212. return this;
  26213. }
  26214. }
  26215. // Multi
  26216. var multiMaterials = this.getScene().multiMaterials;
  26217. for (index = multiMaterials.length - 1; index > -1; index--) {
  26218. if (multiMaterials[index].id === id) {
  26219. this.material = multiMaterials[index];
  26220. return this;
  26221. }
  26222. }
  26223. return this;
  26224. };
  26225. /**
  26226. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26227. */
  26228. Mesh.prototype.getAnimatables = function () {
  26229. var results = new Array();
  26230. if (this.material) {
  26231. results.push(this.material);
  26232. }
  26233. if (this.skeleton) {
  26234. results.push(this.skeleton);
  26235. }
  26236. return results;
  26237. };
  26238. /**
  26239. * Modifies the mesh geometry according to the passed transformation matrix.
  26240. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26241. * The mesh normals are modified accordingly the same transformation.
  26242. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26243. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26244. * Returns the Mesh.
  26245. */
  26246. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26247. // Position
  26248. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26249. return this;
  26250. }
  26251. var submeshes = this.subMeshes.splice(0);
  26252. this._resetPointsArrayCache();
  26253. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26254. var temp = new Array();
  26255. var index;
  26256. for (index = 0; index < data.length; index += 3) {
  26257. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26258. }
  26259. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26260. // Normals
  26261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26262. return this;
  26263. }
  26264. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26265. temp = [];
  26266. for (index = 0; index < data.length; index += 3) {
  26267. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26268. }
  26269. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26270. // flip faces?
  26271. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26272. this.flipFaces();
  26273. }
  26274. // Restore submeshes
  26275. this.releaseSubMeshes();
  26276. this.subMeshes = submeshes;
  26277. return this;
  26278. };
  26279. /**
  26280. * Modifies the mesh geometry according to its own current World Matrix.
  26281. * The mesh World Matrix is then reset.
  26282. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26283. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26284. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26285. * Returns the Mesh.
  26286. */
  26287. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26288. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26289. this.scaling.copyFromFloats(1, 1, 1);
  26290. this.position.copyFromFloats(0, 0, 0);
  26291. this.rotation.copyFromFloats(0, 0, 0);
  26292. //only if quaternion is already set
  26293. if (this.rotationQuaternion) {
  26294. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26295. }
  26296. this._worldMatrix = BABYLON.Matrix.Identity();
  26297. return this;
  26298. };
  26299. Object.defineProperty(Mesh.prototype, "_positions", {
  26300. // Cache
  26301. get: function () {
  26302. if (this._geometry) {
  26303. return this._geometry._positions;
  26304. }
  26305. return null;
  26306. },
  26307. enumerable: true,
  26308. configurable: true
  26309. });
  26310. Mesh.prototype._resetPointsArrayCache = function () {
  26311. if (this._geometry) {
  26312. this._geometry._resetPointsArrayCache();
  26313. }
  26314. return this;
  26315. };
  26316. Mesh.prototype._generatePointsArray = function () {
  26317. if (this._geometry) {
  26318. return this._geometry._generatePointsArray();
  26319. }
  26320. return false;
  26321. };
  26322. /**
  26323. * Returns a new Mesh object generated from the current mesh properties.
  26324. * This method must not get confused with createInstance().
  26325. * The parameter `name` is a string, the name given to the new mesh.
  26326. * The optional parameter `newParent` can be any Node object (default `null`).
  26327. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26328. * 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.
  26329. */
  26330. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26331. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26332. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26333. };
  26334. /**
  26335. * Disposes the Mesh.
  26336. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26337. * Returns nothing.
  26338. */
  26339. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26340. var _this = this;
  26341. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26342. this.morphTargetManager = null;
  26343. if (this._geometry) {
  26344. this._geometry.releaseForMesh(this, true);
  26345. }
  26346. // Sources
  26347. var meshes = this.getScene().meshes;
  26348. meshes.forEach(function (abstractMesh) {
  26349. var mesh = abstractMesh;
  26350. if (mesh._source && mesh._source === _this) {
  26351. mesh._source = null;
  26352. }
  26353. });
  26354. this._source = null;
  26355. // Instances
  26356. if (this._instancesBuffer) {
  26357. this._instancesBuffer.dispose();
  26358. this._instancesBuffer = null;
  26359. }
  26360. while (this.instances.length) {
  26361. this.instances[0].dispose();
  26362. }
  26363. // Highlight layers.
  26364. var highlightLayers = this.getScene().highlightLayers;
  26365. for (var i = 0; i < highlightLayers.length; i++) {
  26366. var highlightLayer = highlightLayers[i];
  26367. if (highlightLayer) {
  26368. highlightLayer.removeMesh(this);
  26369. highlightLayer.removeExcludedMesh(this);
  26370. }
  26371. }
  26372. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26373. };
  26374. /**
  26375. * Modifies the mesh geometry according to a displacement map.
  26376. * 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.
  26377. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26378. * This method returns nothing.
  26379. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26380. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26381. * 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.
  26382. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26383. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26384. *
  26385. * Returns the Mesh.
  26386. */
  26387. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26388. var _this = this;
  26389. var scene = this.getScene();
  26390. var onload = function (img) {
  26391. // Getting height map data
  26392. var canvas = document.createElement("canvas");
  26393. var context = canvas.getContext("2d");
  26394. var heightMapWidth = img.width;
  26395. var heightMapHeight = img.height;
  26396. canvas.width = heightMapWidth;
  26397. canvas.height = heightMapHeight;
  26398. context.drawImage(img, 0, 0);
  26399. // Create VertexData from map data
  26400. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26401. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26402. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26403. //execute success callback, if set
  26404. if (onSuccess) {
  26405. onSuccess(_this);
  26406. }
  26407. };
  26408. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26409. return this;
  26410. };
  26411. /**
  26412. * Modifies the mesh geometry according to a displacementMap buffer.
  26413. * 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.
  26414. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26415. * This method returns nothing.
  26416. * 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.
  26417. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26418. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26419. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26420. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26421. *
  26422. * Returns the Mesh.
  26423. */
  26424. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26425. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26426. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26427. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26428. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26429. return this;
  26430. }
  26431. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26432. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26433. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26434. var position = BABYLON.Vector3.Zero();
  26435. var normal = BABYLON.Vector3.Zero();
  26436. var uv = BABYLON.Vector2.Zero();
  26437. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26438. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26439. for (var index = 0; index < positions.length; index += 3) {
  26440. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26441. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26442. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26443. // Compute height
  26444. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26445. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26446. var pos = (u + v * heightMapWidth) * 4;
  26447. var r = buffer[pos] / 255.0;
  26448. var g = buffer[pos + 1] / 255.0;
  26449. var b = buffer[pos + 2] / 255.0;
  26450. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26451. normal.normalize();
  26452. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26453. position = position.add(normal);
  26454. position.toArray(positions, index);
  26455. }
  26456. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26457. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26458. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26459. return this;
  26460. };
  26461. /**
  26462. * Modify the mesh to get a flat shading rendering.
  26463. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26464. * This method returns the Mesh.
  26465. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26466. */
  26467. Mesh.prototype.convertToFlatShadedMesh = function () {
  26468. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26469. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26470. var kinds = this.getVerticesDataKinds();
  26471. var vbs = {};
  26472. var data = {};
  26473. var newdata = {};
  26474. var updatableNormals = false;
  26475. var kindIndex;
  26476. var kind;
  26477. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26478. kind = kinds[kindIndex];
  26479. var vertexBuffer = this.getVertexBuffer(kind);
  26480. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26481. updatableNormals = vertexBuffer.isUpdatable();
  26482. kinds.splice(kindIndex, 1);
  26483. kindIndex--;
  26484. continue;
  26485. }
  26486. vbs[kind] = vertexBuffer;
  26487. data[kind] = vbs[kind].getData();
  26488. newdata[kind] = [];
  26489. }
  26490. // Save previous submeshes
  26491. var previousSubmeshes = this.subMeshes.slice(0);
  26492. var indices = this.getIndices();
  26493. var totalIndices = this.getTotalIndices();
  26494. // Generating unique vertices per face
  26495. var index;
  26496. for (index = 0; index < totalIndices; index++) {
  26497. var vertexIndex = indices[index];
  26498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26499. kind = kinds[kindIndex];
  26500. var stride = vbs[kind].getStrideSize();
  26501. for (var offset = 0; offset < stride; offset++) {
  26502. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26503. }
  26504. }
  26505. }
  26506. // Updating faces & normal
  26507. var normals = [];
  26508. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26509. for (index = 0; index < totalIndices; index += 3) {
  26510. indices[index] = index;
  26511. indices[index + 1] = index + 1;
  26512. indices[index + 2] = index + 2;
  26513. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26514. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26515. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26516. var p1p2 = p1.subtract(p2);
  26517. var p3p2 = p3.subtract(p2);
  26518. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26519. // Store same normals for every vertex
  26520. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26521. normals.push(normal.x);
  26522. normals.push(normal.y);
  26523. normals.push(normal.z);
  26524. }
  26525. }
  26526. this.setIndices(indices);
  26527. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26528. // Updating vertex buffers
  26529. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26530. kind = kinds[kindIndex];
  26531. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26532. }
  26533. // Updating submeshes
  26534. this.releaseSubMeshes();
  26535. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26536. var previousOne = previousSubmeshes[submeshIndex];
  26537. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26538. }
  26539. this.synchronizeInstances();
  26540. return this;
  26541. };
  26542. /**
  26543. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26544. * In other words, more vertices, no more indices and a single bigger VBO.
  26545. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26546. * Returns the Mesh.
  26547. */
  26548. Mesh.prototype.convertToUnIndexedMesh = function () {
  26549. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26550. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26551. var kinds = this.getVerticesDataKinds();
  26552. var vbs = {};
  26553. var data = {};
  26554. var newdata = {};
  26555. var kindIndex;
  26556. var kind;
  26557. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26558. kind = kinds[kindIndex];
  26559. var vertexBuffer = this.getVertexBuffer(kind);
  26560. vbs[kind] = vertexBuffer;
  26561. data[kind] = vbs[kind].getData();
  26562. newdata[kind] = [];
  26563. }
  26564. // Save previous submeshes
  26565. var previousSubmeshes = this.subMeshes.slice(0);
  26566. var indices = this.getIndices();
  26567. var totalIndices = this.getTotalIndices();
  26568. // Generating unique vertices per face
  26569. var index;
  26570. for (index = 0; index < totalIndices; index++) {
  26571. var vertexIndex = indices[index];
  26572. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26573. kind = kinds[kindIndex];
  26574. var stride = vbs[kind].getStrideSize();
  26575. for (var offset = 0; offset < stride; offset++) {
  26576. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26577. }
  26578. }
  26579. }
  26580. // Updating indices
  26581. for (index = 0; index < totalIndices; index += 3) {
  26582. indices[index] = index;
  26583. indices[index + 1] = index + 1;
  26584. indices[index + 2] = index + 2;
  26585. }
  26586. this.setIndices(indices);
  26587. // Updating vertex buffers
  26588. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26589. kind = kinds[kindIndex];
  26590. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26591. }
  26592. // Updating submeshes
  26593. this.releaseSubMeshes();
  26594. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26595. var previousOne = previousSubmeshes[submeshIndex];
  26596. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26597. }
  26598. this._unIndexed = true;
  26599. this.synchronizeInstances();
  26600. return this;
  26601. };
  26602. /**
  26603. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26604. * This method returns the Mesh.
  26605. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26606. */
  26607. Mesh.prototype.flipFaces = function (flipNormals) {
  26608. if (flipNormals === void 0) { flipNormals = false; }
  26609. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26610. var i;
  26611. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26612. for (i = 0; i < vertex_data.normals.length; i++) {
  26613. vertex_data.normals[i] *= -1;
  26614. }
  26615. }
  26616. if (vertex_data.indices) {
  26617. var temp;
  26618. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26619. // reassign indices
  26620. temp = vertex_data.indices[i + 1];
  26621. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26622. vertex_data.indices[i + 2] = temp;
  26623. }
  26624. }
  26625. vertex_data.applyToMesh(this);
  26626. return this;
  26627. };
  26628. // Instances
  26629. /**
  26630. * Creates a new InstancedMesh object from the mesh model.
  26631. * An instance shares the same properties and the same material than its model.
  26632. * Only these properties of each instance can then be set individually :
  26633. * - position
  26634. * - rotation
  26635. * - rotationQuaternion
  26636. * - setPivotMatrix
  26637. * - scaling
  26638. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26639. * Warning : this method is not supported for Line mesh and LineSystem
  26640. */
  26641. Mesh.prototype.createInstance = function (name) {
  26642. return new BABYLON.InstancedMesh(name, this);
  26643. };
  26644. /**
  26645. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26646. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26647. * This method returns the Mesh.
  26648. */
  26649. Mesh.prototype.synchronizeInstances = function () {
  26650. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26651. var instance = this.instances[instanceIndex];
  26652. instance._syncSubMeshes();
  26653. }
  26654. return this;
  26655. };
  26656. /**
  26657. * Simplify the mesh according to the given array of settings.
  26658. * Function will return immediately and will simplify async. It returns the Mesh.
  26659. * @param settings a collection of simplification settings.
  26660. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26661. * @param type the type of simplification to run.
  26662. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26663. */
  26664. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26665. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26666. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26667. this.getScene().simplificationQueue.addTask({
  26668. settings: settings,
  26669. parallelProcessing: parallelProcessing,
  26670. mesh: this,
  26671. simplificationType: simplificationType,
  26672. successCallback: successCallback
  26673. });
  26674. return this;
  26675. };
  26676. /**
  26677. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26678. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26679. * This should be used together with the simplification to avoid disappearing triangles.
  26680. * Returns the Mesh.
  26681. * @param successCallback an optional success callback to be called after the optimization finished.
  26682. */
  26683. Mesh.prototype.optimizeIndices = function (successCallback) {
  26684. var _this = this;
  26685. var indices = this.getIndices();
  26686. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26687. if (!positions || !indices) {
  26688. return this;
  26689. }
  26690. var vectorPositions = new Array();
  26691. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26692. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26693. }
  26694. var dupes = new Array();
  26695. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26696. var realPos = vectorPositions.length - 1 - iteration;
  26697. var testedPosition = vectorPositions[realPos];
  26698. for (var j = 0; j < realPos; ++j) {
  26699. var againstPosition = vectorPositions[j];
  26700. if (testedPosition.equals(againstPosition)) {
  26701. dupes[realPos] = j;
  26702. break;
  26703. }
  26704. }
  26705. }, function () {
  26706. for (var i = 0; i < indices.length; ++i) {
  26707. indices[i] = dupes[indices[i]] || indices[i];
  26708. }
  26709. //indices are now reordered
  26710. var originalSubMeshes = _this.subMeshes.slice(0);
  26711. _this.setIndices(indices);
  26712. _this.subMeshes = originalSubMeshes;
  26713. if (successCallback) {
  26714. successCallback(_this);
  26715. }
  26716. });
  26717. return this;
  26718. };
  26719. Mesh.prototype.serialize = function (serializationObject) {
  26720. serializationObject.name = this.name;
  26721. serializationObject.id = this.id;
  26722. serializationObject.type = this.getClassName();
  26723. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26724. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26725. }
  26726. serializationObject.position = this.position.asArray();
  26727. if (this.rotationQuaternion) {
  26728. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26729. }
  26730. else if (this.rotation) {
  26731. serializationObject.rotation = this.rotation.asArray();
  26732. }
  26733. serializationObject.scaling = this.scaling.asArray();
  26734. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26735. serializationObject.isEnabled = this.isEnabled(false);
  26736. serializationObject.isVisible = this.isVisible;
  26737. serializationObject.infiniteDistance = this.infiniteDistance;
  26738. serializationObject.pickable = this.isPickable;
  26739. serializationObject.receiveShadows = this.receiveShadows;
  26740. serializationObject.billboardMode = this.billboardMode;
  26741. serializationObject.visibility = this.visibility;
  26742. serializationObject.checkCollisions = this.checkCollisions;
  26743. serializationObject.isBlocker = this.isBlocker;
  26744. // Parent
  26745. if (this.parent) {
  26746. serializationObject.parentId = this.parent.id;
  26747. }
  26748. // Geometry
  26749. serializationObject.isUnIndexed = this.isUnIndexed;
  26750. var geometry = this._geometry;
  26751. if (geometry) {
  26752. var geometryId = geometry.id;
  26753. serializationObject.geometryId = geometryId;
  26754. // SubMeshes
  26755. serializationObject.subMeshes = [];
  26756. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26757. var subMesh = this.subMeshes[subIndex];
  26758. serializationObject.subMeshes.push({
  26759. materialIndex: subMesh.materialIndex,
  26760. verticesStart: subMesh.verticesStart,
  26761. verticesCount: subMesh.verticesCount,
  26762. indexStart: subMesh.indexStart,
  26763. indexCount: subMesh.indexCount
  26764. });
  26765. }
  26766. }
  26767. // Material
  26768. if (this.material) {
  26769. serializationObject.materialId = this.material.id;
  26770. }
  26771. else {
  26772. this.material = null;
  26773. }
  26774. // Morph targets
  26775. if (this.morphTargetManager) {
  26776. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26777. }
  26778. // Skeleton
  26779. if (this.skeleton) {
  26780. serializationObject.skeletonId = this.skeleton.id;
  26781. }
  26782. // Physics
  26783. //TODO implement correct serialization for physics impostors.
  26784. var impostor = this.getPhysicsImpostor();
  26785. if (impostor) {
  26786. serializationObject.physicsMass = impostor.getParam("mass");
  26787. serializationObject.physicsFriction = impostor.getParam("friction");
  26788. serializationObject.physicsRestitution = impostor.getParam("mass");
  26789. serializationObject.physicsImpostor = impostor.type;
  26790. }
  26791. // Metadata
  26792. if (this.metadata) {
  26793. serializationObject.metadata = this.metadata;
  26794. }
  26795. // Instances
  26796. serializationObject.instances = [];
  26797. for (var index = 0; index < this.instances.length; index++) {
  26798. var instance = this.instances[index];
  26799. var serializationInstance = {
  26800. name: instance.name,
  26801. id: instance.id,
  26802. position: instance.position.asArray(),
  26803. scaling: instance.scaling.asArray()
  26804. };
  26805. if (instance.rotationQuaternion) {
  26806. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26807. }
  26808. else if (instance.rotation) {
  26809. serializationInstance.rotation = instance.rotation.asArray();
  26810. }
  26811. serializationObject.instances.push(serializationInstance);
  26812. // Animations
  26813. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26814. serializationInstance.ranges = instance.serializeAnimationRanges();
  26815. }
  26816. //
  26817. // Animations
  26818. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26819. serializationObject.ranges = this.serializeAnimationRanges();
  26820. // Layer mask
  26821. serializationObject.layerMask = this.layerMask;
  26822. // Alpha
  26823. serializationObject.alphaIndex = this.alphaIndex;
  26824. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26825. // Overlay
  26826. serializationObject.overlayAlpha = this.overlayAlpha;
  26827. serializationObject.overlayColor = this.overlayColor.asArray();
  26828. serializationObject.renderOverlay = this.renderOverlay;
  26829. // Fog
  26830. serializationObject.applyFog = this.applyFog;
  26831. // Action Manager
  26832. if (this.actionManager) {
  26833. serializationObject.actions = this.actionManager.serialize(this.name);
  26834. }
  26835. };
  26836. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26837. if (!this.geometry) {
  26838. return;
  26839. }
  26840. this._markSubMeshesAsAttributesDirty();
  26841. var morphTargetManager = this._morphTargetManager;
  26842. if (morphTargetManager && morphTargetManager.vertexCount) {
  26843. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26844. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26845. this.morphTargetManager = null;
  26846. return;
  26847. }
  26848. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26849. var morphTarget = morphTargetManager.getActiveTarget(index);
  26850. var positions = morphTarget.getPositions();
  26851. if (!positions) {
  26852. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26853. return;
  26854. }
  26855. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26856. var normals = morphTarget.getNormals();
  26857. if (normals) {
  26858. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26859. }
  26860. var tangents = morphTarget.getTangents();
  26861. if (tangents) {
  26862. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26863. }
  26864. }
  26865. }
  26866. else {
  26867. var index = 0;
  26868. // Positions
  26869. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26870. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26871. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26872. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26873. }
  26874. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26875. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26876. }
  26877. index++;
  26878. }
  26879. }
  26880. };
  26881. // Statics
  26882. /**
  26883. * Returns a new Mesh object parsed from the source provided.
  26884. * The parameter `parsedMesh` is the source.
  26885. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26886. */
  26887. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26888. var mesh;
  26889. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26890. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26891. }
  26892. else {
  26893. mesh = new Mesh(parsedMesh.name, scene);
  26894. }
  26895. mesh.id = parsedMesh.id;
  26896. if (BABYLON.Tags) {
  26897. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26898. }
  26899. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26900. if (parsedMesh.metadata !== undefined) {
  26901. mesh.metadata = parsedMesh.metadata;
  26902. }
  26903. if (parsedMesh.rotationQuaternion) {
  26904. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26905. }
  26906. else if (parsedMesh.rotation) {
  26907. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26908. }
  26909. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26910. if (parsedMesh.localMatrix) {
  26911. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26912. }
  26913. else if (parsedMesh.pivotMatrix) {
  26914. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26915. }
  26916. mesh.setEnabled(parsedMesh.isEnabled);
  26917. mesh.isVisible = parsedMesh.isVisible;
  26918. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26919. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26920. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26921. if (parsedMesh.applyFog !== undefined) {
  26922. mesh.applyFog = parsedMesh.applyFog;
  26923. }
  26924. if (parsedMesh.pickable !== undefined) {
  26925. mesh.isPickable = parsedMesh.pickable;
  26926. }
  26927. if (parsedMesh.alphaIndex !== undefined) {
  26928. mesh.alphaIndex = parsedMesh.alphaIndex;
  26929. }
  26930. mesh.receiveShadows = parsedMesh.receiveShadows;
  26931. mesh.billboardMode = parsedMesh.billboardMode;
  26932. if (parsedMesh.visibility !== undefined) {
  26933. mesh.visibility = parsedMesh.visibility;
  26934. }
  26935. mesh.checkCollisions = parsedMesh.checkCollisions;
  26936. if (parsedMesh.isBlocker !== undefined) {
  26937. mesh.isBlocker = parsedMesh.isBlocker;
  26938. }
  26939. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26940. // freezeWorldMatrix
  26941. if (parsedMesh.freezeWorldMatrix) {
  26942. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26943. }
  26944. // Parent
  26945. if (parsedMesh.parentId) {
  26946. mesh._waitingParentId = parsedMesh.parentId;
  26947. }
  26948. // Actions
  26949. if (parsedMesh.actions !== undefined) {
  26950. mesh._waitingActions = parsedMesh.actions;
  26951. }
  26952. // Overlay
  26953. if (parsedMesh.overlayAlpha !== undefined) {
  26954. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26955. }
  26956. if (parsedMesh.overlayColor !== undefined) {
  26957. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26958. }
  26959. if (parsedMesh.renderOverlay !== undefined) {
  26960. mesh.renderOverlay = parsedMesh.renderOverlay;
  26961. }
  26962. // Geometry
  26963. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26964. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26965. if (parsedMesh.delayLoadingFile) {
  26966. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26967. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26968. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26969. if (parsedMesh._binaryInfo) {
  26970. mesh._binaryInfo = parsedMesh._binaryInfo;
  26971. }
  26972. mesh._delayInfo = [];
  26973. if (parsedMesh.hasUVs) {
  26974. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26975. }
  26976. if (parsedMesh.hasUVs2) {
  26977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26978. }
  26979. if (parsedMesh.hasUVs3) {
  26980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26981. }
  26982. if (parsedMesh.hasUVs4) {
  26983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26984. }
  26985. if (parsedMesh.hasUVs5) {
  26986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26987. }
  26988. if (parsedMesh.hasUVs6) {
  26989. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26990. }
  26991. if (parsedMesh.hasColors) {
  26992. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26993. }
  26994. if (parsedMesh.hasMatricesIndices) {
  26995. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26996. }
  26997. if (parsedMesh.hasMatricesWeights) {
  26998. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26999. }
  27000. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  27001. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27002. mesh._checkDelayState();
  27003. }
  27004. }
  27005. else {
  27006. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  27007. }
  27008. // Material
  27009. if (parsedMesh.materialId) {
  27010. mesh.setMaterialByID(parsedMesh.materialId);
  27011. }
  27012. else {
  27013. mesh.material = null;
  27014. }
  27015. // Morph targets
  27016. if (parsedMesh.morphTargetManagerId > -1) {
  27017. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27018. }
  27019. // Skeleton
  27020. if (parsedMesh.skeletonId > -1) {
  27021. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27022. if (parsedMesh.numBoneInfluencers) {
  27023. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27024. }
  27025. }
  27026. // Animations
  27027. if (parsedMesh.animations) {
  27028. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27029. var parsedAnimation = parsedMesh.animations[animationIndex];
  27030. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27031. }
  27032. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27033. }
  27034. if (parsedMesh.autoAnimate) {
  27035. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27036. }
  27037. // Layer Mask
  27038. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27039. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27040. }
  27041. else {
  27042. mesh.layerMask = 0x0FFFFFFF;
  27043. }
  27044. // Physics
  27045. if (parsedMesh.physicsImpostor) {
  27046. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27047. mass: parsedMesh.physicsMass,
  27048. friction: parsedMesh.physicsFriction,
  27049. restitution: parsedMesh.physicsRestitution
  27050. }, scene);
  27051. }
  27052. // Instances
  27053. if (parsedMesh.instances) {
  27054. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27055. var parsedInstance = parsedMesh.instances[index];
  27056. var instance = mesh.createInstance(parsedInstance.name);
  27057. if (parsedInstance.id) {
  27058. instance.id = parsedInstance.id;
  27059. }
  27060. if (BABYLON.Tags) {
  27061. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27062. }
  27063. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27064. if (parsedInstance.parentId) {
  27065. instance._waitingParentId = parsedInstance.parentId;
  27066. }
  27067. if (parsedInstance.rotationQuaternion) {
  27068. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27069. }
  27070. else if (parsedInstance.rotation) {
  27071. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27072. }
  27073. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27074. instance.checkCollisions = mesh.checkCollisions;
  27075. if (parsedMesh.animations) {
  27076. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27077. parsedAnimation = parsedMesh.animations[animationIndex];
  27078. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27079. }
  27080. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27081. }
  27082. }
  27083. }
  27084. return mesh;
  27085. };
  27086. /**
  27087. * Creates a ribbon mesh.
  27088. * Please consider using the same method from the MeshBuilder class instead.
  27089. * 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.
  27090. *
  27091. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27092. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27093. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27094. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27095. * 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.
  27096. * 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.
  27097. * 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
  27098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27101. */
  27102. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27103. if (closeArray === void 0) { closeArray = false; }
  27104. if (updatable === void 0) { updatable = false; }
  27105. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27106. pathArray: pathArray,
  27107. closeArray: closeArray,
  27108. closePath: closePath,
  27109. offset: offset,
  27110. updatable: updatable,
  27111. sideOrientation: sideOrientation,
  27112. instance: instance
  27113. }, scene);
  27114. };
  27115. /**
  27116. * Creates a plane polygonal mesh. By default, this is a disc.
  27117. * Please consider using the same method from the MeshBuilder class instead.
  27118. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27119. * 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.
  27120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27123. */
  27124. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27125. if (scene === void 0) { scene = null; }
  27126. var options = {
  27127. radius: radius,
  27128. tessellation: tessellation,
  27129. sideOrientation: sideOrientation,
  27130. updatable: updatable
  27131. };
  27132. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27133. };
  27134. /**
  27135. * Creates a box mesh.
  27136. * Please consider using the same method from the MeshBuilder class instead.
  27137. * The parameter `size` sets the size (float) of each box side (default 1).
  27138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27141. */
  27142. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27143. if (scene === void 0) { scene = null; }
  27144. var options = {
  27145. size: size,
  27146. sideOrientation: sideOrientation,
  27147. updatable: updatable
  27148. };
  27149. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27150. };
  27151. /**
  27152. * Creates a sphere mesh.
  27153. * Please consider using the same method from the MeshBuilder class instead.
  27154. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27155. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27159. */
  27160. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27161. var options = {
  27162. segments: segments,
  27163. diameterX: diameter,
  27164. diameterY: diameter,
  27165. diameterZ: diameter,
  27166. sideOrientation: sideOrientation,
  27167. updatable: updatable
  27168. };
  27169. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27170. };
  27171. /**
  27172. * Creates a cylinder or a cone mesh.
  27173. * Please consider using the same method from the MeshBuilder class instead.
  27174. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27175. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27176. * 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.
  27177. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27178. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27182. */
  27183. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27184. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27185. if (scene !== undefined) {
  27186. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27187. updatable = scene;
  27188. }
  27189. scene = subdivisions;
  27190. subdivisions = 1;
  27191. }
  27192. var options = {
  27193. height: height,
  27194. diameterTop: diameterTop,
  27195. diameterBottom: diameterBottom,
  27196. tessellation: tessellation,
  27197. subdivisions: subdivisions,
  27198. sideOrientation: sideOrientation,
  27199. updatable: updatable
  27200. };
  27201. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27202. };
  27203. // Torus (Code from SharpDX.org)
  27204. /**
  27205. * Creates a torus mesh.
  27206. * Please consider using the same method from the MeshBuilder class instead.
  27207. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27208. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27209. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27211. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27213. */
  27214. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27215. var options = {
  27216. diameter: diameter,
  27217. thickness: thickness,
  27218. tessellation: tessellation,
  27219. sideOrientation: sideOrientation,
  27220. updatable: updatable
  27221. };
  27222. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27223. };
  27224. /**
  27225. * Creates a torus knot mesh.
  27226. * Please consider using the same method from the MeshBuilder class instead.
  27227. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27228. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27229. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27230. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27231. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27234. */
  27235. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27236. var options = {
  27237. radius: radius,
  27238. tube: tube,
  27239. radialSegments: radialSegments,
  27240. tubularSegments: tubularSegments,
  27241. p: p,
  27242. q: q,
  27243. sideOrientation: sideOrientation,
  27244. updatable: updatable
  27245. };
  27246. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27247. };
  27248. /**
  27249. * Creates a line mesh.
  27250. * Please consider using the same method from the MeshBuilder class instead.
  27251. * 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.
  27252. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27253. * The parameter `points` is an array successive Vector3.
  27254. * 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
  27255. * When updating an instance, remember that only point positions can change, not the number of points.
  27256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27257. */
  27258. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27259. if (scene === void 0) { scene = null; }
  27260. if (updatable === void 0) { updatable = false; }
  27261. if (instance === void 0) { instance = null; }
  27262. var options = {
  27263. points: points,
  27264. updatable: updatable,
  27265. instance: instance
  27266. };
  27267. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27268. };
  27269. /**
  27270. * Creates a dashed line mesh.
  27271. * Please consider using the same method from the MeshBuilder class instead.
  27272. * 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.
  27273. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27274. * The parameter `points` is an array successive Vector3.
  27275. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27276. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27277. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27278. * 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
  27279. * When updating an instance, remember that only point positions can change, not the number of points.
  27280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27281. */
  27282. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27283. if (scene === void 0) { scene = null; }
  27284. var options = {
  27285. points: points,
  27286. dashSize: dashSize,
  27287. gapSize: gapSize,
  27288. dashNb: dashNb,
  27289. updatable: updatable,
  27290. instance: instance
  27291. };
  27292. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27293. };
  27294. /**
  27295. * Creates a polygon mesh.
  27296. * Please consider using the same method from the MeshBuilder class instead.
  27297. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27298. * 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.
  27299. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27301. * Remember you can only change the shape positions, not their number when updating a polygon.
  27302. */
  27303. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27304. var options = {
  27305. shape: shape,
  27306. holes: holes,
  27307. updatable: updatable,
  27308. sideOrientation: sideOrientation
  27309. };
  27310. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27311. };
  27312. /**
  27313. * Creates an extruded polygon mesh, with depth in the Y direction.
  27314. * Please consider using the same method from the MeshBuilder class instead.
  27315. */
  27316. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27317. var options = {
  27318. shape: shape,
  27319. holes: holes,
  27320. depth: depth,
  27321. updatable: updatable,
  27322. sideOrientation: sideOrientation
  27323. };
  27324. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27325. };
  27326. /**
  27327. * Creates an extruded shape mesh.
  27328. * 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.
  27329. * Please consider using the same method from the MeshBuilder class instead.
  27330. *
  27331. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27332. * 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
  27333. * extruded along the Z axis.
  27334. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27335. * 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.
  27336. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27337. * 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
  27338. * 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
  27339. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27343. */
  27344. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27345. if (scene === void 0) { scene = null; }
  27346. var options = {
  27347. shape: shape,
  27348. path: path,
  27349. scale: scale,
  27350. rotation: rotation,
  27351. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27352. sideOrientation: sideOrientation,
  27353. instance: instance,
  27354. updatable: updatable
  27355. };
  27356. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27357. };
  27358. /**
  27359. * Creates an custom extruded shape mesh.
  27360. * 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.
  27361. * Please consider using the same method from the MeshBuilder class instead.
  27362. *
  27363. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27364. * 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
  27365. * extruded along the Z axis.
  27366. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27367. * 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
  27368. * and the distance of this point from the begining of the path :
  27369. * ```javascript
  27370. * var rotationFunction = function(i, distance) {
  27371. * // do things
  27372. * return rotationValue; }
  27373. * ```
  27374. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27375. * 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
  27376. * and the distance of this point from the begining of the path :
  27377. * ```javascript
  27378. * var scaleFunction = function(i, distance) {
  27379. * // do things
  27380. * return scaleValue;}
  27381. * ```
  27382. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27383. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27384. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27385. * 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
  27386. * 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
  27387. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27391. */
  27392. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27393. var options = {
  27394. shape: shape,
  27395. path: path,
  27396. scaleFunction: scaleFunction,
  27397. rotationFunction: rotationFunction,
  27398. ribbonCloseArray: ribbonCloseArray,
  27399. ribbonClosePath: ribbonClosePath,
  27400. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27401. sideOrientation: sideOrientation,
  27402. instance: instance,
  27403. updatable: updatable
  27404. };
  27405. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27406. };
  27407. /**
  27408. * Creates lathe mesh.
  27409. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27410. * Please consider using the same method from the MeshBuilder class instead.
  27411. * 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
  27412. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27413. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27414. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27418. */
  27419. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27420. var options = {
  27421. shape: shape,
  27422. radius: radius,
  27423. tessellation: tessellation,
  27424. sideOrientation: sideOrientation,
  27425. updatable: updatable
  27426. };
  27427. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27428. };
  27429. /**
  27430. * Creates a plane mesh.
  27431. * Please consider using the same method from the MeshBuilder class instead.
  27432. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27436. */
  27437. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27438. var options = {
  27439. size: size,
  27440. width: size,
  27441. height: size,
  27442. sideOrientation: sideOrientation,
  27443. updatable: updatable
  27444. };
  27445. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27446. };
  27447. /**
  27448. * Creates a ground mesh.
  27449. * Please consider using the same method from the MeshBuilder class instead.
  27450. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27451. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27453. */
  27454. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27455. var options = {
  27456. width: width,
  27457. height: height,
  27458. subdivisions: subdivisions,
  27459. updatable: updatable
  27460. };
  27461. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27462. };
  27463. /**
  27464. * Creates a tiled ground mesh.
  27465. * Please consider using the same method from the MeshBuilder class instead.
  27466. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27467. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27468. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27469. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27470. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27471. * numbers of subdivisions on the ground width and height of each tile.
  27472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27473. */
  27474. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27475. var options = {
  27476. xmin: xmin,
  27477. zmin: zmin,
  27478. xmax: xmax,
  27479. zmax: zmax,
  27480. subdivisions: subdivisions,
  27481. precision: precision,
  27482. updatable: updatable
  27483. };
  27484. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27485. };
  27486. /**
  27487. * Creates a ground mesh from a height map.
  27488. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27489. * Please consider using the same method from the MeshBuilder class instead.
  27490. * The parameter `url` sets the URL of the height map image resource.
  27491. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27492. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27493. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27494. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27495. * 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).
  27496. * This function is passed the newly built mesh :
  27497. * ```javascript
  27498. * function(mesh) { // do things
  27499. * return; }
  27500. * ```
  27501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27502. */
  27503. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27504. var options = {
  27505. width: width,
  27506. height: height,
  27507. subdivisions: subdivisions,
  27508. minHeight: minHeight,
  27509. maxHeight: maxHeight,
  27510. updatable: updatable,
  27511. onReady: onReady
  27512. };
  27513. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27514. };
  27515. /**
  27516. * Creates a tube mesh.
  27517. * 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.
  27518. * Please consider using the same method from the MeshBuilder class instead.
  27519. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27520. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27521. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27522. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27523. * 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.
  27524. * It must return a radius value (positive float) :
  27525. * ```javascript
  27526. * var radiusFunction = function(i, distance) {
  27527. * // do things
  27528. * return radius; }
  27529. * ```
  27530. * 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
  27531. * 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
  27532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27535. */
  27536. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27537. var options = {
  27538. path: path,
  27539. radius: radius,
  27540. tessellation: tessellation,
  27541. radiusFunction: radiusFunction,
  27542. arc: 1,
  27543. cap: cap,
  27544. updatable: updatable,
  27545. sideOrientation: sideOrientation,
  27546. instance: instance
  27547. };
  27548. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27549. };
  27550. /**
  27551. * Creates a polyhedron mesh.
  27552. * Please consider using the same method from the MeshBuilder class instead.
  27553. * 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
  27554. * to choose the wanted type.
  27555. * The parameter `size` (positive float, default 1) sets the polygon size.
  27556. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27557. * 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`.
  27558. * 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
  27559. * 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)`).
  27560. * 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
  27561. * 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.
  27562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27565. */
  27566. Mesh.CreatePolyhedron = function (name, options, scene) {
  27567. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27568. };
  27569. /**
  27570. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27571. * Please consider using the same method from the MeshBuilder class instead.
  27572. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27573. * 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`).
  27574. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27575. * 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.
  27576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27579. */
  27580. Mesh.CreateIcoSphere = function (name, options, scene) {
  27581. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27582. };
  27583. /**
  27584. * Creates a decal mesh.
  27585. * Please consider using the same method from the MeshBuilder class instead.
  27586. * 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.
  27587. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27588. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27589. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27590. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27591. */
  27592. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27593. var options = {
  27594. position: position,
  27595. normal: normal,
  27596. size: size,
  27597. angle: angle
  27598. };
  27599. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27600. };
  27601. // Skeletons
  27602. /**
  27603. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27604. */
  27605. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27606. if (!this._sourcePositions) {
  27607. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27608. if (!source) {
  27609. return this._sourcePositions;
  27610. }
  27611. this._sourcePositions = new Float32Array(source);
  27612. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27613. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27614. }
  27615. }
  27616. return this._sourcePositions;
  27617. };
  27618. /**
  27619. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27620. */
  27621. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27622. if (!this._sourceNormals) {
  27623. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27624. if (!source) {
  27625. return this._sourceNormals;
  27626. }
  27627. this._sourceNormals = new Float32Array(source);
  27628. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27629. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27630. }
  27631. }
  27632. return this._sourceNormals;
  27633. };
  27634. /**
  27635. * Updates the vertex buffer by applying transformation from the bones.
  27636. * Returns the Mesh.
  27637. *
  27638. * @param {skeleton} skeleton to apply
  27639. */
  27640. Mesh.prototype.applySkeleton = function (skeleton) {
  27641. if (!this.geometry) {
  27642. return this;
  27643. }
  27644. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27645. return this;
  27646. }
  27647. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27649. return this;
  27650. }
  27651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27652. return this;
  27653. }
  27654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27655. return this;
  27656. }
  27657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27658. return this;
  27659. }
  27660. if (!this._sourcePositions) {
  27661. var submeshes = this.subMeshes.slice();
  27662. this.setPositionsForCPUSkinning();
  27663. this.subMeshes = submeshes;
  27664. }
  27665. if (!this._sourceNormals) {
  27666. this.setNormalsForCPUSkinning();
  27667. }
  27668. // positionsData checks for not being Float32Array will only pass at most once
  27669. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27670. if (!positionsData) {
  27671. return this;
  27672. }
  27673. if (!(positionsData instanceof Float32Array)) {
  27674. positionsData = new Float32Array(positionsData);
  27675. }
  27676. // normalsData checks for not being Float32Array will only pass at most once
  27677. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27678. if (!normalsData) {
  27679. return this;
  27680. }
  27681. if (!(normalsData instanceof Float32Array)) {
  27682. normalsData = new Float32Array(normalsData);
  27683. }
  27684. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27685. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27686. if (!matricesWeightsData || !matricesIndicesData) {
  27687. return this;
  27688. }
  27689. var needExtras = this.numBoneInfluencers > 4;
  27690. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27691. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27692. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27693. var tempVector3 = BABYLON.Vector3.Zero();
  27694. var finalMatrix = new BABYLON.Matrix();
  27695. var tempMatrix = new BABYLON.Matrix();
  27696. var matWeightIdx = 0;
  27697. var inf;
  27698. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27699. var weight;
  27700. for (inf = 0; inf < 4; inf++) {
  27701. weight = matricesWeightsData[matWeightIdx + inf];
  27702. if (weight > 0) {
  27703. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27704. finalMatrix.addToSelf(tempMatrix);
  27705. }
  27706. else
  27707. break;
  27708. }
  27709. if (needExtras) {
  27710. for (inf = 0; inf < 4; inf++) {
  27711. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27712. if (weight > 0) {
  27713. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27714. finalMatrix.addToSelf(tempMatrix);
  27715. }
  27716. else
  27717. break;
  27718. }
  27719. }
  27720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27721. tempVector3.toArray(positionsData, index);
  27722. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27723. tempVector3.toArray(normalsData, index);
  27724. finalMatrix.reset();
  27725. }
  27726. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27727. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27728. return this;
  27729. };
  27730. // Tools
  27731. /**
  27732. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27733. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27734. */
  27735. Mesh.MinMax = function (meshes) {
  27736. var minVector = null;
  27737. var maxVector = null;
  27738. meshes.forEach(function (mesh, index, array) {
  27739. var boundingInfo = mesh.getBoundingInfo();
  27740. var boundingBox = boundingInfo.boundingBox;
  27741. if (!minVector || !maxVector) {
  27742. minVector = boundingBox.minimumWorld;
  27743. maxVector = boundingBox.maximumWorld;
  27744. }
  27745. else {
  27746. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27747. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27748. }
  27749. });
  27750. if (!minVector || !maxVector) {
  27751. return {
  27752. min: BABYLON.Vector3.Zero(),
  27753. max: BABYLON.Vector3.Zero()
  27754. };
  27755. }
  27756. return {
  27757. min: minVector,
  27758. max: maxVector
  27759. };
  27760. };
  27761. /**
  27762. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27763. */
  27764. Mesh.Center = function (meshesOrMinMaxVector) {
  27765. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27766. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27767. };
  27768. /**
  27769. * Merge the array of meshes into a single mesh for performance reasons.
  27770. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27771. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27772. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27773. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27774. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27775. */
  27776. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27777. if (disposeSource === void 0) { disposeSource = true; }
  27778. var index;
  27779. if (!allow32BitsIndices) {
  27780. var totalVertices = 0;
  27781. // Counting vertices
  27782. for (index = 0; index < meshes.length; index++) {
  27783. if (meshes[index]) {
  27784. totalVertices += meshes[index].getTotalVertices();
  27785. if (totalVertices > 65536) {
  27786. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27787. return null;
  27788. }
  27789. }
  27790. }
  27791. }
  27792. // Merge
  27793. var vertexData = null;
  27794. var otherVertexData;
  27795. var indiceArray = new Array();
  27796. var source = null;
  27797. for (index = 0; index < meshes.length; index++) {
  27798. if (meshes[index]) {
  27799. meshes[index].computeWorldMatrix(true);
  27800. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27801. otherVertexData.transform(meshes[index].getWorldMatrix());
  27802. if (vertexData) {
  27803. vertexData.merge(otherVertexData);
  27804. }
  27805. else {
  27806. vertexData = otherVertexData;
  27807. source = meshes[index];
  27808. }
  27809. if (subdivideWithSubMeshes) {
  27810. indiceArray.push(meshes[index].getTotalIndices());
  27811. }
  27812. }
  27813. }
  27814. source = source;
  27815. if (!meshSubclass) {
  27816. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27817. }
  27818. vertexData.applyToMesh(meshSubclass);
  27819. // Setting properties
  27820. meshSubclass.material = source.material;
  27821. meshSubclass.checkCollisions = source.checkCollisions;
  27822. // Cleaning
  27823. if (disposeSource) {
  27824. for (index = 0; index < meshes.length; index++) {
  27825. if (meshes[index]) {
  27826. meshes[index].dispose();
  27827. }
  27828. }
  27829. }
  27830. // Subdivide
  27831. if (subdivideWithSubMeshes) {
  27832. //-- Suppresions du submesh global
  27833. meshSubclass.releaseSubMeshes();
  27834. index = 0;
  27835. var offset = 0;
  27836. //-- aplique la subdivision en fonction du tableau d'indices
  27837. while (index < indiceArray.length) {
  27838. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27839. offset += indiceArray[index];
  27840. index++;
  27841. }
  27842. }
  27843. return meshSubclass;
  27844. };
  27845. // Consts
  27846. Mesh._FRONTSIDE = 0;
  27847. Mesh._BACKSIDE = 1;
  27848. Mesh._DOUBLESIDE = 2;
  27849. Mesh._DEFAULTSIDE = 0;
  27850. Mesh._NO_CAP = 0;
  27851. Mesh._CAP_START = 1;
  27852. Mesh._CAP_END = 2;
  27853. Mesh._CAP_ALL = 3;
  27854. return Mesh;
  27855. }(BABYLON.AbstractMesh));
  27856. BABYLON.Mesh = Mesh;
  27857. })(BABYLON || (BABYLON = {}));
  27858. //# sourceMappingURL=babylon.mesh.js.map
  27859. var BABYLON;
  27860. (function (BABYLON) {
  27861. var BaseSubMesh = /** @class */ (function () {
  27862. function BaseSubMesh() {
  27863. }
  27864. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27865. get: function () {
  27866. return this._materialEffect;
  27867. },
  27868. enumerable: true,
  27869. configurable: true
  27870. });
  27871. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27872. if (defines === void 0) { defines = null; }
  27873. if (this._materialEffect === effect) {
  27874. if (!effect) {
  27875. this._materialDefines = null;
  27876. }
  27877. return;
  27878. }
  27879. this._materialDefines = defines;
  27880. this._materialEffect = effect;
  27881. };
  27882. return BaseSubMesh;
  27883. }());
  27884. BABYLON.BaseSubMesh = BaseSubMesh;
  27885. var SubMesh = /** @class */ (function (_super) {
  27886. __extends(SubMesh, _super);
  27887. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27888. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27889. var _this = _super.call(this) || this;
  27890. _this.materialIndex = materialIndex;
  27891. _this.verticesStart = verticesStart;
  27892. _this.verticesCount = verticesCount;
  27893. _this.indexStart = indexStart;
  27894. _this.indexCount = indexCount;
  27895. _this._renderId = 0;
  27896. _this._mesh = mesh;
  27897. _this._renderingMesh = renderingMesh || mesh;
  27898. mesh.subMeshes.push(_this);
  27899. _this._trianglePlanes = [];
  27900. _this._id = mesh.subMeshes.length - 1;
  27901. if (createBoundingBox) {
  27902. _this.refreshBoundingInfo();
  27903. mesh.computeWorldMatrix(true);
  27904. }
  27905. return _this;
  27906. }
  27907. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27908. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27909. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27910. };
  27911. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27912. get: function () {
  27913. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. /**
  27919. * Returns the submesh BoudingInfo object.
  27920. */
  27921. SubMesh.prototype.getBoundingInfo = function () {
  27922. if (this.IsGlobal) {
  27923. return this._mesh.getBoundingInfo();
  27924. }
  27925. return this._boundingInfo;
  27926. };
  27927. /**
  27928. * Sets the submesh BoundingInfo.
  27929. * Return the SubMesh.
  27930. */
  27931. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27932. this._boundingInfo = boundingInfo;
  27933. return this;
  27934. };
  27935. /**
  27936. * Returns the mesh of the current submesh.
  27937. */
  27938. SubMesh.prototype.getMesh = function () {
  27939. return this._mesh;
  27940. };
  27941. /**
  27942. * Returns the rendering mesh of the submesh.
  27943. */
  27944. SubMesh.prototype.getRenderingMesh = function () {
  27945. return this._renderingMesh;
  27946. };
  27947. /**
  27948. * Returns the submesh material.
  27949. */
  27950. SubMesh.prototype.getMaterial = function () {
  27951. var rootMaterial = this._renderingMesh.material;
  27952. if (rootMaterial === null || rootMaterial === undefined) {
  27953. return this._mesh.getScene().defaultMaterial;
  27954. }
  27955. else if (rootMaterial.getSubMaterial) {
  27956. var multiMaterial = rootMaterial;
  27957. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27958. if (this._currentMaterial !== effectiveMaterial) {
  27959. this._currentMaterial = effectiveMaterial;
  27960. this._materialDefines = null;
  27961. }
  27962. return effectiveMaterial;
  27963. }
  27964. return rootMaterial;
  27965. };
  27966. // Methods
  27967. /**
  27968. * Sets a new updated BoundingInfo object to the submesh.
  27969. * Returns the SubMesh.
  27970. */
  27971. SubMesh.prototype.refreshBoundingInfo = function () {
  27972. this._lastColliderWorldVertices = null;
  27973. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27974. return this;
  27975. }
  27976. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27977. if (!data) {
  27978. this._boundingInfo = this._mesh.getBoundingInfo();
  27979. return this;
  27980. }
  27981. var indices = this._renderingMesh.getIndices();
  27982. var extend;
  27983. //is this the only submesh?
  27984. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27985. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27986. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27987. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27988. }
  27989. else {
  27990. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27991. }
  27992. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27993. return this;
  27994. };
  27995. SubMesh.prototype._checkCollision = function (collider) {
  27996. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27997. return boundingInfo._checkCollision(collider);
  27998. };
  27999. /**
  28000. * Updates the submesh BoundingInfo.
  28001. * Returns the Submesh.
  28002. */
  28003. SubMesh.prototype.updateBoundingInfo = function (world) {
  28004. var boundingInfo = this.getBoundingInfo();
  28005. if (!boundingInfo) {
  28006. this.refreshBoundingInfo();
  28007. boundingInfo = this.getBoundingInfo();
  28008. }
  28009. boundingInfo.update(world);
  28010. return this;
  28011. };
  28012. /**
  28013. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28014. * Boolean returned.
  28015. */
  28016. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28017. var boundingInfo = this.getBoundingInfo();
  28018. if (!boundingInfo) {
  28019. return false;
  28020. }
  28021. return boundingInfo.isInFrustum(frustumPlanes);
  28022. };
  28023. /**
  28024. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28025. * Boolean returned.
  28026. */
  28027. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28028. var boundingInfo = this.getBoundingInfo();
  28029. if (!boundingInfo) {
  28030. return false;
  28031. }
  28032. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28033. };
  28034. /**
  28035. * Renders the submesh.
  28036. * Returns it.
  28037. */
  28038. SubMesh.prototype.render = function (enableAlphaMode) {
  28039. this._renderingMesh.render(this, enableAlphaMode);
  28040. return this;
  28041. };
  28042. /**
  28043. * Returns a new Index Buffer.
  28044. * Type returned : WebGLBuffer.
  28045. */
  28046. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28047. if (!this._linesIndexBuffer) {
  28048. var linesIndices = [];
  28049. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28050. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28051. }
  28052. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28053. this.linesIndexCount = linesIndices.length;
  28054. }
  28055. return this._linesIndexBuffer;
  28056. };
  28057. /**
  28058. * True is the passed Ray intersects the submesh bounding box.
  28059. * Boolean returned.
  28060. */
  28061. SubMesh.prototype.canIntersects = function (ray) {
  28062. var boundingInfo = this.getBoundingInfo();
  28063. if (!boundingInfo) {
  28064. return false;
  28065. }
  28066. return ray.intersectsBox(boundingInfo.boundingBox);
  28067. };
  28068. /**
  28069. * Returns an object IntersectionInfo.
  28070. */
  28071. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28072. var intersectInfo = null;
  28073. // LineMesh first as it's also a Mesh...
  28074. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28075. var lineMesh = this._mesh;
  28076. // Line test
  28077. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28078. var p0 = positions[indices[index]];
  28079. var p1 = positions[indices[index + 1]];
  28080. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28081. if (length < 0) {
  28082. continue;
  28083. }
  28084. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28085. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28086. if (fastCheck) {
  28087. break;
  28088. }
  28089. }
  28090. }
  28091. }
  28092. else {
  28093. // Triangles test
  28094. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28095. var p0 = positions[indices[index]];
  28096. var p1 = positions[indices[index + 1]];
  28097. var p2 = positions[indices[index + 2]];
  28098. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28099. if (currentIntersectInfo) {
  28100. if (currentIntersectInfo.distance < 0) {
  28101. continue;
  28102. }
  28103. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28104. intersectInfo = currentIntersectInfo;
  28105. intersectInfo.faceId = index / 3;
  28106. if (fastCheck) {
  28107. break;
  28108. }
  28109. }
  28110. }
  28111. }
  28112. }
  28113. return intersectInfo;
  28114. };
  28115. SubMesh.prototype._rebuild = function () {
  28116. if (this._linesIndexBuffer) {
  28117. this._linesIndexBuffer = null;
  28118. }
  28119. };
  28120. // Clone
  28121. /**
  28122. * Creates a new Submesh from the passed Mesh.
  28123. */
  28124. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28125. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28126. if (!this.IsGlobal) {
  28127. var boundingInfo = this.getBoundingInfo();
  28128. if (!boundingInfo) {
  28129. return result;
  28130. }
  28131. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28132. }
  28133. return result;
  28134. };
  28135. // Dispose
  28136. /**
  28137. * Disposes the Submesh.
  28138. * Returns nothing.
  28139. */
  28140. SubMesh.prototype.dispose = function () {
  28141. if (this._linesIndexBuffer) {
  28142. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28143. this._linesIndexBuffer = null;
  28144. }
  28145. // Remove from mesh
  28146. var index = this._mesh.subMeshes.indexOf(this);
  28147. this._mesh.subMeshes.splice(index, 1);
  28148. };
  28149. // Statics
  28150. /**
  28151. * Creates a new Submesh from the passed parameters :
  28152. * - materialIndex (integer) : the index of the main mesh material.
  28153. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28154. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28155. * - mesh (Mesh) : the main mesh to create the submesh from.
  28156. * - renderingMesh (optional Mesh) : rendering mesh.
  28157. */
  28158. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28159. var minVertexIndex = Number.MAX_VALUE;
  28160. var maxVertexIndex = -Number.MAX_VALUE;
  28161. renderingMesh = (renderingMesh || mesh);
  28162. var indices = renderingMesh.getIndices();
  28163. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28164. var vertexIndex = indices[index];
  28165. if (vertexIndex < minVertexIndex)
  28166. minVertexIndex = vertexIndex;
  28167. if (vertexIndex > maxVertexIndex)
  28168. maxVertexIndex = vertexIndex;
  28169. }
  28170. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28171. };
  28172. return SubMesh;
  28173. }(BaseSubMesh));
  28174. BABYLON.SubMesh = SubMesh;
  28175. })(BABYLON || (BABYLON = {}));
  28176. //# sourceMappingURL=babylon.subMesh.js.map
  28177. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28178. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28179. s = arguments[i];
  28180. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28181. t[p] = s[p];
  28182. }
  28183. return t;
  28184. };
  28185. var BABYLON;
  28186. (function (BABYLON) {
  28187. var MaterialDefines = /** @class */ (function () {
  28188. function MaterialDefines() {
  28189. this._isDirty = true;
  28190. this._areLightsDirty = true;
  28191. this._areAttributesDirty = true;
  28192. this._areTexturesDirty = true;
  28193. this._areFresnelDirty = true;
  28194. this._areMiscDirty = true;
  28195. this._areImageProcessingDirty = true;
  28196. this._normals = false;
  28197. this._uvs = false;
  28198. this._needNormals = false;
  28199. this._needUVs = false;
  28200. }
  28201. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28202. get: function () {
  28203. return this._isDirty;
  28204. },
  28205. enumerable: true,
  28206. configurable: true
  28207. });
  28208. MaterialDefines.prototype.markAsProcessed = function () {
  28209. this._isDirty = false;
  28210. this._areAttributesDirty = false;
  28211. this._areTexturesDirty = false;
  28212. this._areFresnelDirty = false;
  28213. this._areLightsDirty = false;
  28214. this._areMiscDirty = false;
  28215. this._areImageProcessingDirty = false;
  28216. };
  28217. MaterialDefines.prototype.markAsUnprocessed = function () {
  28218. this._isDirty = true;
  28219. };
  28220. MaterialDefines.prototype.markAllAsDirty = function () {
  28221. this._areTexturesDirty = true;
  28222. this._areAttributesDirty = true;
  28223. this._areLightsDirty = true;
  28224. this._areFresnelDirty = true;
  28225. this._areMiscDirty = true;
  28226. this._areImageProcessingDirty = true;
  28227. this._isDirty = true;
  28228. };
  28229. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28230. this._areImageProcessingDirty = true;
  28231. this._isDirty = true;
  28232. };
  28233. MaterialDefines.prototype.markAsLightDirty = function () {
  28234. this._areLightsDirty = true;
  28235. this._isDirty = true;
  28236. };
  28237. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28238. this._areAttributesDirty = true;
  28239. this._isDirty = true;
  28240. };
  28241. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28242. this._areTexturesDirty = true;
  28243. this._isDirty = true;
  28244. };
  28245. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28246. this._areFresnelDirty = true;
  28247. this._isDirty = true;
  28248. };
  28249. MaterialDefines.prototype.markAsMiscDirty = function () {
  28250. this._areMiscDirty = true;
  28251. this._isDirty = true;
  28252. };
  28253. MaterialDefines.prototype.rebuild = function () {
  28254. if (this._keys) {
  28255. delete this._keys;
  28256. }
  28257. this._keys = [];
  28258. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28259. var key = _a[_i];
  28260. if (key[0] === "_") {
  28261. continue;
  28262. }
  28263. this._keys.push(key);
  28264. }
  28265. };
  28266. MaterialDefines.prototype.isEqual = function (other) {
  28267. if (this._keys.length !== other._keys.length) {
  28268. return false;
  28269. }
  28270. for (var index = 0; index < this._keys.length; index++) {
  28271. var prop = this._keys[index];
  28272. if (this[prop] !== other[prop]) {
  28273. return false;
  28274. }
  28275. }
  28276. return true;
  28277. };
  28278. MaterialDefines.prototype.cloneTo = function (other) {
  28279. if (this._keys.length !== other._keys.length) {
  28280. other._keys = this._keys.slice(0);
  28281. }
  28282. for (var index = 0; index < this._keys.length; index++) {
  28283. var prop = this._keys[index];
  28284. other[prop] = this[prop];
  28285. }
  28286. };
  28287. MaterialDefines.prototype.reset = function () {
  28288. for (var index = 0; index < this._keys.length; index++) {
  28289. var prop = this._keys[index];
  28290. if (typeof (this[prop]) === "number") {
  28291. this[prop] = 0;
  28292. }
  28293. else {
  28294. this[prop] = false;
  28295. }
  28296. }
  28297. };
  28298. MaterialDefines.prototype.toString = function () {
  28299. var result = "";
  28300. for (var index = 0; index < this._keys.length; index++) {
  28301. var prop = this._keys[index];
  28302. var value = this[prop];
  28303. if (typeof (value) === "number") {
  28304. result += "#define " + prop + " " + this[prop] + "\n";
  28305. }
  28306. else if (value) {
  28307. result += "#define " + prop + "\n";
  28308. }
  28309. }
  28310. return result;
  28311. };
  28312. return MaterialDefines;
  28313. }());
  28314. BABYLON.MaterialDefines = MaterialDefines;
  28315. var Material = /** @class */ (function () {
  28316. function Material(name, scene, doNotAdd) {
  28317. this.checkReadyOnEveryCall = false;
  28318. this.checkReadyOnlyOnce = false;
  28319. this.state = "";
  28320. this.alpha = 1.0;
  28321. this._backFaceCulling = true;
  28322. this.doNotSerialize = false;
  28323. this.storeEffectOnSubMeshes = false;
  28324. /**
  28325. * An event triggered when the material is disposed.
  28326. * @type {BABYLON.Observable}
  28327. */
  28328. this.onDisposeObservable = new BABYLON.Observable();
  28329. /**
  28330. * An event triggered when the material is bound.
  28331. * @type {BABYLON.Observable}
  28332. */
  28333. this.onBindObservable = new BABYLON.Observable();
  28334. /**
  28335. * An event triggered when the material is unbound.
  28336. * @type {BABYLON.Observable}
  28337. */
  28338. this.onUnBindObservable = new BABYLON.Observable();
  28339. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28340. this._needDepthPrePass = false;
  28341. this.disableDepthWrite = false;
  28342. this.forceDepthWrite = false;
  28343. this.separateCullingPass = false;
  28344. this._fogEnabled = true;
  28345. this.pointSize = 1.0;
  28346. this.zOffset = 0;
  28347. this._wasPreviouslyReady = false;
  28348. this._fillMode = Material.TriangleFillMode;
  28349. this.name = name;
  28350. this.id = name || BABYLON.Tools.RandomId();
  28351. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28352. if (this._scene.useRightHandedSystem) {
  28353. this.sideOrientation = Material.ClockWiseSideOrientation;
  28354. }
  28355. else {
  28356. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28357. }
  28358. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28359. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28360. if (!doNotAdd) {
  28361. this._scene.materials.push(this);
  28362. }
  28363. }
  28364. Object.defineProperty(Material, "TriangleFillMode", {
  28365. get: function () {
  28366. return Material._TriangleFillMode;
  28367. },
  28368. enumerable: true,
  28369. configurable: true
  28370. });
  28371. Object.defineProperty(Material, "WireFrameFillMode", {
  28372. get: function () {
  28373. return Material._WireFrameFillMode;
  28374. },
  28375. enumerable: true,
  28376. configurable: true
  28377. });
  28378. Object.defineProperty(Material, "PointFillMode", {
  28379. get: function () {
  28380. return Material._PointFillMode;
  28381. },
  28382. enumerable: true,
  28383. configurable: true
  28384. });
  28385. Object.defineProperty(Material, "PointListDrawMode", {
  28386. get: function () {
  28387. return Material._PointListDrawMode;
  28388. },
  28389. enumerable: true,
  28390. configurable: true
  28391. });
  28392. Object.defineProperty(Material, "LineListDrawMode", {
  28393. get: function () {
  28394. return Material._LineListDrawMode;
  28395. },
  28396. enumerable: true,
  28397. configurable: true
  28398. });
  28399. Object.defineProperty(Material, "LineLoopDrawMode", {
  28400. get: function () {
  28401. return Material._LineLoopDrawMode;
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. Object.defineProperty(Material, "LineStripDrawMode", {
  28407. get: function () {
  28408. return Material._LineStripDrawMode;
  28409. },
  28410. enumerable: true,
  28411. configurable: true
  28412. });
  28413. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28414. get: function () {
  28415. return Material._TriangleStripDrawMode;
  28416. },
  28417. enumerable: true,
  28418. configurable: true
  28419. });
  28420. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28421. get: function () {
  28422. return Material._TriangleFanDrawMode;
  28423. },
  28424. enumerable: true,
  28425. configurable: true
  28426. });
  28427. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28428. get: function () {
  28429. return Material._ClockWiseSideOrientation;
  28430. },
  28431. enumerable: true,
  28432. configurable: true
  28433. });
  28434. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28435. get: function () {
  28436. return Material._CounterClockWiseSideOrientation;
  28437. },
  28438. enumerable: true,
  28439. configurable: true
  28440. });
  28441. Object.defineProperty(Material, "TextureDirtyFlag", {
  28442. get: function () {
  28443. return Material._TextureDirtyFlag;
  28444. },
  28445. enumerable: true,
  28446. configurable: true
  28447. });
  28448. Object.defineProperty(Material, "LightDirtyFlag", {
  28449. get: function () {
  28450. return Material._LightDirtyFlag;
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28456. get: function () {
  28457. return Material._FresnelDirtyFlag;
  28458. },
  28459. enumerable: true,
  28460. configurable: true
  28461. });
  28462. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28463. get: function () {
  28464. return Material._AttributesDirtyFlag;
  28465. },
  28466. enumerable: true,
  28467. configurable: true
  28468. });
  28469. Object.defineProperty(Material, "MiscDirtyFlag", {
  28470. get: function () {
  28471. return Material._MiscDirtyFlag;
  28472. },
  28473. enumerable: true,
  28474. configurable: true
  28475. });
  28476. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28477. get: function () {
  28478. return this._backFaceCulling;
  28479. },
  28480. set: function (value) {
  28481. if (this._backFaceCulling === value) {
  28482. return;
  28483. }
  28484. this._backFaceCulling = value;
  28485. this.markAsDirty(Material.TextureDirtyFlag);
  28486. },
  28487. enumerable: true,
  28488. configurable: true
  28489. });
  28490. Object.defineProperty(Material.prototype, "onDispose", {
  28491. set: function (callback) {
  28492. if (this._onDisposeObserver) {
  28493. this.onDisposeObservable.remove(this._onDisposeObserver);
  28494. }
  28495. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28496. },
  28497. enumerable: true,
  28498. configurable: true
  28499. });
  28500. Object.defineProperty(Material.prototype, "onBind", {
  28501. set: function (callback) {
  28502. if (this._onBindObserver) {
  28503. this.onBindObservable.remove(this._onBindObserver);
  28504. }
  28505. this._onBindObserver = this.onBindObservable.add(callback);
  28506. },
  28507. enumerable: true,
  28508. configurable: true
  28509. });
  28510. Object.defineProperty(Material.prototype, "alphaMode", {
  28511. get: function () {
  28512. return this._alphaMode;
  28513. },
  28514. set: function (value) {
  28515. if (this._alphaMode === value) {
  28516. return;
  28517. }
  28518. this._alphaMode = value;
  28519. this.markAsDirty(Material.TextureDirtyFlag);
  28520. },
  28521. enumerable: true,
  28522. configurable: true
  28523. });
  28524. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28525. get: function () {
  28526. return this._needDepthPrePass;
  28527. },
  28528. set: function (value) {
  28529. if (this._needDepthPrePass === value) {
  28530. return;
  28531. }
  28532. this._needDepthPrePass = value;
  28533. if (this._needDepthPrePass) {
  28534. this.checkReadyOnEveryCall = true;
  28535. }
  28536. },
  28537. enumerable: true,
  28538. configurable: true
  28539. });
  28540. Object.defineProperty(Material.prototype, "fogEnabled", {
  28541. get: function () {
  28542. return this._fogEnabled;
  28543. },
  28544. set: function (value) {
  28545. if (this._fogEnabled === value) {
  28546. return;
  28547. }
  28548. this._fogEnabled = value;
  28549. this.markAsDirty(Material.MiscDirtyFlag);
  28550. },
  28551. enumerable: true,
  28552. configurable: true
  28553. });
  28554. Object.defineProperty(Material.prototype, "wireframe", {
  28555. get: function () {
  28556. return this._fillMode === Material.WireFrameFillMode;
  28557. },
  28558. set: function (value) {
  28559. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28560. },
  28561. enumerable: true,
  28562. configurable: true
  28563. });
  28564. Object.defineProperty(Material.prototype, "pointsCloud", {
  28565. get: function () {
  28566. return this._fillMode === Material.PointFillMode;
  28567. },
  28568. set: function (value) {
  28569. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28570. },
  28571. enumerable: true,
  28572. configurable: true
  28573. });
  28574. Object.defineProperty(Material.prototype, "fillMode", {
  28575. get: function () {
  28576. return this._fillMode;
  28577. },
  28578. set: function (value) {
  28579. if (this._fillMode === value) {
  28580. return;
  28581. }
  28582. this._fillMode = value;
  28583. this.markAsDirty(Material.MiscDirtyFlag);
  28584. },
  28585. enumerable: true,
  28586. configurable: true
  28587. });
  28588. /**
  28589. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28590. * subclasses should override adding information pertainent to themselves
  28591. */
  28592. Material.prototype.toString = function (fullDetails) {
  28593. var ret = "Name: " + this.name;
  28594. if (fullDetails) {
  28595. }
  28596. return ret;
  28597. };
  28598. /**
  28599. * Child classes can use it to update shaders
  28600. */
  28601. Material.prototype.getClassName = function () {
  28602. return "Material";
  28603. };
  28604. Object.defineProperty(Material.prototype, "isFrozen", {
  28605. get: function () {
  28606. return this.checkReadyOnlyOnce;
  28607. },
  28608. enumerable: true,
  28609. configurable: true
  28610. });
  28611. Material.prototype.freeze = function () {
  28612. this.checkReadyOnlyOnce = true;
  28613. };
  28614. Material.prototype.unfreeze = function () {
  28615. this.checkReadyOnlyOnce = false;
  28616. };
  28617. Material.prototype.isReady = function (mesh, useInstances) {
  28618. return true;
  28619. };
  28620. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28621. return false;
  28622. };
  28623. Material.prototype.getEffect = function () {
  28624. return this._effect;
  28625. };
  28626. Material.prototype.getScene = function () {
  28627. return this._scene;
  28628. };
  28629. Material.prototype.needAlphaBlending = function () {
  28630. return (this.alpha < 1.0);
  28631. };
  28632. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28633. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28634. };
  28635. Material.prototype.needAlphaTesting = function () {
  28636. return false;
  28637. };
  28638. Material.prototype.getAlphaTestTexture = function () {
  28639. return null;
  28640. };
  28641. Material.prototype.markDirty = function () {
  28642. this._wasPreviouslyReady = false;
  28643. };
  28644. Material.prototype._preBind = function (effect, overrideOrientation) {
  28645. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28646. var engine = this._scene.getEngine();
  28647. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28648. var reverse = orientation === Material.ClockWiseSideOrientation;
  28649. engine.enableEffect(effect ? effect : this._effect);
  28650. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28651. return reverse;
  28652. };
  28653. Material.prototype.bind = function (world, mesh) {
  28654. };
  28655. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28656. };
  28657. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28658. };
  28659. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28660. sceneUbo.bindToEffect(effect, "Scene");
  28661. };
  28662. Material.prototype.bindView = function (effect) {
  28663. if (!this._useUBO) {
  28664. effect.setMatrix("view", this.getScene().getViewMatrix());
  28665. }
  28666. else {
  28667. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28668. }
  28669. };
  28670. Material.prototype.bindViewProjection = function (effect) {
  28671. if (!this._useUBO) {
  28672. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28673. }
  28674. else {
  28675. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28676. }
  28677. };
  28678. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  28679. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  28680. };
  28681. Material.prototype._afterBind = function (mesh) {
  28682. this._scene._cachedMaterial = this;
  28683. if (mesh) {
  28684. this._scene._cachedVisibility = mesh.visibility;
  28685. }
  28686. else {
  28687. this._scene._cachedVisibility = 1;
  28688. }
  28689. if (mesh) {
  28690. this.onBindObservable.notifyObservers(mesh);
  28691. }
  28692. if (this.disableDepthWrite) {
  28693. var engine = this._scene.getEngine();
  28694. this._cachedDepthWriteState = engine.getDepthWrite();
  28695. engine.setDepthWrite(false);
  28696. }
  28697. };
  28698. Material.prototype.unbind = function () {
  28699. this.onUnBindObservable.notifyObservers(this);
  28700. if (this.disableDepthWrite) {
  28701. var engine = this._scene.getEngine();
  28702. engine.setDepthWrite(this._cachedDepthWriteState);
  28703. }
  28704. };
  28705. Material.prototype.getActiveTextures = function () {
  28706. return [];
  28707. };
  28708. Material.prototype.hasTexture = function (texture) {
  28709. return false;
  28710. };
  28711. Material.prototype.clone = function (name) {
  28712. return null;
  28713. };
  28714. Material.prototype.getBindedMeshes = function () {
  28715. var result = new Array();
  28716. for (var index = 0; index < this._scene.meshes.length; index++) {
  28717. var mesh = this._scene.meshes[index];
  28718. if (mesh.material === this) {
  28719. result.push(mesh);
  28720. }
  28721. }
  28722. return result;
  28723. };
  28724. /**
  28725. * Force shader compilation including textures ready check
  28726. */
  28727. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28728. var _this = this;
  28729. var localOptions = __assign({ clipPlane: false }, options);
  28730. var subMesh = new BABYLON.BaseSubMesh();
  28731. var scene = this.getScene();
  28732. var checkReady = function () {
  28733. if (!_this._scene || !_this._scene.getEngine()) {
  28734. return;
  28735. }
  28736. if (subMesh._materialDefines) {
  28737. subMesh._materialDefines._renderId = -1;
  28738. }
  28739. var clipPlaneState = scene.clipPlane;
  28740. if (localOptions.clipPlane) {
  28741. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28742. }
  28743. if (_this.storeEffectOnSubMeshes) {
  28744. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28745. if (onCompiled) {
  28746. onCompiled(_this);
  28747. }
  28748. }
  28749. else {
  28750. setTimeout(checkReady, 16);
  28751. }
  28752. }
  28753. else {
  28754. if (_this.isReady(mesh)) {
  28755. if (onCompiled) {
  28756. onCompiled(_this);
  28757. }
  28758. }
  28759. else {
  28760. setTimeout(checkReady, 16);
  28761. }
  28762. }
  28763. if (options && options.clipPlane) {
  28764. scene.clipPlane = clipPlaneState;
  28765. }
  28766. };
  28767. checkReady();
  28768. };
  28769. Material.prototype.markAsDirty = function (flag) {
  28770. if (flag & Material.TextureDirtyFlag) {
  28771. this._markAllSubMeshesAsTexturesDirty();
  28772. }
  28773. if (flag & Material.LightDirtyFlag) {
  28774. this._markAllSubMeshesAsLightsDirty();
  28775. }
  28776. if (flag & Material.FresnelDirtyFlag) {
  28777. this._markAllSubMeshesAsFresnelDirty();
  28778. }
  28779. if (flag & Material.AttributesDirtyFlag) {
  28780. this._markAllSubMeshesAsAttributesDirty();
  28781. }
  28782. if (flag & Material.MiscDirtyFlag) {
  28783. this._markAllSubMeshesAsMiscDirty();
  28784. }
  28785. this.getScene().resetCachedMaterial();
  28786. };
  28787. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28788. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28789. var mesh = _a[_i];
  28790. if (!mesh.subMeshes) {
  28791. continue;
  28792. }
  28793. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28794. var subMesh = _c[_b];
  28795. if (subMesh.getMaterial() !== this) {
  28796. continue;
  28797. }
  28798. if (!subMesh._materialDefines) {
  28799. continue;
  28800. }
  28801. func(subMesh._materialDefines);
  28802. }
  28803. }
  28804. };
  28805. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28806. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28807. };
  28808. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28809. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28810. };
  28811. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28812. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28813. };
  28814. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28815. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28816. };
  28817. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28818. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28819. };
  28820. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28821. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28822. };
  28823. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28824. // Animations
  28825. this.getScene().stopAnimation(this);
  28826. // Remove from scene
  28827. var index = this._scene.materials.indexOf(this);
  28828. if (index >= 0) {
  28829. this._scene.materials.splice(index, 1);
  28830. }
  28831. // Remove from meshes
  28832. for (index = 0; index < this._scene.meshes.length; index++) {
  28833. var mesh = this._scene.meshes[index];
  28834. if (mesh.material === this) {
  28835. mesh.material = null;
  28836. if (mesh.geometry) {
  28837. var geometry = (mesh.geometry);
  28838. if (this.storeEffectOnSubMeshes) {
  28839. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28840. var subMesh = _a[_i];
  28841. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28842. if (forceDisposeEffect && subMesh._materialEffect) {
  28843. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28844. }
  28845. }
  28846. }
  28847. else {
  28848. geometry._releaseVertexArrayObject(this._effect);
  28849. }
  28850. }
  28851. }
  28852. }
  28853. this._uniformBuffer.dispose();
  28854. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28855. if (forceDisposeEffect && this._effect) {
  28856. if (!this.storeEffectOnSubMeshes) {
  28857. this._scene.getEngine()._releaseEffect(this._effect);
  28858. }
  28859. this._effect = null;
  28860. }
  28861. // Callback
  28862. this.onDisposeObservable.notifyObservers(this);
  28863. this.onDisposeObservable.clear();
  28864. this.onBindObservable.clear();
  28865. this.onUnBindObservable.clear();
  28866. };
  28867. Material.prototype.serialize = function () {
  28868. return BABYLON.SerializationHelper.Serialize(this);
  28869. };
  28870. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28871. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28872. multiMaterial.id = parsedMultiMaterial.id;
  28873. if (BABYLON.Tags) {
  28874. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28875. }
  28876. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28877. var subMatId = parsedMultiMaterial.materials[matIndex];
  28878. if (subMatId) {
  28879. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28880. }
  28881. else {
  28882. multiMaterial.subMaterials.push(null);
  28883. }
  28884. }
  28885. return multiMaterial;
  28886. };
  28887. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28888. if (!parsedMaterial.customType) {
  28889. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28890. }
  28891. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28892. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28893. if (!BABYLON.LegacyPBRMaterial) {
  28894. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28895. return;
  28896. }
  28897. }
  28898. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28899. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28900. ;
  28901. };
  28902. // Triangle views
  28903. Material._TriangleFillMode = 0;
  28904. Material._WireFrameFillMode = 1;
  28905. Material._PointFillMode = 2;
  28906. // Draw modes
  28907. Material._PointListDrawMode = 3;
  28908. Material._LineListDrawMode = 4;
  28909. Material._LineLoopDrawMode = 5;
  28910. Material._LineStripDrawMode = 6;
  28911. Material._TriangleStripDrawMode = 7;
  28912. Material._TriangleFanDrawMode = 8;
  28913. Material._ClockWiseSideOrientation = 0;
  28914. Material._CounterClockWiseSideOrientation = 1;
  28915. Material._TextureDirtyFlag = 1;
  28916. Material._LightDirtyFlag = 2;
  28917. Material._FresnelDirtyFlag = 4;
  28918. Material._AttributesDirtyFlag = 8;
  28919. Material._MiscDirtyFlag = 16;
  28920. __decorate([
  28921. BABYLON.serialize()
  28922. ], Material.prototype, "id", void 0);
  28923. __decorate([
  28924. BABYLON.serialize()
  28925. ], Material.prototype, "name", void 0);
  28926. __decorate([
  28927. BABYLON.serialize()
  28928. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28929. __decorate([
  28930. BABYLON.serialize()
  28931. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28932. __decorate([
  28933. BABYLON.serialize()
  28934. ], Material.prototype, "state", void 0);
  28935. __decorate([
  28936. BABYLON.serialize()
  28937. ], Material.prototype, "alpha", void 0);
  28938. __decorate([
  28939. BABYLON.serialize("backFaceCulling")
  28940. ], Material.prototype, "_backFaceCulling", void 0);
  28941. __decorate([
  28942. BABYLON.serialize()
  28943. ], Material.prototype, "sideOrientation", void 0);
  28944. __decorate([
  28945. BABYLON.serialize("alphaMode")
  28946. ], Material.prototype, "_alphaMode", void 0);
  28947. __decorate([
  28948. BABYLON.serialize()
  28949. ], Material.prototype, "_needDepthPrePass", void 0);
  28950. __decorate([
  28951. BABYLON.serialize()
  28952. ], Material.prototype, "disableDepthWrite", void 0);
  28953. __decorate([
  28954. BABYLON.serialize()
  28955. ], Material.prototype, "forceDepthWrite", void 0);
  28956. __decorate([
  28957. BABYLON.serialize()
  28958. ], Material.prototype, "separateCullingPass", void 0);
  28959. __decorate([
  28960. BABYLON.serialize("fogEnabled")
  28961. ], Material.prototype, "_fogEnabled", void 0);
  28962. __decorate([
  28963. BABYLON.serialize()
  28964. ], Material.prototype, "pointSize", void 0);
  28965. __decorate([
  28966. BABYLON.serialize()
  28967. ], Material.prototype, "zOffset", void 0);
  28968. __decorate([
  28969. BABYLON.serialize()
  28970. ], Material.prototype, "wireframe", null);
  28971. __decorate([
  28972. BABYLON.serialize()
  28973. ], Material.prototype, "pointsCloud", null);
  28974. __decorate([
  28975. BABYLON.serialize()
  28976. ], Material.prototype, "fillMode", null);
  28977. return Material;
  28978. }());
  28979. BABYLON.Material = Material;
  28980. })(BABYLON || (BABYLON = {}));
  28981. //# sourceMappingURL=babylon.material.js.map
  28982. var BABYLON;
  28983. (function (BABYLON) {
  28984. var UniformBuffer = /** @class */ (function () {
  28985. /**
  28986. * Uniform buffer objects.
  28987. *
  28988. * Handles blocks of uniform on the GPU.
  28989. *
  28990. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28991. *
  28992. * For more information, please refer to :
  28993. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28994. */
  28995. function UniformBuffer(engine, data, dynamic) {
  28996. this._engine = engine;
  28997. this._noUBO = !engine.supportsUniformBuffers;
  28998. this._dynamic = dynamic;
  28999. this._data = data || [];
  29000. this._uniformLocations = {};
  29001. this._uniformSizes = {};
  29002. this._uniformLocationPointer = 0;
  29003. this._needSync = false;
  29004. if (this._noUBO) {
  29005. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29006. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29007. this.updateFloat = this._updateFloatForEffect;
  29008. this.updateFloat2 = this._updateFloat2ForEffect;
  29009. this.updateFloat3 = this._updateFloat3ForEffect;
  29010. this.updateFloat4 = this._updateFloat4ForEffect;
  29011. this.updateMatrix = this._updateMatrixForEffect;
  29012. this.updateVector3 = this._updateVector3ForEffect;
  29013. this.updateVector4 = this._updateVector4ForEffect;
  29014. this.updateColor3 = this._updateColor3ForEffect;
  29015. this.updateColor4 = this._updateColor4ForEffect;
  29016. }
  29017. else {
  29018. this._engine._uniformBuffers.push(this);
  29019. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29020. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29021. this.updateFloat = this._updateFloatForUniform;
  29022. this.updateFloat2 = this._updateFloat2ForUniform;
  29023. this.updateFloat3 = this._updateFloat3ForUniform;
  29024. this.updateFloat4 = this._updateFloat4ForUniform;
  29025. this.updateMatrix = this._updateMatrixForUniform;
  29026. this.updateVector3 = this._updateVector3ForUniform;
  29027. this.updateVector4 = this._updateVector4ForUniform;
  29028. this.updateColor3 = this._updateColor3ForUniform;
  29029. this.updateColor4 = this._updateColor4ForUniform;
  29030. }
  29031. }
  29032. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29033. // Properties
  29034. /**
  29035. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29036. * or just falling back on setUniformXXX calls.
  29037. */
  29038. get: function () {
  29039. return !this._noUBO;
  29040. },
  29041. enumerable: true,
  29042. configurable: true
  29043. });
  29044. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29045. /**
  29046. * Indicates if the WebGL underlying uniform buffer is in sync
  29047. * with the javascript cache data.
  29048. */
  29049. get: function () {
  29050. return !this._needSync;
  29051. },
  29052. enumerable: true,
  29053. configurable: true
  29054. });
  29055. /**
  29056. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29057. * Also, a dynamic UniformBuffer will disable cache verification and always
  29058. * update the underlying WebGL uniform buffer to the GPU.
  29059. */
  29060. UniformBuffer.prototype.isDynamic = function () {
  29061. return this._dynamic !== undefined;
  29062. };
  29063. /**
  29064. * The data cache on JS side.
  29065. */
  29066. UniformBuffer.prototype.getData = function () {
  29067. return this._bufferData;
  29068. };
  29069. /**
  29070. * The underlying WebGL Uniform buffer.
  29071. */
  29072. UniformBuffer.prototype.getBuffer = function () {
  29073. return this._buffer;
  29074. };
  29075. /**
  29076. * std140 layout specifies how to align data within an UBO structure.
  29077. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29078. * for specs.
  29079. */
  29080. UniformBuffer.prototype._fillAlignment = function (size) {
  29081. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29082. // and 4x4 matrices
  29083. // TODO : change if other types are used
  29084. var alignment;
  29085. if (size <= 2) {
  29086. alignment = size;
  29087. }
  29088. else {
  29089. alignment = 4;
  29090. }
  29091. if ((this._uniformLocationPointer % alignment) !== 0) {
  29092. var oldPointer = this._uniformLocationPointer;
  29093. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29094. var diff = this._uniformLocationPointer - oldPointer;
  29095. for (var i = 0; i < diff; i++) {
  29096. this._data.push(0);
  29097. }
  29098. }
  29099. };
  29100. /**
  29101. * Adds an uniform in the buffer.
  29102. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29103. * for the layout to be correct !
  29104. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29105. * @param {number|number[]} size Data size, or data directly.
  29106. */
  29107. UniformBuffer.prototype.addUniform = function (name, size) {
  29108. if (this._noUBO) {
  29109. return;
  29110. }
  29111. if (this._uniformLocations[name] !== undefined) {
  29112. // Already existing uniform
  29113. return;
  29114. }
  29115. // This function must be called in the order of the shader layout !
  29116. // size can be the size of the uniform, or data directly
  29117. var data;
  29118. if (size instanceof Array) {
  29119. data = size;
  29120. size = data.length;
  29121. }
  29122. else {
  29123. size = size;
  29124. data = [];
  29125. // Fill with zeros
  29126. for (var i = 0; i < size; i++) {
  29127. data.push(0);
  29128. }
  29129. }
  29130. this._fillAlignment(size);
  29131. this._uniformSizes[name] = size;
  29132. this._uniformLocations[name] = this._uniformLocationPointer;
  29133. this._uniformLocationPointer += size;
  29134. for (var i = 0; i < size; i++) {
  29135. this._data.push(data[i]);
  29136. }
  29137. this._needSync = true;
  29138. };
  29139. /**
  29140. * Wrapper for addUniform.
  29141. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29142. * @param {Matrix} mat A 4x4 matrix.
  29143. */
  29144. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29145. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29146. };
  29147. /**
  29148. * Wrapper for addUniform.
  29149. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29150. * @param {number} x
  29151. * @param {number} y
  29152. */
  29153. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29154. var temp = [x, y];
  29155. this.addUniform(name, temp);
  29156. };
  29157. /**
  29158. * Wrapper for addUniform.
  29159. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29160. * @param {number} x
  29161. * @param {number} y
  29162. * @param {number} z
  29163. */
  29164. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29165. var temp = [x, y, z];
  29166. this.addUniform(name, temp);
  29167. };
  29168. /**
  29169. * Wrapper for addUniform.
  29170. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29171. * @param {Color3} color
  29172. */
  29173. UniformBuffer.prototype.addColor3 = function (name, color) {
  29174. var temp = new Array();
  29175. color.toArray(temp);
  29176. this.addUniform(name, temp);
  29177. };
  29178. /**
  29179. * Wrapper for addUniform.
  29180. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29181. * @param {Color3} color
  29182. * @param {number} alpha
  29183. */
  29184. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29185. var temp = new Array();
  29186. color.toArray(temp);
  29187. temp.push(alpha);
  29188. this.addUniform(name, temp);
  29189. };
  29190. /**
  29191. * Wrapper for addUniform.
  29192. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29193. * @param {Vector3} vector
  29194. */
  29195. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29196. var temp = new Array();
  29197. vector.toArray(temp);
  29198. this.addUniform(name, temp);
  29199. };
  29200. /**
  29201. * Wrapper for addUniform.
  29202. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29203. */
  29204. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29205. this.addUniform(name, 12);
  29206. };
  29207. /**
  29208. * Wrapper for addUniform.
  29209. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29210. */
  29211. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29212. this.addUniform(name, 8);
  29213. };
  29214. /**
  29215. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29216. */
  29217. UniformBuffer.prototype.create = function () {
  29218. if (this._noUBO) {
  29219. return;
  29220. }
  29221. if (this._buffer) {
  29222. return; // nothing to do
  29223. }
  29224. // See spec, alignment must be filled as a vec4
  29225. this._fillAlignment(4);
  29226. this._bufferData = new Float32Array(this._data);
  29227. this._rebuild();
  29228. this._needSync = true;
  29229. };
  29230. UniformBuffer.prototype._rebuild = function () {
  29231. if (this._noUBO) {
  29232. return;
  29233. }
  29234. if (this._dynamic) {
  29235. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29236. }
  29237. else {
  29238. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29239. }
  29240. };
  29241. /**
  29242. * Updates the WebGL Uniform Buffer on the GPU.
  29243. * If the `dynamic` flag is set to true, no cache comparison is done.
  29244. * Otherwise, the buffer will be updated only if the cache differs.
  29245. */
  29246. UniformBuffer.prototype.update = function () {
  29247. if (!this._buffer) {
  29248. this.create();
  29249. return;
  29250. }
  29251. if (!this._dynamic && !this._needSync) {
  29252. return;
  29253. }
  29254. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29255. this._needSync = false;
  29256. };
  29257. /**
  29258. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29259. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29260. * @param {number[]|Float32Array} data Flattened data
  29261. * @param {number} size Size of the data.
  29262. */
  29263. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29264. var location = this._uniformLocations[uniformName];
  29265. if (location === undefined) {
  29266. if (this._buffer) {
  29267. // Cannot add an uniform if the buffer is already created
  29268. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29269. return;
  29270. }
  29271. this.addUniform(uniformName, size);
  29272. location = this._uniformLocations[uniformName];
  29273. }
  29274. if (!this._buffer) {
  29275. this.create();
  29276. }
  29277. if (!this._dynamic) {
  29278. // Cache for static uniform buffers
  29279. var changed = false;
  29280. for (var i = 0; i < size; i++) {
  29281. if (this._bufferData[location + i] !== data[i]) {
  29282. changed = true;
  29283. this._bufferData[location + i] = data[i];
  29284. }
  29285. }
  29286. this._needSync = this._needSync || changed;
  29287. }
  29288. else {
  29289. // No cache for dynamic
  29290. for (var i = 0; i < size; i++) {
  29291. this._bufferData[location + i] = data[i];
  29292. }
  29293. }
  29294. };
  29295. // Update methods
  29296. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29297. // To match std140, matrix must be realigned
  29298. for (var i = 0; i < 3; i++) {
  29299. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29300. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29301. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29302. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29303. }
  29304. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29305. };
  29306. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29307. this._currentEffect.setMatrix3x3(name, matrix);
  29308. };
  29309. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29310. this._currentEffect.setMatrix2x2(name, matrix);
  29311. };
  29312. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29313. // To match std140, matrix must be realigned
  29314. for (var i = 0; i < 2; i++) {
  29315. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29316. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29317. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29318. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29319. }
  29320. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29321. };
  29322. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29323. this._currentEffect.setFloat(name, x);
  29324. };
  29325. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29326. UniformBuffer._tempBuffer[0] = x;
  29327. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29328. };
  29329. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29330. if (suffix === void 0) { suffix = ""; }
  29331. this._currentEffect.setFloat2(name + suffix, x, y);
  29332. };
  29333. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29334. if (suffix === void 0) { suffix = ""; }
  29335. UniformBuffer._tempBuffer[0] = x;
  29336. UniformBuffer._tempBuffer[1] = y;
  29337. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29338. };
  29339. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29340. if (suffix === void 0) { suffix = ""; }
  29341. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29342. };
  29343. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29344. if (suffix === void 0) { suffix = ""; }
  29345. UniformBuffer._tempBuffer[0] = x;
  29346. UniformBuffer._tempBuffer[1] = y;
  29347. UniformBuffer._tempBuffer[2] = z;
  29348. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29349. };
  29350. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29351. if (suffix === void 0) { suffix = ""; }
  29352. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29353. };
  29354. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29355. if (suffix === void 0) { suffix = ""; }
  29356. UniformBuffer._tempBuffer[0] = x;
  29357. UniformBuffer._tempBuffer[1] = y;
  29358. UniformBuffer._tempBuffer[2] = z;
  29359. UniformBuffer._tempBuffer[3] = w;
  29360. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29361. };
  29362. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29363. this._currentEffect.setMatrix(name, mat);
  29364. };
  29365. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29366. this.updateUniform(name, mat.toArray(), 16);
  29367. };
  29368. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29369. this._currentEffect.setVector3(name, vector);
  29370. };
  29371. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29372. vector.toArray(UniformBuffer._tempBuffer);
  29373. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29374. };
  29375. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29376. this._currentEffect.setVector4(name, vector);
  29377. };
  29378. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29379. vector.toArray(UniformBuffer._tempBuffer);
  29380. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29381. };
  29382. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29383. if (suffix === void 0) { suffix = ""; }
  29384. this._currentEffect.setColor3(name + suffix, color);
  29385. };
  29386. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29387. if (suffix === void 0) { suffix = ""; }
  29388. color.toArray(UniformBuffer._tempBuffer);
  29389. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29390. };
  29391. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29392. if (suffix === void 0) { suffix = ""; }
  29393. this._currentEffect.setColor4(name + suffix, color, alpha);
  29394. };
  29395. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29396. if (suffix === void 0) { suffix = ""; }
  29397. color.toArray(UniformBuffer._tempBuffer);
  29398. UniformBuffer._tempBuffer[3] = alpha;
  29399. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29400. };
  29401. /**
  29402. * Sets a sampler uniform on the effect.
  29403. * @param {string} name Name of the sampler.
  29404. * @param {Texture} texture
  29405. */
  29406. UniformBuffer.prototype.setTexture = function (name, texture) {
  29407. this._currentEffect.setTexture(name, texture);
  29408. };
  29409. /**
  29410. * Directly updates the value of the uniform in the cache AND on the GPU.
  29411. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29412. * @param {number[]|Float32Array} data Flattened data
  29413. */
  29414. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29415. this.updateUniform(uniformName, data, data.length);
  29416. this.update();
  29417. };
  29418. /**
  29419. * Binds this uniform buffer to an effect.
  29420. * @param {Effect} effect
  29421. * @param {string} name Name of the uniform block in the shader.
  29422. */
  29423. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29424. this._currentEffect = effect;
  29425. if (this._noUBO || !this._buffer) {
  29426. return;
  29427. }
  29428. effect.bindUniformBuffer(this._buffer, name);
  29429. };
  29430. /**
  29431. * Disposes the uniform buffer.
  29432. */
  29433. UniformBuffer.prototype.dispose = function () {
  29434. if (this._noUBO) {
  29435. return;
  29436. }
  29437. var index = this._engine._uniformBuffers.indexOf(this);
  29438. if (index !== -1) {
  29439. this._engine._uniformBuffers.splice(index, 1);
  29440. }
  29441. if (!this._buffer) {
  29442. return;
  29443. }
  29444. if (this._engine._releaseBuffer(this._buffer)) {
  29445. this._buffer = null;
  29446. }
  29447. };
  29448. // Pool for avoiding memory leaks
  29449. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29450. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29451. return UniformBuffer;
  29452. }());
  29453. BABYLON.UniformBuffer = UniformBuffer;
  29454. })(BABYLON || (BABYLON = {}));
  29455. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29456. var BABYLON;
  29457. (function (BABYLON) {
  29458. var VertexData = /** @class */ (function () {
  29459. function VertexData() {
  29460. }
  29461. VertexData.prototype.set = function (data, kind) {
  29462. switch (kind) {
  29463. case BABYLON.VertexBuffer.PositionKind:
  29464. this.positions = data;
  29465. break;
  29466. case BABYLON.VertexBuffer.NormalKind:
  29467. this.normals = data;
  29468. break;
  29469. case BABYLON.VertexBuffer.TangentKind:
  29470. this.tangents = data;
  29471. break;
  29472. case BABYLON.VertexBuffer.UVKind:
  29473. this.uvs = data;
  29474. break;
  29475. case BABYLON.VertexBuffer.UV2Kind:
  29476. this.uvs2 = data;
  29477. break;
  29478. case BABYLON.VertexBuffer.UV3Kind:
  29479. this.uvs3 = data;
  29480. break;
  29481. case BABYLON.VertexBuffer.UV4Kind:
  29482. this.uvs4 = data;
  29483. break;
  29484. case BABYLON.VertexBuffer.UV5Kind:
  29485. this.uvs5 = data;
  29486. break;
  29487. case BABYLON.VertexBuffer.UV6Kind:
  29488. this.uvs6 = data;
  29489. break;
  29490. case BABYLON.VertexBuffer.ColorKind:
  29491. this.colors = data;
  29492. break;
  29493. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29494. this.matricesIndices = data;
  29495. break;
  29496. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29497. this.matricesWeights = data;
  29498. break;
  29499. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29500. this.matricesIndicesExtra = data;
  29501. break;
  29502. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29503. this.matricesWeightsExtra = data;
  29504. break;
  29505. }
  29506. };
  29507. /**
  29508. * Associates the vertexData to the passed Mesh.
  29509. * Sets it as updatable or not (default `false`).
  29510. * Returns the VertexData.
  29511. */
  29512. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29513. this._applyTo(mesh, updatable);
  29514. return this;
  29515. };
  29516. /**
  29517. * Associates the vertexData to the passed Geometry.
  29518. * Sets it as updatable or not (default `false`).
  29519. * Returns the VertexData.
  29520. */
  29521. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29522. this._applyTo(geometry, updatable);
  29523. return this;
  29524. };
  29525. /**
  29526. * Updates the associated mesh.
  29527. * Returns the VertexData.
  29528. */
  29529. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29530. this._update(mesh);
  29531. return this;
  29532. };
  29533. /**
  29534. * Updates the associated geometry.
  29535. * Returns the VertexData.
  29536. */
  29537. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29538. this._update(geometry);
  29539. return this;
  29540. };
  29541. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29542. if (updatable === void 0) { updatable = false; }
  29543. if (this.positions) {
  29544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29545. }
  29546. if (this.normals) {
  29547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29548. }
  29549. if (this.tangents) {
  29550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29551. }
  29552. if (this.uvs) {
  29553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29554. }
  29555. if (this.uvs2) {
  29556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29557. }
  29558. if (this.uvs3) {
  29559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29560. }
  29561. if (this.uvs4) {
  29562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29563. }
  29564. if (this.uvs5) {
  29565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29566. }
  29567. if (this.uvs6) {
  29568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29569. }
  29570. if (this.colors) {
  29571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29572. }
  29573. if (this.matricesIndices) {
  29574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29575. }
  29576. if (this.matricesWeights) {
  29577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29578. }
  29579. if (this.matricesIndicesExtra) {
  29580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29581. }
  29582. if (this.matricesWeightsExtra) {
  29583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29584. }
  29585. if (this.indices) {
  29586. meshOrGeometry.setIndices(this.indices, null, updatable);
  29587. }
  29588. return this;
  29589. };
  29590. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29591. if (this.positions) {
  29592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29593. }
  29594. if (this.normals) {
  29595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29596. }
  29597. if (this.tangents) {
  29598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29599. }
  29600. if (this.uvs) {
  29601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29602. }
  29603. if (this.uvs2) {
  29604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29605. }
  29606. if (this.uvs3) {
  29607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29608. }
  29609. if (this.uvs4) {
  29610. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29611. }
  29612. if (this.uvs5) {
  29613. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29614. }
  29615. if (this.uvs6) {
  29616. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29617. }
  29618. if (this.colors) {
  29619. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29620. }
  29621. if (this.matricesIndices) {
  29622. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29623. }
  29624. if (this.matricesWeights) {
  29625. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29626. }
  29627. if (this.matricesIndicesExtra) {
  29628. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29629. }
  29630. if (this.matricesWeightsExtra) {
  29631. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29632. }
  29633. if (this.indices) {
  29634. meshOrGeometry.setIndices(this.indices, null);
  29635. }
  29636. return this;
  29637. };
  29638. /**
  29639. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29640. * Returns the VertexData.
  29641. */
  29642. VertexData.prototype.transform = function (matrix) {
  29643. var transformed = BABYLON.Vector3.Zero();
  29644. var index;
  29645. if (this.positions) {
  29646. var position = BABYLON.Vector3.Zero();
  29647. for (index = 0; index < this.positions.length; index += 3) {
  29648. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29649. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29650. this.positions[index] = transformed.x;
  29651. this.positions[index + 1] = transformed.y;
  29652. this.positions[index + 2] = transformed.z;
  29653. }
  29654. }
  29655. if (this.normals) {
  29656. var normal = BABYLON.Vector3.Zero();
  29657. for (index = 0; index < this.normals.length; index += 3) {
  29658. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29659. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29660. this.normals[index] = transformed.x;
  29661. this.normals[index + 1] = transformed.y;
  29662. this.normals[index + 2] = transformed.z;
  29663. }
  29664. }
  29665. if (this.tangents) {
  29666. var tangent = BABYLON.Vector4.Zero();
  29667. var tangentTransformed = BABYLON.Vector4.Zero();
  29668. for (index = 0; index < this.tangents.length; index += 4) {
  29669. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29670. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29671. this.tangents[index] = tangentTransformed.x;
  29672. this.tangents[index + 1] = tangentTransformed.y;
  29673. this.tangents[index + 2] = tangentTransformed.z;
  29674. this.tangents[index + 3] = tangentTransformed.w;
  29675. }
  29676. }
  29677. return this;
  29678. };
  29679. /**
  29680. * Merges the passed VertexData into the current one.
  29681. * Returns the modified VertexData.
  29682. */
  29683. VertexData.prototype.merge = function (other, options) {
  29684. options = options || {};
  29685. if (other.indices) {
  29686. if (!this.indices) {
  29687. this.indices = [];
  29688. }
  29689. var offset = this.positions ? this.positions.length / 3 : 0;
  29690. for (var index = 0; index < other.indices.length; index++) {
  29691. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29692. this.indices.push(other.indices[index] + offset);
  29693. }
  29694. }
  29695. this.positions = this._mergeElement(this.positions, other.positions);
  29696. if (!this.positions) {
  29697. return this;
  29698. }
  29699. var count = this.positions.length / 3;
  29700. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29701. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29702. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29703. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29704. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29705. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29706. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29707. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29708. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29709. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29710. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29711. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29712. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29713. return this;
  29714. };
  29715. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29716. if (length === void 0) { length = 0; }
  29717. if (defaultValue === void 0) { defaultValue = 0; }
  29718. if (!other && !source) {
  29719. return null;
  29720. }
  29721. if (!other) {
  29722. var padding = new Float32Array(source.length);
  29723. padding.fill(defaultValue);
  29724. return this._mergeElement(source, padding, length);
  29725. }
  29726. if (!source) {
  29727. if (length === 0 || length === other.length) {
  29728. return other;
  29729. }
  29730. var padding = new Float32Array(length - other.length);
  29731. padding.fill(defaultValue);
  29732. return this._mergeElement(padding, other, length);
  29733. }
  29734. var len = other.length + source.length;
  29735. var isSrcTypedArray = source instanceof Float32Array;
  29736. var isOthTypedArray = other instanceof Float32Array;
  29737. // use non-loop method when the source is Float32Array
  29738. if (isSrcTypedArray) {
  29739. var ret32 = new Float32Array(len);
  29740. ret32.set(source);
  29741. ret32.set(other, source.length);
  29742. return ret32;
  29743. // source is number[], when other is also use concat
  29744. }
  29745. else if (!isOthTypedArray) {
  29746. return source.concat(other);
  29747. // source is a number[], but other is a Float32Array, loop required
  29748. }
  29749. else {
  29750. var ret = source.slice(0); // copy source to a separate array
  29751. for (var i = 0, len = other.length; i < len; i++) {
  29752. ret.push(other[i]);
  29753. }
  29754. return ret;
  29755. }
  29756. };
  29757. /**
  29758. * Serializes the VertexData.
  29759. * Returns a serialized object.
  29760. */
  29761. VertexData.prototype.serialize = function () {
  29762. var serializationObject = this.serialize();
  29763. if (this.positions) {
  29764. serializationObject.positions = this.positions;
  29765. }
  29766. if (this.normals) {
  29767. serializationObject.normals = this.normals;
  29768. }
  29769. if (this.tangents) {
  29770. serializationObject.tangents = this.tangents;
  29771. }
  29772. if (this.uvs) {
  29773. serializationObject.uvs = this.uvs;
  29774. }
  29775. if (this.uvs2) {
  29776. serializationObject.uvs2 = this.uvs2;
  29777. }
  29778. if (this.uvs3) {
  29779. serializationObject.uvs3 = this.uvs3;
  29780. }
  29781. if (this.uvs4) {
  29782. serializationObject.uvs4 = this.uvs4;
  29783. }
  29784. if (this.uvs5) {
  29785. serializationObject.uvs5 = this.uvs5;
  29786. }
  29787. if (this.uvs6) {
  29788. serializationObject.uvs6 = this.uvs6;
  29789. }
  29790. if (this.colors) {
  29791. serializationObject.colors = this.colors;
  29792. }
  29793. if (this.matricesIndices) {
  29794. serializationObject.matricesIndices = this.matricesIndices;
  29795. serializationObject.matricesIndices._isExpanded = true;
  29796. }
  29797. if (this.matricesWeights) {
  29798. serializationObject.matricesWeights = this.matricesWeights;
  29799. }
  29800. if (this.matricesIndicesExtra) {
  29801. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29802. serializationObject.matricesIndicesExtra._isExpanded = true;
  29803. }
  29804. if (this.matricesWeightsExtra) {
  29805. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29806. }
  29807. serializationObject.indices = this.indices;
  29808. return serializationObject;
  29809. };
  29810. // Statics
  29811. /**
  29812. * Returns the object VertexData associated to the passed mesh.
  29813. */
  29814. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29815. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29816. };
  29817. /**
  29818. * Returns the object VertexData associated to the passed geometry.
  29819. */
  29820. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29821. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29822. };
  29823. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29824. var result = new VertexData();
  29825. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29826. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29827. }
  29828. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29829. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29830. }
  29831. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29832. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29833. }
  29834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29835. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29836. }
  29837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29838. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29839. }
  29840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29841. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29842. }
  29843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29844. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29845. }
  29846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29847. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29848. }
  29849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29850. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29851. }
  29852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29853. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29854. }
  29855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29856. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29857. }
  29858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29859. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29860. }
  29861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29862. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29863. }
  29864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29865. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29866. }
  29867. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29868. return result;
  29869. };
  29870. /**
  29871. * Creates the vertexData of the Ribbon.
  29872. */
  29873. VertexData.CreateRibbon = function (options) {
  29874. var pathArray = options.pathArray;
  29875. var closeArray = options.closeArray || false;
  29876. var closePath = options.closePath || false;
  29877. var invertUV = options.invertUV || false;
  29878. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29879. var offset = options.offset || defaultOffset;
  29880. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29881. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29882. var customUV = options.uvs;
  29883. var customColors = options.colors;
  29884. var positions = [];
  29885. var indices = [];
  29886. var normals = [];
  29887. var uvs = [];
  29888. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29889. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29890. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29891. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29892. var minlg; // minimal length among all paths from pathArray
  29893. var lg = []; // array of path lengths : nb of vertex per path
  29894. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29895. var p; // path iterator
  29896. var i; // point iterator
  29897. var j; // point iterator
  29898. // if single path in pathArray
  29899. if (pathArray.length < 2) {
  29900. var ar1 = [];
  29901. var ar2 = [];
  29902. for (i = 0; i < pathArray[0].length - offset; i++) {
  29903. ar1.push(pathArray[0][i]);
  29904. ar2.push(pathArray[0][i + offset]);
  29905. }
  29906. pathArray = [ar1, ar2];
  29907. }
  29908. // positions and horizontal distances (u)
  29909. var idc = 0;
  29910. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29911. var path;
  29912. var l;
  29913. minlg = pathArray[0].length;
  29914. var vectlg;
  29915. var dist;
  29916. for (p = 0; p < pathArray.length; p++) {
  29917. uTotalDistance[p] = 0;
  29918. us[p] = [0];
  29919. path = pathArray[p];
  29920. l = path.length;
  29921. minlg = (minlg < l) ? minlg : l;
  29922. j = 0;
  29923. while (j < l) {
  29924. positions.push(path[j].x, path[j].y, path[j].z);
  29925. if (j > 0) {
  29926. vectlg = path[j].subtract(path[j - 1]).length();
  29927. dist = vectlg + uTotalDistance[p];
  29928. us[p].push(dist);
  29929. uTotalDistance[p] = dist;
  29930. }
  29931. j++;
  29932. }
  29933. if (closePath) {
  29934. j--;
  29935. positions.push(path[0].x, path[0].y, path[0].z);
  29936. vectlg = path[j].subtract(path[0]).length();
  29937. dist = vectlg + uTotalDistance[p];
  29938. us[p].push(dist);
  29939. uTotalDistance[p] = dist;
  29940. }
  29941. lg[p] = l + closePathCorr;
  29942. idx[p] = idc;
  29943. idc += (l + closePathCorr);
  29944. }
  29945. // vertical distances (v)
  29946. var path1;
  29947. var path2;
  29948. var vertex1 = null;
  29949. var vertex2 = null;
  29950. for (i = 0; i < minlg + closePathCorr; i++) {
  29951. vTotalDistance[i] = 0;
  29952. vs[i] = [0];
  29953. for (p = 0; p < pathArray.length - 1; p++) {
  29954. path1 = pathArray[p];
  29955. path2 = pathArray[p + 1];
  29956. if (i === minlg) {
  29957. vertex1 = path1[0];
  29958. vertex2 = path2[0];
  29959. }
  29960. else {
  29961. vertex1 = path1[i];
  29962. vertex2 = path2[i];
  29963. }
  29964. vectlg = vertex2.subtract(vertex1).length();
  29965. dist = vectlg + vTotalDistance[i];
  29966. vs[i].push(dist);
  29967. vTotalDistance[i] = dist;
  29968. }
  29969. if (closeArray && vertex2 && vertex1) {
  29970. path1 = pathArray[p];
  29971. path2 = pathArray[0];
  29972. if (i === minlg) {
  29973. vertex2 = path2[0];
  29974. }
  29975. vectlg = vertex2.subtract(vertex1).length();
  29976. dist = vectlg + vTotalDistance[i];
  29977. vTotalDistance[i] = dist;
  29978. }
  29979. }
  29980. // uvs
  29981. var u;
  29982. var v;
  29983. if (customUV) {
  29984. for (p = 0; p < customUV.length; p++) {
  29985. uvs.push(customUV[p].x, customUV[p].y);
  29986. }
  29987. }
  29988. else {
  29989. for (p = 0; p < pathArray.length; p++) {
  29990. for (i = 0; i < minlg + closePathCorr; i++) {
  29991. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29992. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29993. if (invertUV) {
  29994. uvs.push(v, u);
  29995. }
  29996. else {
  29997. uvs.push(u, v);
  29998. }
  29999. }
  30000. }
  30001. }
  30002. // indices
  30003. p = 0; // path index
  30004. var pi = 0; // positions array index
  30005. var l1 = lg[p] - 1; // path1 length
  30006. var l2 = lg[p + 1] - 1; // path2 length
  30007. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30008. var shft = idx[1] - idx[0]; // shift
  30009. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30010. while (pi <= min && p < path1nb) {
  30011. // 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
  30012. indices.push(pi, pi + shft, pi + 1);
  30013. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30014. pi += 1;
  30015. if (pi === min) {
  30016. p++;
  30017. if (p === lg.length - 1) {
  30018. shft = idx[0] - idx[p];
  30019. l1 = lg[p] - 1;
  30020. l2 = lg[0] - 1;
  30021. }
  30022. else {
  30023. shft = idx[p + 1] - idx[p];
  30024. l1 = lg[p] - 1;
  30025. l2 = lg[p + 1] - 1;
  30026. }
  30027. pi = idx[p];
  30028. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30029. }
  30030. }
  30031. // normals
  30032. VertexData.ComputeNormals(positions, indices, normals);
  30033. if (closePath) {
  30034. var indexFirst = 0;
  30035. var indexLast = 0;
  30036. for (p = 0; p < pathArray.length; p++) {
  30037. indexFirst = idx[p] * 3;
  30038. if (p + 1 < pathArray.length) {
  30039. indexLast = (idx[p + 1] - 1) * 3;
  30040. }
  30041. else {
  30042. indexLast = normals.length - 3;
  30043. }
  30044. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30045. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30046. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30047. normals[indexLast] = normals[indexFirst];
  30048. normals[indexLast + 1] = normals[indexFirst + 1];
  30049. normals[indexLast + 2] = normals[indexFirst + 2];
  30050. }
  30051. }
  30052. // sides
  30053. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30054. // Colors
  30055. var colors = null;
  30056. if (customColors) {
  30057. colors = new Float32Array(customColors.length * 4);
  30058. for (var c = 0; c < customColors.length; c++) {
  30059. colors[c * 4] = customColors[c].r;
  30060. colors[c * 4 + 1] = customColors[c].g;
  30061. colors[c * 4 + 2] = customColors[c].b;
  30062. colors[c * 4 + 3] = customColors[c].a;
  30063. }
  30064. }
  30065. // Result
  30066. var vertexData = new VertexData();
  30067. var positions32 = new Float32Array(positions);
  30068. var normals32 = new Float32Array(normals);
  30069. var uvs32 = new Float32Array(uvs);
  30070. vertexData.indices = indices;
  30071. vertexData.positions = positions32;
  30072. vertexData.normals = normals32;
  30073. vertexData.uvs = uvs32;
  30074. if (colors) {
  30075. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30076. }
  30077. if (closePath) {
  30078. vertexData._idx = idx;
  30079. }
  30080. return vertexData;
  30081. };
  30082. /**
  30083. * Creates the VertexData of the Box.
  30084. */
  30085. VertexData.CreateBox = function (options) {
  30086. var normalsSource = [
  30087. new BABYLON.Vector3(0, 0, 1),
  30088. new BABYLON.Vector3(0, 0, -1),
  30089. new BABYLON.Vector3(1, 0, 0),
  30090. new BABYLON.Vector3(-1, 0, 0),
  30091. new BABYLON.Vector3(0, 1, 0),
  30092. new BABYLON.Vector3(0, -1, 0)
  30093. ];
  30094. var indices = [];
  30095. var positions = [];
  30096. var normals = [];
  30097. var uvs = [];
  30098. var width = options.width || options.size || 1;
  30099. var height = options.height || options.size || 1;
  30100. var depth = options.depth || options.size || 1;
  30101. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30102. var faceUV = options.faceUV || new Array(6);
  30103. var faceColors = options.faceColors;
  30104. var colors = [];
  30105. // default face colors and UV if undefined
  30106. for (var f = 0; f < 6; f++) {
  30107. if (faceUV[f] === undefined) {
  30108. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30109. }
  30110. if (faceColors && faceColors[f] === undefined) {
  30111. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30112. }
  30113. }
  30114. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30115. // Create each face in turn.
  30116. for (var index = 0; index < normalsSource.length; index++) {
  30117. var normal = normalsSource[index];
  30118. // Get two vectors perpendicular to the face normal and to each other.
  30119. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30120. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30121. // Six indices (two triangles) per face.
  30122. var verticesLength = positions.length / 3;
  30123. indices.push(verticesLength);
  30124. indices.push(verticesLength + 1);
  30125. indices.push(verticesLength + 2);
  30126. indices.push(verticesLength);
  30127. indices.push(verticesLength + 2);
  30128. indices.push(verticesLength + 3);
  30129. // Four vertices per face.
  30130. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30131. positions.push(vertex.x, vertex.y, vertex.z);
  30132. normals.push(normal.x, normal.y, normal.z);
  30133. uvs.push(faceUV[index].z, faceUV[index].w);
  30134. if (faceColors) {
  30135. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30136. }
  30137. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30138. positions.push(vertex.x, vertex.y, vertex.z);
  30139. normals.push(normal.x, normal.y, normal.z);
  30140. uvs.push(faceUV[index].x, faceUV[index].w);
  30141. if (faceColors) {
  30142. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30143. }
  30144. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30145. positions.push(vertex.x, vertex.y, vertex.z);
  30146. normals.push(normal.x, normal.y, normal.z);
  30147. uvs.push(faceUV[index].x, faceUV[index].y);
  30148. if (faceColors) {
  30149. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30150. }
  30151. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30152. positions.push(vertex.x, vertex.y, vertex.z);
  30153. normals.push(normal.x, normal.y, normal.z);
  30154. uvs.push(faceUV[index].z, faceUV[index].y);
  30155. if (faceColors) {
  30156. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30157. }
  30158. }
  30159. // sides
  30160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30161. // Result
  30162. var vertexData = new VertexData();
  30163. vertexData.indices = indices;
  30164. vertexData.positions = positions;
  30165. vertexData.normals = normals;
  30166. vertexData.uvs = uvs;
  30167. if (faceColors) {
  30168. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30169. vertexData.colors = totalColors;
  30170. }
  30171. return vertexData;
  30172. };
  30173. /**
  30174. * Creates the VertexData of the Sphere.
  30175. */
  30176. VertexData.CreateSphere = function (options) {
  30177. var segments = options.segments || 32;
  30178. var diameterX = options.diameterX || options.diameter || 1;
  30179. var diameterY = options.diameterY || options.diameter || 1;
  30180. var diameterZ = options.diameterZ || options.diameter || 1;
  30181. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30182. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30183. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30184. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30185. var totalZRotationSteps = 2 + segments;
  30186. var totalYRotationSteps = 2 * totalZRotationSteps;
  30187. var indices = [];
  30188. var positions = [];
  30189. var normals = [];
  30190. var uvs = [];
  30191. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30192. var normalizedZ = zRotationStep / totalZRotationSteps;
  30193. var angleZ = normalizedZ * Math.PI * slice;
  30194. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30195. var normalizedY = yRotationStep / totalYRotationSteps;
  30196. var angleY = normalizedY * Math.PI * 2 * arc;
  30197. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30198. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30199. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30200. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30201. var vertex = complete.multiply(radius);
  30202. var normal = complete.divide(radius).normalize();
  30203. positions.push(vertex.x, vertex.y, vertex.z);
  30204. normals.push(normal.x, normal.y, normal.z);
  30205. uvs.push(normalizedY, normalizedZ);
  30206. }
  30207. if (zRotationStep > 0) {
  30208. var verticesCount = positions.length / 3;
  30209. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30210. indices.push((firstIndex));
  30211. indices.push((firstIndex + 1));
  30212. indices.push(firstIndex + totalYRotationSteps + 1);
  30213. indices.push((firstIndex + totalYRotationSteps + 1));
  30214. indices.push((firstIndex + 1));
  30215. indices.push((firstIndex + totalYRotationSteps + 2));
  30216. }
  30217. }
  30218. }
  30219. // Sides
  30220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30221. // Result
  30222. var vertexData = new VertexData();
  30223. vertexData.indices = indices;
  30224. vertexData.positions = positions;
  30225. vertexData.normals = normals;
  30226. vertexData.uvs = uvs;
  30227. return vertexData;
  30228. };
  30229. /**
  30230. * Creates the VertexData of the Cylinder or Cone.
  30231. */
  30232. VertexData.CreateCylinder = function (options) {
  30233. var height = options.height || 2;
  30234. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30235. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30236. var tessellation = options.tessellation || 24;
  30237. var subdivisions = options.subdivisions || 1;
  30238. var hasRings = options.hasRings ? true : false;
  30239. var enclose = options.enclose ? true : false;
  30240. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30241. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30242. var faceUV = options.faceUV || new Array(3);
  30243. var faceColors = options.faceColors;
  30244. // default face colors and UV if undefined
  30245. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30246. var ringNb = (hasRings) ? subdivisions : 1;
  30247. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30248. var f;
  30249. for (f = 0; f < surfaceNb; f++) {
  30250. if (faceColors && faceColors[f] === undefined) {
  30251. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30252. }
  30253. }
  30254. for (f = 0; f < surfaceNb; f++) {
  30255. if (faceUV && faceUV[f] === undefined) {
  30256. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30257. }
  30258. }
  30259. var indices = new Array();
  30260. var positions = new Array();
  30261. var normals = new Array();
  30262. var uvs = new Array();
  30263. var colors = new Array();
  30264. var angle_step = Math.PI * 2 * arc / tessellation;
  30265. var angle;
  30266. var h;
  30267. var radius;
  30268. var tan = (diameterBottom - diameterTop) / 2 / height;
  30269. var ringVertex = BABYLON.Vector3.Zero();
  30270. var ringNormal = BABYLON.Vector3.Zero();
  30271. var ringFirstVertex = BABYLON.Vector3.Zero();
  30272. var ringFirstNormal = BABYLON.Vector3.Zero();
  30273. var quadNormal = BABYLON.Vector3.Zero();
  30274. var Y = BABYLON.Axis.Y;
  30275. // positions, normals, uvs
  30276. var i;
  30277. var j;
  30278. var r;
  30279. var ringIdx = 1;
  30280. var s = 1; // surface index
  30281. var cs = 0;
  30282. var v = 0;
  30283. for (i = 0; i <= subdivisions; i++) {
  30284. h = i / subdivisions;
  30285. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30286. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30287. for (r = 0; r < ringIdx; r++) {
  30288. if (hasRings) {
  30289. s += r;
  30290. }
  30291. if (enclose) {
  30292. s += 2 * r;
  30293. }
  30294. for (j = 0; j <= tessellation; j++) {
  30295. angle = j * angle_step;
  30296. // position
  30297. ringVertex.x = Math.cos(-angle) * radius;
  30298. ringVertex.y = -height / 2 + h * height;
  30299. ringVertex.z = Math.sin(-angle) * radius;
  30300. // normal
  30301. if (diameterTop === 0 && i === subdivisions) {
  30302. // if no top cap, reuse former normals
  30303. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30304. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30305. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30306. }
  30307. else {
  30308. ringNormal.x = ringVertex.x;
  30309. ringNormal.z = ringVertex.z;
  30310. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30311. ringNormal.normalize();
  30312. }
  30313. // keep first ring vertex values for enclose
  30314. if (j === 0) {
  30315. ringFirstVertex.copyFrom(ringVertex);
  30316. ringFirstNormal.copyFrom(ringNormal);
  30317. }
  30318. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30319. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30320. if (hasRings) {
  30321. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30322. }
  30323. else {
  30324. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30325. }
  30326. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30327. if (faceColors) {
  30328. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30329. }
  30330. }
  30331. // if enclose, add four vertices and their dedicated normals
  30332. if (arc !== 1 && enclose) {
  30333. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30334. positions.push(0, ringVertex.y, 0);
  30335. positions.push(0, ringVertex.y, 0);
  30336. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30337. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30338. quadNormal.normalize();
  30339. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30340. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30341. quadNormal.normalize();
  30342. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30343. if (hasRings) {
  30344. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30345. }
  30346. else {
  30347. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30348. }
  30349. uvs.push(faceUV[s + 1].x, v);
  30350. uvs.push(faceUV[s + 1].z, v);
  30351. if (hasRings) {
  30352. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30353. }
  30354. else {
  30355. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30356. }
  30357. uvs.push(faceUV[s + 2].x, v);
  30358. uvs.push(faceUV[s + 2].z, v);
  30359. if (faceColors) {
  30360. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30361. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30362. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30363. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30364. }
  30365. }
  30366. if (cs !== s) {
  30367. cs = s;
  30368. }
  30369. }
  30370. }
  30371. // indices
  30372. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30373. var s;
  30374. i = 0;
  30375. for (s = 0; s < subdivisions; s++) {
  30376. var i0 = 0;
  30377. var i1 = 0;
  30378. var i2 = 0;
  30379. var i3 = 0;
  30380. for (j = 0; j < tessellation; j++) {
  30381. i0 = i * (e + 1) + j;
  30382. i1 = (i + 1) * (e + 1) + j;
  30383. i2 = i * (e + 1) + (j + 1);
  30384. i3 = (i + 1) * (e + 1) + (j + 1);
  30385. indices.push(i0, i1, i2);
  30386. indices.push(i3, i2, i1);
  30387. }
  30388. if (arc !== 1 && enclose) {
  30389. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30390. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30391. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30392. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30393. }
  30394. i = (hasRings) ? (i + 2) : (i + 1);
  30395. }
  30396. // Caps
  30397. var createCylinderCap = function (isTop) {
  30398. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30399. if (radius === 0) {
  30400. return;
  30401. }
  30402. // Cap positions, normals & uvs
  30403. var angle;
  30404. var circleVector;
  30405. var i;
  30406. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30407. var c = null;
  30408. if (faceColors) {
  30409. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30410. }
  30411. // cap center
  30412. var vbase = positions.length / 3;
  30413. var offset = isTop ? height / 2 : -height / 2;
  30414. var center = new BABYLON.Vector3(0, offset, 0);
  30415. positions.push(center.x, center.y, center.z);
  30416. normals.push(0, isTop ? 1 : -1, 0);
  30417. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30418. if (c) {
  30419. colors.push(c.r, c.g, c.b, c.a);
  30420. }
  30421. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30422. for (i = 0; i <= tessellation; i++) {
  30423. angle = Math.PI * 2 * i * arc / tessellation;
  30424. var cos = Math.cos(-angle);
  30425. var sin = Math.sin(-angle);
  30426. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30427. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30428. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30429. normals.push(0, isTop ? 1 : -1, 0);
  30430. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30431. if (c) {
  30432. colors.push(c.r, c.g, c.b, c.a);
  30433. }
  30434. }
  30435. // Cap indices
  30436. for (i = 0; i < tessellation; i++) {
  30437. if (!isTop) {
  30438. indices.push(vbase);
  30439. indices.push(vbase + (i + 1));
  30440. indices.push(vbase + (i + 2));
  30441. }
  30442. else {
  30443. indices.push(vbase);
  30444. indices.push(vbase + (i + 2));
  30445. indices.push(vbase + (i + 1));
  30446. }
  30447. }
  30448. };
  30449. // add caps to geometry
  30450. createCylinderCap(false);
  30451. createCylinderCap(true);
  30452. // Sides
  30453. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30454. var vertexData = new VertexData();
  30455. vertexData.indices = indices;
  30456. vertexData.positions = positions;
  30457. vertexData.normals = normals;
  30458. vertexData.uvs = uvs;
  30459. if (faceColors) {
  30460. vertexData.colors = colors;
  30461. }
  30462. return vertexData;
  30463. };
  30464. /**
  30465. * Creates the VertexData of the Torus.
  30466. */
  30467. VertexData.CreateTorus = function (options) {
  30468. var indices = [];
  30469. var positions = [];
  30470. var normals = [];
  30471. var uvs = [];
  30472. var diameter = options.diameter || 1;
  30473. var thickness = options.thickness || 0.5;
  30474. var tessellation = options.tessellation || 16;
  30475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30476. var stride = tessellation + 1;
  30477. for (var i = 0; i <= tessellation; i++) {
  30478. var u = i / tessellation;
  30479. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30480. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30481. for (var j = 0; j <= tessellation; j++) {
  30482. var v = 1 - j / tessellation;
  30483. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30484. var dx = Math.cos(innerAngle);
  30485. var dy = Math.sin(innerAngle);
  30486. // Create a vertex.
  30487. var normal = new BABYLON.Vector3(dx, dy, 0);
  30488. var position = normal.scale(thickness / 2);
  30489. var textureCoordinate = new BABYLON.Vector2(u, v);
  30490. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30491. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30492. positions.push(position.x, position.y, position.z);
  30493. normals.push(normal.x, normal.y, normal.z);
  30494. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30495. // And create indices for two triangles.
  30496. var nextI = (i + 1) % stride;
  30497. var nextJ = (j + 1) % stride;
  30498. indices.push(i * stride + j);
  30499. indices.push(i * stride + nextJ);
  30500. indices.push(nextI * stride + j);
  30501. indices.push(i * stride + nextJ);
  30502. indices.push(nextI * stride + nextJ);
  30503. indices.push(nextI * stride + j);
  30504. }
  30505. }
  30506. // Sides
  30507. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30508. // Result
  30509. var vertexData = new VertexData();
  30510. vertexData.indices = indices;
  30511. vertexData.positions = positions;
  30512. vertexData.normals = normals;
  30513. vertexData.uvs = uvs;
  30514. return vertexData;
  30515. };
  30516. /**
  30517. * Creates the VertexData of the LineSystem.
  30518. */
  30519. VertexData.CreateLineSystem = function (options) {
  30520. var indices = [];
  30521. var positions = [];
  30522. var lines = options.lines;
  30523. var colors = options.colors;
  30524. var vertexColors = [];
  30525. var idx = 0;
  30526. for (var l = 0; l < lines.length; l++) {
  30527. var points = lines[l];
  30528. for (var index = 0; index < points.length; index++) {
  30529. positions.push(points[index].x, points[index].y, points[index].z);
  30530. if (colors) {
  30531. var color = colors[l];
  30532. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30533. }
  30534. if (index > 0) {
  30535. indices.push(idx - 1);
  30536. indices.push(idx);
  30537. }
  30538. idx++;
  30539. }
  30540. }
  30541. var vertexData = new VertexData();
  30542. vertexData.indices = indices;
  30543. vertexData.positions = positions;
  30544. if (colors) {
  30545. vertexData.colors = vertexColors;
  30546. }
  30547. return vertexData;
  30548. };
  30549. /**
  30550. * Create the VertexData of the DashedLines.
  30551. */
  30552. VertexData.CreateDashedLines = function (options) {
  30553. var dashSize = options.dashSize || 3;
  30554. var gapSize = options.gapSize || 1;
  30555. var dashNb = options.dashNb || 200;
  30556. var points = options.points;
  30557. var positions = new Array();
  30558. var indices = new Array();
  30559. var curvect = BABYLON.Vector3.Zero();
  30560. var lg = 0;
  30561. var nb = 0;
  30562. var shft = 0;
  30563. var dashshft = 0;
  30564. var curshft = 0;
  30565. var idx = 0;
  30566. var i = 0;
  30567. for (i = 0; i < points.length - 1; i++) {
  30568. points[i + 1].subtractToRef(points[i], curvect);
  30569. lg += curvect.length();
  30570. }
  30571. shft = lg / dashNb;
  30572. dashshft = dashSize * shft / (dashSize + gapSize);
  30573. for (i = 0; i < points.length - 1; i++) {
  30574. points[i + 1].subtractToRef(points[i], curvect);
  30575. nb = Math.floor(curvect.length() / shft);
  30576. curvect.normalize();
  30577. for (var j = 0; j < nb; j++) {
  30578. curshft = shft * j;
  30579. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30580. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30581. indices.push(idx, idx + 1);
  30582. idx += 2;
  30583. }
  30584. }
  30585. // Result
  30586. var vertexData = new VertexData();
  30587. vertexData.positions = positions;
  30588. vertexData.indices = indices;
  30589. return vertexData;
  30590. };
  30591. /**
  30592. * Creates the VertexData of the Ground.
  30593. */
  30594. VertexData.CreateGround = function (options) {
  30595. var indices = [];
  30596. var positions = [];
  30597. var normals = [];
  30598. var uvs = [];
  30599. var row, col;
  30600. var width = options.width || 1;
  30601. var height = options.height || 1;
  30602. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30603. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30604. for (row = 0; row <= subdivisionsY; row++) {
  30605. for (col = 0; col <= subdivisionsX; col++) {
  30606. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30607. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30608. positions.push(position.x, position.y, position.z);
  30609. normals.push(normal.x, normal.y, normal.z);
  30610. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30611. }
  30612. }
  30613. for (row = 0; row < subdivisionsY; row++) {
  30614. for (col = 0; col < subdivisionsX; col++) {
  30615. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30616. indices.push(col + 1 + row * (subdivisionsX + 1));
  30617. indices.push(col + row * (subdivisionsX + 1));
  30618. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30619. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30620. indices.push(col + row * (subdivisionsX + 1));
  30621. }
  30622. }
  30623. // Result
  30624. var vertexData = new VertexData();
  30625. vertexData.indices = indices;
  30626. vertexData.positions = positions;
  30627. vertexData.normals = normals;
  30628. vertexData.uvs = uvs;
  30629. return vertexData;
  30630. };
  30631. /**
  30632. * Creates the VertexData of the TiledGround.
  30633. */
  30634. VertexData.CreateTiledGround = function (options) {
  30635. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30636. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30637. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30638. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30639. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30640. var precision = options.precision || { w: 1, h: 1 };
  30641. var indices = new Array();
  30642. var positions = new Array();
  30643. var normals = new Array();
  30644. var uvs = new Array();
  30645. var row, col, tileRow, tileCol;
  30646. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30647. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30648. precision.w = (precision.w < 1) ? 1 : precision.w;
  30649. precision.h = (precision.h < 1) ? 1 : precision.h;
  30650. var tileSize = {
  30651. 'w': (xmax - xmin) / subdivisions.w,
  30652. 'h': (zmax - zmin) / subdivisions.h
  30653. };
  30654. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30655. // Indices
  30656. var base = positions.length / 3;
  30657. var rowLength = precision.w + 1;
  30658. for (row = 0; row < precision.h; row++) {
  30659. for (col = 0; col < precision.w; col++) {
  30660. var square = [
  30661. base + col + row * rowLength,
  30662. base + (col + 1) + row * rowLength,
  30663. base + (col + 1) + (row + 1) * rowLength,
  30664. base + col + (row + 1) * rowLength
  30665. ];
  30666. indices.push(square[1]);
  30667. indices.push(square[2]);
  30668. indices.push(square[3]);
  30669. indices.push(square[0]);
  30670. indices.push(square[1]);
  30671. indices.push(square[3]);
  30672. }
  30673. }
  30674. // Position, normals and uvs
  30675. var position = BABYLON.Vector3.Zero();
  30676. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30677. for (row = 0; row <= precision.h; row++) {
  30678. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30679. for (col = 0; col <= precision.w; col++) {
  30680. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30681. position.y = 0;
  30682. positions.push(position.x, position.y, position.z);
  30683. normals.push(normal.x, normal.y, normal.z);
  30684. uvs.push(col / precision.w, row / precision.h);
  30685. }
  30686. }
  30687. }
  30688. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30689. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30690. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30691. }
  30692. }
  30693. // Result
  30694. var vertexData = new VertexData();
  30695. vertexData.indices = indices;
  30696. vertexData.positions = positions;
  30697. vertexData.normals = normals;
  30698. vertexData.uvs = uvs;
  30699. return vertexData;
  30700. };
  30701. /**
  30702. * Creates the VertexData of the Ground designed from a heightmap.
  30703. */
  30704. VertexData.CreateGroundFromHeightMap = function (options) {
  30705. var indices = [];
  30706. var positions = [];
  30707. var normals = [];
  30708. var uvs = [];
  30709. var row, col;
  30710. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30711. // Vertices
  30712. for (row = 0; row <= options.subdivisions; row++) {
  30713. for (col = 0; col <= options.subdivisions; col++) {
  30714. 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));
  30715. // Compute height
  30716. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30717. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30718. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30719. var r = options.buffer[pos] / 255.0;
  30720. var g = options.buffer[pos + 1] / 255.0;
  30721. var b = options.buffer[pos + 2] / 255.0;
  30722. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30723. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30724. // Add vertex
  30725. positions.push(position.x, position.y, position.z);
  30726. normals.push(0, 0, 0);
  30727. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30728. }
  30729. }
  30730. // Indices
  30731. for (row = 0; row < options.subdivisions; row++) {
  30732. for (col = 0; col < options.subdivisions; col++) {
  30733. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30734. indices.push(col + 1 + row * (options.subdivisions + 1));
  30735. indices.push(col + row * (options.subdivisions + 1));
  30736. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30737. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30738. indices.push(col + row * (options.subdivisions + 1));
  30739. }
  30740. }
  30741. // Normals
  30742. VertexData.ComputeNormals(positions, indices, normals);
  30743. // Result
  30744. var vertexData = new VertexData();
  30745. vertexData.indices = indices;
  30746. vertexData.positions = positions;
  30747. vertexData.normals = normals;
  30748. vertexData.uvs = uvs;
  30749. return vertexData;
  30750. };
  30751. /**
  30752. * Creates the VertexData of the Plane.
  30753. */
  30754. VertexData.CreatePlane = function (options) {
  30755. var indices = [];
  30756. var positions = [];
  30757. var normals = [];
  30758. var uvs = [];
  30759. var width = options.width || options.size || 1;
  30760. var height = options.height || options.size || 1;
  30761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30762. // Vertices
  30763. var halfWidth = width / 2.0;
  30764. var halfHeight = height / 2.0;
  30765. positions.push(-halfWidth, -halfHeight, 0);
  30766. normals.push(0, 0, -1.0);
  30767. uvs.push(0.0, 0.0);
  30768. positions.push(halfWidth, -halfHeight, 0);
  30769. normals.push(0, 0, -1.0);
  30770. uvs.push(1.0, 0.0);
  30771. positions.push(halfWidth, halfHeight, 0);
  30772. normals.push(0, 0, -1.0);
  30773. uvs.push(1.0, 1.0);
  30774. positions.push(-halfWidth, halfHeight, 0);
  30775. normals.push(0, 0, -1.0);
  30776. uvs.push(0.0, 1.0);
  30777. // Indices
  30778. indices.push(0);
  30779. indices.push(1);
  30780. indices.push(2);
  30781. indices.push(0);
  30782. indices.push(2);
  30783. indices.push(3);
  30784. // Sides
  30785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30786. // Result
  30787. var vertexData = new VertexData();
  30788. vertexData.indices = indices;
  30789. vertexData.positions = positions;
  30790. vertexData.normals = normals;
  30791. vertexData.uvs = uvs;
  30792. return vertexData;
  30793. };
  30794. /**
  30795. * Creates the VertexData of the Disc or regular Polygon.
  30796. */
  30797. VertexData.CreateDisc = function (options) {
  30798. var positions = new Array();
  30799. var indices = new Array();
  30800. var normals = new Array();
  30801. var uvs = new Array();
  30802. var radius = options.radius || 0.5;
  30803. var tessellation = options.tessellation || 64;
  30804. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30805. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30806. // positions and uvs
  30807. positions.push(0, 0, 0); // disc center first
  30808. uvs.push(0.5, 0.5);
  30809. var theta = Math.PI * 2 * arc;
  30810. var step = theta / tessellation;
  30811. for (var a = 0; a < theta; a += step) {
  30812. var x = Math.cos(a);
  30813. var y = Math.sin(a);
  30814. var u = (x + 1) / 2;
  30815. var v = (1 - y) / 2;
  30816. positions.push(radius * x, radius * y, 0);
  30817. uvs.push(u, v);
  30818. }
  30819. if (arc === 1) {
  30820. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30821. uvs.push(uvs[2], uvs[3]);
  30822. }
  30823. //indices
  30824. var vertexNb = positions.length / 3;
  30825. for (var i = 1; i < vertexNb - 1; i++) {
  30826. indices.push(i + 1, 0, i);
  30827. }
  30828. // result
  30829. VertexData.ComputeNormals(positions, indices, normals);
  30830. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30831. var vertexData = new VertexData();
  30832. vertexData.indices = indices;
  30833. vertexData.positions = positions;
  30834. vertexData.normals = normals;
  30835. vertexData.uvs = uvs;
  30836. return vertexData;
  30837. };
  30838. /**
  30839. * Re-creates the VertexData of the Polygon for sideOrientation.
  30840. */
  30841. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30842. var faceUV = fUV || new Array(3);
  30843. var faceColors = fColors;
  30844. var colors = [];
  30845. // default face colors and UV if undefined
  30846. for (var f = 0; f < 3; f++) {
  30847. if (faceUV[f] === undefined) {
  30848. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30849. }
  30850. if (faceColors && faceColors[f] === undefined) {
  30851. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30852. }
  30853. }
  30854. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30855. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30856. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30857. var indices = polygon.getIndices();
  30858. // set face colours and textures
  30859. var idx = 0;
  30860. var face = 0;
  30861. for (var index = 0; index < normals.length; index += 3) {
  30862. //Edge Face no. 1
  30863. if (Math.abs(normals[index + 1]) < 0.001) {
  30864. face = 1;
  30865. }
  30866. //Top Face no. 0
  30867. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30868. face = 0;
  30869. }
  30870. //Bottom Face no. 2
  30871. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30872. face = 2;
  30873. }
  30874. idx = index / 3;
  30875. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30876. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30877. if (faceColors) {
  30878. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30879. }
  30880. }
  30881. // sides
  30882. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30883. // Result
  30884. var vertexData = new VertexData();
  30885. vertexData.indices = indices;
  30886. vertexData.positions = positions;
  30887. vertexData.normals = normals;
  30888. vertexData.uvs = uvs;
  30889. if (faceColors) {
  30890. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30891. vertexData.colors = totalColors;
  30892. }
  30893. return vertexData;
  30894. };
  30895. /**
  30896. * Creates the VertexData of the IcoSphere.
  30897. */
  30898. VertexData.CreateIcoSphere = function (options) {
  30899. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30900. var radius = options.radius || 1;
  30901. var flat = (options.flat === undefined) ? true : options.flat;
  30902. var subdivisions = options.subdivisions || 4;
  30903. var radiusX = options.radiusX || radius;
  30904. var radiusY = options.radiusY || radius;
  30905. var radiusZ = options.radiusZ || radius;
  30906. var t = (1 + Math.sqrt(5)) / 2;
  30907. // 12 vertex x,y,z
  30908. var ico_vertices = [
  30909. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30910. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30911. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30912. ];
  30913. // index of 3 vertex makes a face of icopshere
  30914. var ico_indices = [
  30915. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30916. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30917. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30918. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30919. ];
  30920. // vertex for uv have aliased position, not for UV
  30921. var vertices_unalias_id = [
  30922. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30923. // vertex alias
  30924. 0,
  30925. 2,
  30926. 3,
  30927. 3,
  30928. 3,
  30929. 4,
  30930. 7,
  30931. 8,
  30932. 9,
  30933. 9,
  30934. 10,
  30935. 11 // 23: B + 12
  30936. ];
  30937. // uv as integer step (not pixels !)
  30938. var ico_vertexuv = [
  30939. 5, 1, 3, 1, 6, 4, 0, 0,
  30940. 5, 3, 4, 2, 2, 2, 4, 0,
  30941. 2, 0, 1, 1, 6, 0, 6, 2,
  30942. // vertex alias (for same vertex on different faces)
  30943. 0, 4,
  30944. 3, 3,
  30945. 4, 4,
  30946. 3, 1,
  30947. 4, 2,
  30948. 4, 4,
  30949. 0, 2,
  30950. 1, 1,
  30951. 2, 2,
  30952. 3, 3,
  30953. 1, 3,
  30954. 2, 4 // 23: B + 12
  30955. ];
  30956. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30957. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30958. // First island of uv mapping
  30959. // v = 4h 3+ 2
  30960. // v = 3h 9+ 4
  30961. // v = 2h 9+ 5 B
  30962. // v = 1h 9 1 0
  30963. // v = 0h 3 8 7 A
  30964. // u = 0 1 2 3 4 5 6 *a
  30965. // Second island of uv mapping
  30966. // v = 4h 0+ B+ 4+
  30967. // v = 3h A+ 2+
  30968. // v = 2h 7+ 6 3+
  30969. // v = 1h 8+ 3+
  30970. // v = 0h
  30971. // u = 0 1 2 3 4 5 6 *a
  30972. // Face layout on texture UV mapping
  30973. // ============
  30974. // \ 4 /\ 16 / ======
  30975. // \ / \ / /\ 11 /
  30976. // \/ 7 \/ / \ /
  30977. // ======= / 10 \/
  30978. // /\ 17 /\ =======
  30979. // / \ / \ \ 15 /\
  30980. // / 8 \/ 12 \ \ / \
  30981. // ============ \/ 6 \
  30982. // \ 18 /\ ============
  30983. // \ / \ \ 5 /\ 0 /
  30984. // \/ 13 \ \ / \ /
  30985. // ======= \/ 1 \/
  30986. // =============
  30987. // /\ 19 /\ 2 /\
  30988. // / \ / \ / \
  30989. // / 14 \/ 9 \/ 3 \
  30990. // ===================
  30991. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30992. var ustep = 138 / 1024;
  30993. var vstep = 239 / 1024;
  30994. var uoffset = 60 / 1024;
  30995. var voffset = 26 / 1024;
  30996. // Second island should have margin, not to touch the first island
  30997. // avoid any borderline artefact in pixel rounding
  30998. var island_u_offset = -40 / 1024;
  30999. var island_v_offset = +20 / 1024;
  31000. // face is either island 0 or 1 :
  31001. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31002. var island = [
  31003. 0, 0, 0, 0, 1,
  31004. 0, 0, 1, 1, 0,
  31005. 0, 0, 1, 1, 0,
  31006. 0, 1, 1, 1, 0 // 15 - 19
  31007. ];
  31008. var indices = new Array();
  31009. var positions = new Array();
  31010. var normals = new Array();
  31011. var uvs = new Array();
  31012. var current_indice = 0;
  31013. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31014. var face_vertex_pos = new Array(3);
  31015. var face_vertex_uv = new Array(3);
  31016. var v012;
  31017. for (v012 = 0; v012 < 3; v012++) {
  31018. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31019. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31020. }
  31021. // create all with normals
  31022. for (var face = 0; face < 20; face++) {
  31023. // 3 vertex per face
  31024. for (v012 = 0; v012 < 3; v012++) {
  31025. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31026. var v_id = ico_indices[3 * face + v012];
  31027. // vertex have 3D position (x,y,z)
  31028. 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]);
  31029. // Normalize to get normal, then scale to radius
  31030. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31031. // uv Coordinates from vertex ID
  31032. 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);
  31033. }
  31034. // Subdivide the face (interpolate pos, norm, uv)
  31035. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31036. // - norm is linear interpolation of vertex corner normal
  31037. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31038. // - uv is linear interpolation
  31039. //
  31040. // Topology is as below for sub-divide by 2
  31041. // vertex shown as v0,v1,v2
  31042. // interp index is i1 to progress in range [v0,v1[
  31043. // interp index is i2 to progress in range [v0,v2[
  31044. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31045. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31046. //
  31047. //
  31048. // i2 v2
  31049. // ^ ^
  31050. // / / \
  31051. // / / \
  31052. // / / \
  31053. // / / (0,1) \
  31054. // / #---------\
  31055. // / / \ (0,0)'/ \
  31056. // / / \ / \
  31057. // / / \ / \
  31058. // / / (0,0) \ / (1,0) \
  31059. // / #---------#---------\
  31060. // v0 v1
  31061. //
  31062. // --------------------> i1
  31063. //
  31064. // interp of (i1,i2):
  31065. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31066. // along i1 : lerp(x0,x1, i1/(S-i2))
  31067. //
  31068. // centroid of triangle is needed to get help normal computation
  31069. // (c1,c2) are used for centroid location
  31070. var interp_vertex = function (i1, i2, c1, c2) {
  31071. // vertex is interpolated from
  31072. // - face_vertex_pos[0..2]
  31073. // - face_vertex_uv[0..2]
  31074. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31075. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31076. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31077. pos_interp.normalize();
  31078. var vertex_normal;
  31079. if (flat) {
  31080. // in flat mode, recalculate normal as face centroid normal
  31081. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31082. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31083. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31084. }
  31085. else {
  31086. // in smooth mode, recalculate normal from each single vertex position
  31087. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31088. }
  31089. // Vertex normal need correction due to X,Y,Z radius scaling
  31090. vertex_normal.x /= radiusX;
  31091. vertex_normal.y /= radiusY;
  31092. vertex_normal.z /= radiusZ;
  31093. vertex_normal.normalize();
  31094. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31095. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31096. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31097. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31098. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31099. uvs.push(uv_interp.x, uv_interp.y);
  31100. // push each vertex has member of a face
  31101. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31102. indices.push(current_indice);
  31103. current_indice++;
  31104. };
  31105. for (var i2 = 0; i2 < subdivisions; i2++) {
  31106. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31107. // face : (i1,i2) for /\ :
  31108. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31109. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31110. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31111. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31112. if (i1 + i2 + 1 < subdivisions) {
  31113. // face : (i1,i2)' for \/ :
  31114. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31115. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31116. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31117. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31118. }
  31119. }
  31120. }
  31121. }
  31122. // Sides
  31123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31124. // Result
  31125. var vertexData = new VertexData();
  31126. vertexData.indices = indices;
  31127. vertexData.positions = positions;
  31128. vertexData.normals = normals;
  31129. vertexData.uvs = uvs;
  31130. return vertexData;
  31131. };
  31132. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31133. /**
  31134. * Creates the VertexData of the Polyhedron.
  31135. */
  31136. VertexData.CreatePolyhedron = function (options) {
  31137. // provided polyhedron types :
  31138. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31139. // 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)
  31140. var polyhedra = [];
  31141. 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]] };
  31142. 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]] };
  31143. polyhedra[2] = {
  31144. 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]],
  31145. 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]]
  31146. };
  31147. polyhedra[3] = {
  31148. 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]],
  31149. 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]]
  31150. };
  31151. polyhedra[4] = {
  31152. 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]],
  31153. 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]]
  31154. };
  31155. 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]] };
  31156. 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]] };
  31157. 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]] };
  31158. 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]] };
  31159. 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]] };
  31160. 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]] };
  31161. 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]] };
  31162. 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]] };
  31163. 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]] };
  31164. polyhedra[14] = {
  31165. 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]],
  31166. 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]]
  31167. };
  31168. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31169. var size = options.size;
  31170. var sizeX = options.sizeX || size || 1;
  31171. var sizeY = options.sizeY || size || 1;
  31172. var sizeZ = options.sizeZ || size || 1;
  31173. var data = options.custom || polyhedra[type];
  31174. var nbfaces = data.face.length;
  31175. var faceUV = options.faceUV || new Array(nbfaces);
  31176. var faceColors = options.faceColors;
  31177. var flat = (options.flat === undefined) ? true : options.flat;
  31178. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31179. var positions = new Array();
  31180. var indices = new Array();
  31181. var normals = new Array();
  31182. var uvs = new Array();
  31183. var colors = new Array();
  31184. var index = 0;
  31185. var faceIdx = 0; // face cursor in the array "indexes"
  31186. var indexes = new Array();
  31187. var i = 0;
  31188. var f = 0;
  31189. var u, v, ang, x, y, tmp;
  31190. // default face colors and UV if undefined
  31191. if (flat) {
  31192. for (f = 0; f < nbfaces; f++) {
  31193. if (faceColors && faceColors[f] === undefined) {
  31194. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31195. }
  31196. if (faceUV && faceUV[f] === undefined) {
  31197. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31198. }
  31199. }
  31200. }
  31201. if (!flat) {
  31202. for (i = 0; i < data.vertex.length; i++) {
  31203. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31204. uvs.push(0, 0);
  31205. }
  31206. for (f = 0; f < nbfaces; f++) {
  31207. for (i = 0; i < data.face[f].length - 2; i++) {
  31208. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31209. }
  31210. }
  31211. }
  31212. else {
  31213. for (f = 0; f < nbfaces; f++) {
  31214. var fl = data.face[f].length; // number of vertices of the current face
  31215. ang = 2 * Math.PI / fl;
  31216. x = 0.5 * Math.tan(ang / 2);
  31217. y = 0.5;
  31218. // positions, uvs, colors
  31219. for (i = 0; i < fl; i++) {
  31220. // positions
  31221. 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);
  31222. indexes.push(index);
  31223. index++;
  31224. // uvs
  31225. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31226. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31227. uvs.push(u, v);
  31228. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31229. y = x * Math.sin(ang) + y * Math.cos(ang);
  31230. x = tmp;
  31231. // colors
  31232. if (faceColors) {
  31233. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31234. }
  31235. }
  31236. // indices from indexes
  31237. for (i = 0; i < fl - 2; i++) {
  31238. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31239. }
  31240. faceIdx += fl;
  31241. }
  31242. }
  31243. VertexData.ComputeNormals(positions, indices, normals);
  31244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31245. var vertexData = new VertexData();
  31246. vertexData.positions = positions;
  31247. vertexData.indices = indices;
  31248. vertexData.normals = normals;
  31249. vertexData.uvs = uvs;
  31250. if (faceColors && flat) {
  31251. vertexData.colors = colors;
  31252. }
  31253. return vertexData;
  31254. };
  31255. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31256. /**
  31257. * Creates the VertexData of the Torus Knot.
  31258. */
  31259. VertexData.CreateTorusKnot = function (options) {
  31260. var indices = new Array();
  31261. var positions = new Array();
  31262. var normals = new Array();
  31263. var uvs = new Array();
  31264. var radius = options.radius || 2;
  31265. var tube = options.tube || 0.5;
  31266. var radialSegments = options.radialSegments || 32;
  31267. var tubularSegments = options.tubularSegments || 32;
  31268. var p = options.p || 2;
  31269. var q = options.q || 3;
  31270. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31271. // Helper
  31272. var getPos = function (angle) {
  31273. var cu = Math.cos(angle);
  31274. var su = Math.sin(angle);
  31275. var quOverP = q / p * angle;
  31276. var cs = Math.cos(quOverP);
  31277. var tx = radius * (2 + cs) * 0.5 * cu;
  31278. var ty = radius * (2 + cs) * su * 0.5;
  31279. var tz = radius * Math.sin(quOverP) * 0.5;
  31280. return new BABYLON.Vector3(tx, ty, tz);
  31281. };
  31282. // Vertices
  31283. var i;
  31284. var j;
  31285. for (i = 0; i <= radialSegments; i++) {
  31286. var modI = i % radialSegments;
  31287. var u = modI / radialSegments * 2 * p * Math.PI;
  31288. var p1 = getPos(u);
  31289. var p2 = getPos(u + 0.01);
  31290. var tang = p2.subtract(p1);
  31291. var n = p2.add(p1);
  31292. var bitan = BABYLON.Vector3.Cross(tang, n);
  31293. n = BABYLON.Vector3.Cross(bitan, tang);
  31294. bitan.normalize();
  31295. n.normalize();
  31296. for (j = 0; j < tubularSegments; j++) {
  31297. var modJ = j % tubularSegments;
  31298. var v = modJ / tubularSegments * 2 * Math.PI;
  31299. var cx = -tube * Math.cos(v);
  31300. var cy = tube * Math.sin(v);
  31301. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31302. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31303. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31304. uvs.push(i / radialSegments);
  31305. uvs.push(j / tubularSegments);
  31306. }
  31307. }
  31308. for (i = 0; i < radialSegments; i++) {
  31309. for (j = 0; j < tubularSegments; j++) {
  31310. var jNext = (j + 1) % tubularSegments;
  31311. var a = i * tubularSegments + j;
  31312. var b = (i + 1) * tubularSegments + j;
  31313. var c = (i + 1) * tubularSegments + jNext;
  31314. var d = i * tubularSegments + jNext;
  31315. indices.push(d);
  31316. indices.push(b);
  31317. indices.push(a);
  31318. indices.push(d);
  31319. indices.push(c);
  31320. indices.push(b);
  31321. }
  31322. }
  31323. // Normals
  31324. VertexData.ComputeNormals(positions, indices, normals);
  31325. // Sides
  31326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31327. // Result
  31328. var vertexData = new VertexData();
  31329. vertexData.indices = indices;
  31330. vertexData.positions = positions;
  31331. vertexData.normals = normals;
  31332. vertexData.uvs = uvs;
  31333. return vertexData;
  31334. };
  31335. // Tools
  31336. /**
  31337. * @param {any} - positions (number[] or Float32Array)
  31338. * @param {any} - indices (number[] or Uint16Array)
  31339. * @param {any} - normals (number[] or Float32Array)
  31340. * options (optional) :
  31341. * facetPositions : optional array of facet positions (vector3)
  31342. * facetNormals : optional array of facet normals (vector3)
  31343. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31344. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31345. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31346. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31347. * bInfo : optional bounding info, required for facetPartitioning computation
  31348. * useRightHandedSystem: optional boolean to for right handed system computation
  31349. * depthSort : optional boolean to enable the facet depth sort computation
  31350. * distanceTo : optional Vector3 to compute the facet depth from this location
  31351. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31352. */
  31353. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31354. // temporary scalar variables
  31355. var index = 0; // facet index
  31356. var p1p2x = 0.0; // p1p2 vector x coordinate
  31357. var p1p2y = 0.0; // p1p2 vector y coordinate
  31358. var p1p2z = 0.0; // p1p2 vector z coordinate
  31359. var p3p2x = 0.0; // p3p2 vector x coordinate
  31360. var p3p2y = 0.0; // p3p2 vector y coordinate
  31361. var p3p2z = 0.0; // p3p2 vector z coordinate
  31362. var faceNormalx = 0.0; // facet normal x coordinate
  31363. var faceNormaly = 0.0; // facet normal y coordinate
  31364. var faceNormalz = 0.0; // facet normal z coordinate
  31365. var length = 0.0; // facet normal length before normalization
  31366. var v1x = 0; // vector1 x index in the positions array
  31367. var v1y = 0; // vector1 y index in the positions array
  31368. var v1z = 0; // vector1 z index in the positions array
  31369. var v2x = 0; // vector2 x index in the positions array
  31370. var v2y = 0; // vector2 y index in the positions array
  31371. var v2z = 0; // vector2 z index in the positions array
  31372. var v3x = 0; // vector3 x index in the positions array
  31373. var v3y = 0; // vector3 y index in the positions array
  31374. var v3z = 0; // vector3 z index in the positions array
  31375. var computeFacetNormals = false;
  31376. var computeFacetPositions = false;
  31377. var computeFacetPartitioning = false;
  31378. var computeDepthSort = false;
  31379. var faceNormalSign = 1;
  31380. var ratio = 0;
  31381. var distanceTo = null;
  31382. if (options) {
  31383. computeFacetNormals = (options.facetNormals) ? true : false;
  31384. computeFacetPositions = (options.facetPositions) ? true : false;
  31385. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31386. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31387. ratio = options.ratio || 0;
  31388. computeDepthSort = (options.depthSort) ? true : false;
  31389. distanceTo = (options.distanceTo);
  31390. if (computeDepthSort) {
  31391. if (distanceTo === undefined) {
  31392. distanceTo = BABYLON.Vector3.Zero();
  31393. }
  31394. var depthSortedFacets = options.depthSortedFacets;
  31395. }
  31396. }
  31397. // facetPartitioning reinit if needed
  31398. var xSubRatio = 0;
  31399. var ySubRatio = 0;
  31400. var zSubRatio = 0;
  31401. var subSq = 0;
  31402. if (computeFacetPartitioning && options && options.bbSize) {
  31403. var ox = 0; // X partitioning index for facet position
  31404. var oy = 0; // Y partinioning index for facet position
  31405. var oz = 0; // Z partinioning index for facet position
  31406. var b1x = 0; // X partitioning index for facet v1 vertex
  31407. var b1y = 0; // Y partitioning index for facet v1 vertex
  31408. var b1z = 0; // z partitioning index for facet v1 vertex
  31409. var b2x = 0; // X partitioning index for facet v2 vertex
  31410. var b2y = 0; // Y partitioning index for facet v2 vertex
  31411. var b2z = 0; // Z partitioning index for facet v2 vertex
  31412. var b3x = 0; // X partitioning index for facet v3 vertex
  31413. var b3y = 0; // Y partitioning index for facet v3 vertex
  31414. var b3z = 0; // Z partitioning index for facet v3 vertex
  31415. var block_idx_o = 0; // facet barycenter block index
  31416. var block_idx_v1 = 0; // v1 vertex block index
  31417. var block_idx_v2 = 0; // v2 vertex block index
  31418. var block_idx_v3 = 0; // v3 vertex block index
  31419. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31420. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31421. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31422. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31423. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31424. subSq = options.subDiv.max * options.subDiv.max;
  31425. options.facetPartitioning.length = 0;
  31426. }
  31427. // reset the normals
  31428. for (index = 0; index < positions.length; index++) {
  31429. normals[index] = 0.0;
  31430. }
  31431. // Loop : 1 indice triplet = 1 facet
  31432. var nbFaces = (indices.length / 3) | 0;
  31433. for (index = 0; index < nbFaces; index++) {
  31434. // get the indexes of the coordinates of each vertex of the facet
  31435. v1x = indices[index * 3] * 3;
  31436. v1y = v1x + 1;
  31437. v1z = v1x + 2;
  31438. v2x = indices[index * 3 + 1] * 3;
  31439. v2y = v2x + 1;
  31440. v2z = v2x + 2;
  31441. v3x = indices[index * 3 + 2] * 3;
  31442. v3y = v3x + 1;
  31443. v3z = v3x + 2;
  31444. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31445. p1p2y = positions[v1y] - positions[v2y];
  31446. p1p2z = positions[v1z] - positions[v2z];
  31447. p3p2x = positions[v3x] - positions[v2x];
  31448. p3p2y = positions[v3y] - positions[v2y];
  31449. p3p2z = positions[v3z] - positions[v2z];
  31450. // compute the face normal with the cross product
  31451. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31452. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31453. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31454. // normalize this normal and store it in the array facetData
  31455. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31456. length = (length === 0) ? 1.0 : length;
  31457. faceNormalx /= length;
  31458. faceNormaly /= length;
  31459. faceNormalz /= length;
  31460. if (computeFacetNormals && options) {
  31461. options.facetNormals[index].x = faceNormalx;
  31462. options.facetNormals[index].y = faceNormaly;
  31463. options.facetNormals[index].z = faceNormalz;
  31464. }
  31465. if (computeFacetPositions && options) {
  31466. // compute and the facet barycenter coordinates in the array facetPositions
  31467. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31468. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31469. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31470. }
  31471. if (computeFacetPartitioning && options) {
  31472. // store the facet indexes in arrays in the main facetPartitioning array :
  31473. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31474. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31475. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31476. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31477. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31478. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31479. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31480. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31481. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31482. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31483. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31484. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31485. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31486. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31487. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31488. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31489. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31490. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31491. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31492. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31493. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31494. // push each facet index in each block containing the vertex
  31495. options.facetPartitioning[block_idx_v1].push(index);
  31496. if (block_idx_v2 != block_idx_v1) {
  31497. options.facetPartitioning[block_idx_v2].push(index);
  31498. }
  31499. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31500. options.facetPartitioning[block_idx_v3].push(index);
  31501. }
  31502. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31503. options.facetPartitioning[block_idx_o].push(index);
  31504. }
  31505. }
  31506. if (computeDepthSort && options && options.facetPositions) {
  31507. var dsf = depthSortedFacets[index];
  31508. dsf.ind = index * 3;
  31509. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31510. }
  31511. // compute the normals anyway
  31512. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31513. normals[v1y] += faceNormaly;
  31514. normals[v1z] += faceNormalz;
  31515. normals[v2x] += faceNormalx;
  31516. normals[v2y] += faceNormaly;
  31517. normals[v2z] += faceNormalz;
  31518. normals[v3x] += faceNormalx;
  31519. normals[v3y] += faceNormaly;
  31520. normals[v3z] += faceNormalz;
  31521. }
  31522. // last normalization of each normal
  31523. for (index = 0; index < normals.length / 3; index++) {
  31524. faceNormalx = normals[index * 3];
  31525. faceNormaly = normals[index * 3 + 1];
  31526. faceNormalz = normals[index * 3 + 2];
  31527. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31528. length = (length === 0) ? 1.0 : length;
  31529. faceNormalx /= length;
  31530. faceNormaly /= length;
  31531. faceNormalz /= length;
  31532. normals[index * 3] = faceNormalx;
  31533. normals[index * 3 + 1] = faceNormaly;
  31534. normals[index * 3 + 2] = faceNormalz;
  31535. }
  31536. };
  31537. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31538. var li = indices.length;
  31539. var ln = normals.length;
  31540. var i;
  31541. var n;
  31542. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31543. switch (sideOrientation) {
  31544. case BABYLON.Mesh.FRONTSIDE:
  31545. // nothing changed
  31546. break;
  31547. case BABYLON.Mesh.BACKSIDE:
  31548. var tmp;
  31549. // indices
  31550. for (i = 0; i < li; i += 3) {
  31551. tmp = indices[i];
  31552. indices[i] = indices[i + 2];
  31553. indices[i + 2] = tmp;
  31554. }
  31555. // normals
  31556. for (n = 0; n < ln; n++) {
  31557. normals[n] = -normals[n];
  31558. }
  31559. break;
  31560. case BABYLON.Mesh.DOUBLESIDE:
  31561. // positions
  31562. var lp = positions.length;
  31563. var l = lp / 3;
  31564. for (var p = 0; p < lp; p++) {
  31565. positions[lp + p] = positions[p];
  31566. }
  31567. // indices
  31568. for (i = 0; i < li; i += 3) {
  31569. indices[i + li] = indices[i + 2] + l;
  31570. indices[i + 1 + li] = indices[i + 1] + l;
  31571. indices[i + 2 + li] = indices[i] + l;
  31572. }
  31573. // normals
  31574. for (n = 0; n < ln; n++) {
  31575. normals[ln + n] = -normals[n];
  31576. }
  31577. // uvs
  31578. var lu = uvs.length;
  31579. var u = 0;
  31580. for (u = 0; u < lu; u++) {
  31581. uvs[u + lu] = uvs[u];
  31582. }
  31583. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31584. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31585. u = 0;
  31586. for (i = 0; i < lu / 2; i++) {
  31587. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31588. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31589. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31590. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31591. u += 2;
  31592. }
  31593. break;
  31594. }
  31595. };
  31596. /**
  31597. * Creates a new VertexData from the imported parameters.
  31598. */
  31599. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31600. var vertexData = new VertexData();
  31601. // positions
  31602. var positions = parsedVertexData.positions;
  31603. if (positions) {
  31604. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31605. }
  31606. // normals
  31607. var normals = parsedVertexData.normals;
  31608. if (normals) {
  31609. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31610. }
  31611. // tangents
  31612. var tangents = parsedVertexData.tangents;
  31613. if (tangents) {
  31614. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31615. }
  31616. // uvs
  31617. var uvs = parsedVertexData.uvs;
  31618. if (uvs) {
  31619. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31620. }
  31621. // uv2s
  31622. var uv2s = parsedVertexData.uv2s;
  31623. if (uv2s) {
  31624. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31625. }
  31626. // uv3s
  31627. var uv3s = parsedVertexData.uv3s;
  31628. if (uv3s) {
  31629. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31630. }
  31631. // uv4s
  31632. var uv4s = parsedVertexData.uv4s;
  31633. if (uv4s) {
  31634. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31635. }
  31636. // uv5s
  31637. var uv5s = parsedVertexData.uv5s;
  31638. if (uv5s) {
  31639. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31640. }
  31641. // uv6s
  31642. var uv6s = parsedVertexData.uv6s;
  31643. if (uv6s) {
  31644. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31645. }
  31646. // colors
  31647. var colors = parsedVertexData.colors;
  31648. if (colors) {
  31649. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31650. }
  31651. // matricesIndices
  31652. var matricesIndices = parsedVertexData.matricesIndices;
  31653. if (matricesIndices) {
  31654. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31655. }
  31656. // matricesWeights
  31657. var matricesWeights = parsedVertexData.matricesWeights;
  31658. if (matricesWeights) {
  31659. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31660. }
  31661. // indices
  31662. var indices = parsedVertexData.indices;
  31663. if (indices) {
  31664. vertexData.indices = indices;
  31665. }
  31666. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31667. };
  31668. return VertexData;
  31669. }());
  31670. BABYLON.VertexData = VertexData;
  31671. })(BABYLON || (BABYLON = {}));
  31672. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31673. var BABYLON;
  31674. (function (BABYLON) {
  31675. var Geometry = /** @class */ (function () {
  31676. function Geometry(id, scene, vertexData, updatable, mesh) {
  31677. if (updatable === void 0) { updatable = false; }
  31678. if (mesh === void 0) { mesh = null; }
  31679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31680. this._totalVertices = 0;
  31681. this._isDisposed = false;
  31682. this._indexBufferIsUpdatable = false;
  31683. this.id = id;
  31684. this._engine = scene.getEngine();
  31685. this._meshes = [];
  31686. this._scene = scene;
  31687. //Init vertex buffer cache
  31688. this._vertexBuffers = {};
  31689. this._indices = [];
  31690. this._updatable = updatable;
  31691. // vertexData
  31692. if (vertexData) {
  31693. this.setAllVerticesData(vertexData, updatable);
  31694. }
  31695. else {
  31696. this._totalVertices = 0;
  31697. this._indices = [];
  31698. }
  31699. if (this._engine.getCaps().vertexArrayObject) {
  31700. this._vertexArrayObjects = {};
  31701. }
  31702. // applyToMesh
  31703. if (mesh) {
  31704. if (mesh.getClassName() === "LinesMesh") {
  31705. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31706. this.updateExtend();
  31707. }
  31708. this.applyToMesh(mesh);
  31709. mesh.computeWorldMatrix(true);
  31710. }
  31711. }
  31712. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31713. /**
  31714. * 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
  31715. * @returns The Bias Vector
  31716. */
  31717. get: function () {
  31718. return this._boundingBias;
  31719. },
  31720. set: function (value) {
  31721. if (this._boundingBias && this._boundingBias.equals(value)) {
  31722. return;
  31723. }
  31724. this._boundingBias = value.clone();
  31725. this.updateBoundingInfo(true, null);
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. Geometry.CreateGeometryForMesh = function (mesh) {
  31731. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31732. geometry.applyToMesh(mesh);
  31733. return geometry;
  31734. };
  31735. Object.defineProperty(Geometry.prototype, "extend", {
  31736. get: function () {
  31737. return this._extend;
  31738. },
  31739. enumerable: true,
  31740. configurable: true
  31741. });
  31742. Geometry.prototype.getScene = function () {
  31743. return this._scene;
  31744. };
  31745. Geometry.prototype.getEngine = function () {
  31746. return this._engine;
  31747. };
  31748. Geometry.prototype.isReady = function () {
  31749. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31750. };
  31751. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31752. get: function () {
  31753. for (var index = 0; index < this._meshes.length; index++) {
  31754. if (!this._meshes[index].doNotSerialize) {
  31755. return false;
  31756. }
  31757. }
  31758. return true;
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. Geometry.prototype._rebuild = function () {
  31764. if (this._vertexArrayObjects) {
  31765. this._vertexArrayObjects = {};
  31766. }
  31767. // Index buffer
  31768. if (this._meshes.length !== 0 && this._indices) {
  31769. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31770. }
  31771. // Vertex buffers
  31772. for (var key in this._vertexBuffers) {
  31773. var vertexBuffer = this._vertexBuffers[key];
  31774. vertexBuffer._rebuild();
  31775. }
  31776. };
  31777. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31778. vertexData.applyToGeometry(this, updatable);
  31779. this.notifyUpdate();
  31780. };
  31781. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31782. if (updatable === void 0) { updatable = false; }
  31783. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31784. this.setVerticesBuffer(buffer);
  31785. };
  31786. Geometry.prototype.removeVerticesData = function (kind) {
  31787. if (this._vertexBuffers[kind]) {
  31788. this._vertexBuffers[kind].dispose();
  31789. delete this._vertexBuffers[kind];
  31790. }
  31791. };
  31792. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31793. var kind = buffer.getKind();
  31794. if (this._vertexBuffers[kind]) {
  31795. this._vertexBuffers[kind].dispose();
  31796. }
  31797. this._vertexBuffers[kind] = buffer;
  31798. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31799. var data = buffer.getData();
  31800. var stride = buffer.getStrideSize();
  31801. this._totalVertices = data.length / stride;
  31802. this.updateExtend(data, stride);
  31803. this._resetPointsArrayCache();
  31804. var meshes = this._meshes;
  31805. var numOfMeshes = meshes.length;
  31806. for (var index = 0; index < numOfMeshes; index++) {
  31807. var mesh = meshes[index];
  31808. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31809. mesh._createGlobalSubMesh(false);
  31810. mesh.computeWorldMatrix(true);
  31811. }
  31812. }
  31813. this.notifyUpdate(kind);
  31814. if (this._vertexArrayObjects) {
  31815. this._disposeVertexArrayObjects();
  31816. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31817. }
  31818. };
  31819. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31820. var vertexBuffer = this.getVertexBuffer(kind);
  31821. if (!vertexBuffer) {
  31822. return;
  31823. }
  31824. vertexBuffer.updateDirectly(data, offset);
  31825. this.notifyUpdate(kind);
  31826. };
  31827. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31828. if (updateExtends === void 0) { updateExtends = false; }
  31829. var vertexBuffer = this.getVertexBuffer(kind);
  31830. if (!vertexBuffer) {
  31831. return;
  31832. }
  31833. vertexBuffer.update(data);
  31834. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31835. var stride = vertexBuffer.getStrideSize();
  31836. this._totalVertices = data.length / stride;
  31837. this.updateBoundingInfo(updateExtends, data);
  31838. }
  31839. this.notifyUpdate(kind);
  31840. };
  31841. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31842. if (updateExtends) {
  31843. this.updateExtend(data);
  31844. }
  31845. var meshes = this._meshes;
  31846. var numOfMeshes = meshes.length;
  31847. this._resetPointsArrayCache();
  31848. for (var index = 0; index < numOfMeshes; index++) {
  31849. var mesh = meshes[index];
  31850. if (updateExtends) {
  31851. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31852. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31853. var subMesh = mesh.subMeshes[subIndex];
  31854. subMesh.refreshBoundingInfo();
  31855. }
  31856. }
  31857. }
  31858. };
  31859. Geometry.prototype._bind = function (effect, indexToBind) {
  31860. if (!effect) {
  31861. return;
  31862. }
  31863. if (indexToBind === undefined) {
  31864. indexToBind = this._indexBuffer;
  31865. }
  31866. var vbs = this.getVertexBuffers();
  31867. if (!vbs) {
  31868. return;
  31869. }
  31870. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31871. this._engine.bindBuffers(vbs, indexToBind, effect);
  31872. return;
  31873. }
  31874. // Using VAO
  31875. if (!this._vertexArrayObjects[effect.key]) {
  31876. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31877. }
  31878. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31879. };
  31880. Geometry.prototype.getTotalVertices = function () {
  31881. if (!this.isReady()) {
  31882. return 0;
  31883. }
  31884. return this._totalVertices;
  31885. };
  31886. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31887. var vertexBuffer = this.getVertexBuffer(kind);
  31888. if (!vertexBuffer) {
  31889. return null;
  31890. }
  31891. var orig = vertexBuffer.getData();
  31892. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31893. return orig;
  31894. }
  31895. else {
  31896. var len = orig.length;
  31897. var copy = [];
  31898. for (var i = 0; i < len; i++) {
  31899. copy.push(orig[i]);
  31900. }
  31901. return copy;
  31902. }
  31903. };
  31904. /**
  31905. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31906. * Possible `kind` values :
  31907. * - BABYLON.VertexBuffer.PositionKind
  31908. * - BABYLON.VertexBuffer.UVKind
  31909. * - BABYLON.VertexBuffer.UV2Kind
  31910. * - BABYLON.VertexBuffer.UV3Kind
  31911. * - BABYLON.VertexBuffer.UV4Kind
  31912. * - BABYLON.VertexBuffer.UV5Kind
  31913. * - BABYLON.VertexBuffer.UV6Kind
  31914. * - BABYLON.VertexBuffer.ColorKind
  31915. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31916. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31917. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31918. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31919. */
  31920. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31921. var vb = this._vertexBuffers[kind];
  31922. if (!vb) {
  31923. return false;
  31924. }
  31925. return vb.isUpdatable();
  31926. };
  31927. Geometry.prototype.getVertexBuffer = function (kind) {
  31928. if (!this.isReady()) {
  31929. return null;
  31930. }
  31931. return this._vertexBuffers[kind];
  31932. };
  31933. Geometry.prototype.getVertexBuffers = function () {
  31934. if (!this.isReady()) {
  31935. return null;
  31936. }
  31937. return this._vertexBuffers;
  31938. };
  31939. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31940. if (!this._vertexBuffers) {
  31941. if (this._delayInfo) {
  31942. return this._delayInfo.indexOf(kind) !== -1;
  31943. }
  31944. return false;
  31945. }
  31946. return this._vertexBuffers[kind] !== undefined;
  31947. };
  31948. Geometry.prototype.getVerticesDataKinds = function () {
  31949. var result = [];
  31950. var kind;
  31951. if (!this._vertexBuffers && this._delayInfo) {
  31952. for (kind in this._delayInfo) {
  31953. result.push(kind);
  31954. }
  31955. }
  31956. else {
  31957. for (kind in this._vertexBuffers) {
  31958. result.push(kind);
  31959. }
  31960. }
  31961. return result;
  31962. };
  31963. Geometry.prototype.updateIndices = function (indices, offset) {
  31964. if (!this._indexBuffer) {
  31965. return;
  31966. }
  31967. if (!this._indexBufferIsUpdatable) {
  31968. this.setIndices(indices, null, true);
  31969. }
  31970. else {
  31971. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31972. }
  31973. };
  31974. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31975. if (totalVertices === void 0) { totalVertices = null; }
  31976. if (updatable === void 0) { updatable = false; }
  31977. if (this._indexBuffer) {
  31978. this._engine._releaseBuffer(this._indexBuffer);
  31979. }
  31980. this._disposeVertexArrayObjects();
  31981. this._indices = indices;
  31982. this._indexBufferIsUpdatable = updatable;
  31983. if (this._meshes.length !== 0 && this._indices) {
  31984. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31985. }
  31986. if (totalVertices != undefined) {
  31987. this._totalVertices = totalVertices;
  31988. }
  31989. var meshes = this._meshes;
  31990. var numOfMeshes = meshes.length;
  31991. for (var index = 0; index < numOfMeshes; index++) {
  31992. meshes[index]._createGlobalSubMesh(true);
  31993. }
  31994. this.notifyUpdate();
  31995. };
  31996. Geometry.prototype.getTotalIndices = function () {
  31997. if (!this.isReady()) {
  31998. return 0;
  31999. }
  32000. return this._indices.length;
  32001. };
  32002. Geometry.prototype.getIndices = function (copyWhenShared) {
  32003. if (!this.isReady()) {
  32004. return null;
  32005. }
  32006. var orig = this._indices;
  32007. if (!copyWhenShared || this._meshes.length === 1) {
  32008. return orig;
  32009. }
  32010. else {
  32011. var len = orig.length;
  32012. var copy = [];
  32013. for (var i = 0; i < len; i++) {
  32014. copy.push(orig[i]);
  32015. }
  32016. return copy;
  32017. }
  32018. };
  32019. Geometry.prototype.getIndexBuffer = function () {
  32020. if (!this.isReady()) {
  32021. return null;
  32022. }
  32023. return this._indexBuffer;
  32024. };
  32025. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32026. if (effect === void 0) { effect = null; }
  32027. if (!effect || !this._vertexArrayObjects) {
  32028. return;
  32029. }
  32030. if (this._vertexArrayObjects[effect.key]) {
  32031. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32032. delete this._vertexArrayObjects[effect.key];
  32033. }
  32034. };
  32035. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32036. var meshes = this._meshes;
  32037. var index = meshes.indexOf(mesh);
  32038. if (index === -1) {
  32039. return;
  32040. }
  32041. meshes.splice(index, 1);
  32042. mesh._geometry = null;
  32043. if (meshes.length === 0 && shouldDispose) {
  32044. this.dispose();
  32045. }
  32046. };
  32047. Geometry.prototype.applyToMesh = function (mesh) {
  32048. if (mesh._geometry === this) {
  32049. return;
  32050. }
  32051. var previousGeometry = mesh._geometry;
  32052. if (previousGeometry) {
  32053. previousGeometry.releaseForMesh(mesh);
  32054. }
  32055. var meshes = this._meshes;
  32056. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32057. mesh._geometry = this;
  32058. this._scene.pushGeometry(this);
  32059. meshes.push(mesh);
  32060. if (this.isReady()) {
  32061. this._applyToMesh(mesh);
  32062. }
  32063. else {
  32064. mesh._boundingInfo = this._boundingInfo;
  32065. }
  32066. };
  32067. Geometry.prototype.updateExtend = function (data, stride) {
  32068. if (data === void 0) { data = null; }
  32069. if (!data) {
  32070. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32071. }
  32072. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32073. };
  32074. Geometry.prototype._applyToMesh = function (mesh) {
  32075. var numOfMeshes = this._meshes.length;
  32076. // vertexBuffers
  32077. for (var kind in this._vertexBuffers) {
  32078. if (numOfMeshes === 1) {
  32079. this._vertexBuffers[kind].create();
  32080. }
  32081. var buffer = this._vertexBuffers[kind].getBuffer();
  32082. if (buffer)
  32083. buffer.references = numOfMeshes;
  32084. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32085. if (!this._extend) {
  32086. this.updateExtend(this._vertexBuffers[kind].getData());
  32087. }
  32088. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32089. mesh._createGlobalSubMesh(false);
  32090. //bounding info was just created again, world matrix should be applied again.
  32091. mesh._updateBoundingInfo();
  32092. }
  32093. }
  32094. // indexBuffer
  32095. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32096. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32097. }
  32098. if (this._indexBuffer) {
  32099. this._indexBuffer.references = numOfMeshes;
  32100. }
  32101. };
  32102. Geometry.prototype.notifyUpdate = function (kind) {
  32103. if (this.onGeometryUpdated) {
  32104. this.onGeometryUpdated(this, kind);
  32105. }
  32106. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32107. var mesh = _a[_i];
  32108. mesh._markSubMeshesAsAttributesDirty();
  32109. }
  32110. };
  32111. Geometry.prototype.load = function (scene, onLoaded) {
  32112. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32113. return;
  32114. }
  32115. if (this.isReady()) {
  32116. if (onLoaded) {
  32117. onLoaded();
  32118. }
  32119. return;
  32120. }
  32121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32122. this._queueLoad(scene, onLoaded);
  32123. };
  32124. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32125. var _this = this;
  32126. if (!this.delayLoadingFile) {
  32127. return;
  32128. }
  32129. scene._addPendingData(this);
  32130. scene._loadFile(this.delayLoadingFile, function (data) {
  32131. if (!_this._delayLoadingFunction) {
  32132. return;
  32133. }
  32134. _this._delayLoadingFunction(JSON.parse(data), _this);
  32135. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32136. _this._delayInfo = [];
  32137. scene._removePendingData(_this);
  32138. var meshes = _this._meshes;
  32139. var numOfMeshes = meshes.length;
  32140. for (var index = 0; index < numOfMeshes; index++) {
  32141. _this._applyToMesh(meshes[index]);
  32142. }
  32143. if (onLoaded) {
  32144. onLoaded();
  32145. }
  32146. }, undefined, true);
  32147. };
  32148. /**
  32149. * Invert the geometry to move from a right handed system to a left handed one.
  32150. */
  32151. Geometry.prototype.toLeftHanded = function () {
  32152. // Flip faces
  32153. var tIndices = this.getIndices(false);
  32154. if (tIndices != null && tIndices.length > 0) {
  32155. for (var i = 0; i < tIndices.length; i += 3) {
  32156. var tTemp = tIndices[i + 0];
  32157. tIndices[i + 0] = tIndices[i + 2];
  32158. tIndices[i + 2] = tTemp;
  32159. }
  32160. this.setIndices(tIndices);
  32161. }
  32162. // Negate position.z
  32163. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32164. if (tPositions != null && tPositions.length > 0) {
  32165. for (var i = 0; i < tPositions.length; i += 3) {
  32166. tPositions[i + 2] = -tPositions[i + 2];
  32167. }
  32168. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32169. }
  32170. // Negate normal.z
  32171. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32172. if (tNormals != null && tNormals.length > 0) {
  32173. for (var i = 0; i < tNormals.length; i += 3) {
  32174. tNormals[i + 2] = -tNormals[i + 2];
  32175. }
  32176. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32177. }
  32178. };
  32179. // Cache
  32180. Geometry.prototype._resetPointsArrayCache = function () {
  32181. this._positions = null;
  32182. };
  32183. Geometry.prototype._generatePointsArray = function () {
  32184. if (this._positions)
  32185. return true;
  32186. this._positions = [];
  32187. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32188. if (!data) {
  32189. return false;
  32190. }
  32191. for (var index = 0; index < data.length; index += 3) {
  32192. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32193. }
  32194. return true;
  32195. };
  32196. Geometry.prototype.isDisposed = function () {
  32197. return this._isDisposed;
  32198. };
  32199. Geometry.prototype._disposeVertexArrayObjects = function () {
  32200. if (this._vertexArrayObjects) {
  32201. for (var kind in this._vertexArrayObjects) {
  32202. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32203. }
  32204. this._vertexArrayObjects = {};
  32205. }
  32206. };
  32207. Geometry.prototype.dispose = function () {
  32208. var meshes = this._meshes;
  32209. var numOfMeshes = meshes.length;
  32210. var index;
  32211. for (index = 0; index < numOfMeshes; index++) {
  32212. this.releaseForMesh(meshes[index]);
  32213. }
  32214. this._meshes = [];
  32215. this._disposeVertexArrayObjects();
  32216. for (var kind in this._vertexBuffers) {
  32217. this._vertexBuffers[kind].dispose();
  32218. }
  32219. this._vertexBuffers = {};
  32220. this._totalVertices = 0;
  32221. if (this._indexBuffer) {
  32222. this._engine._releaseBuffer(this._indexBuffer);
  32223. }
  32224. this._indexBuffer = null;
  32225. this._indices = [];
  32226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32227. this.delayLoadingFile = null;
  32228. this._delayLoadingFunction = null;
  32229. this._delayInfo = [];
  32230. this._boundingInfo = null;
  32231. this._scene.removeGeometry(this);
  32232. this._isDisposed = true;
  32233. };
  32234. Geometry.prototype.copy = function (id) {
  32235. var vertexData = new BABYLON.VertexData();
  32236. vertexData.indices = [];
  32237. var indices = this.getIndices();
  32238. if (indices) {
  32239. for (var index = 0; index < indices.length; index++) {
  32240. vertexData.indices.push(indices[index]);
  32241. }
  32242. }
  32243. var updatable = false;
  32244. var stopChecking = false;
  32245. var kind;
  32246. for (kind in this._vertexBuffers) {
  32247. // using slice() to make a copy of the array and not just reference it
  32248. var data = this.getVerticesData(kind);
  32249. if (data instanceof Float32Array) {
  32250. vertexData.set(new Float32Array(data), kind);
  32251. }
  32252. else {
  32253. vertexData.set(data.slice(0), kind);
  32254. }
  32255. if (!stopChecking) {
  32256. var vb = this.getVertexBuffer(kind);
  32257. if (vb) {
  32258. updatable = vb.isUpdatable();
  32259. stopChecking = !updatable;
  32260. }
  32261. }
  32262. }
  32263. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32264. geometry.delayLoadState = this.delayLoadState;
  32265. geometry.delayLoadingFile = this.delayLoadingFile;
  32266. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32267. for (kind in this._delayInfo) {
  32268. geometry._delayInfo = geometry._delayInfo || [];
  32269. geometry._delayInfo.push(kind);
  32270. }
  32271. // Bounding info
  32272. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32273. return geometry;
  32274. };
  32275. Geometry.prototype.serialize = function () {
  32276. var serializationObject = {};
  32277. serializationObject.id = this.id;
  32278. serializationObject.updatable = this._updatable;
  32279. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32280. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32281. }
  32282. return serializationObject;
  32283. };
  32284. Geometry.prototype.toNumberArray = function (origin) {
  32285. if (Array.isArray(origin)) {
  32286. return origin;
  32287. }
  32288. else {
  32289. return Array.prototype.slice.call(origin);
  32290. }
  32291. };
  32292. Geometry.prototype.serializeVerticeData = function () {
  32293. var serializationObject = this.serialize();
  32294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32295. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32296. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32297. serializationObject.positions._updatable = true;
  32298. }
  32299. }
  32300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32301. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32302. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32303. serializationObject.normals._updatable = true;
  32304. }
  32305. }
  32306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32307. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32308. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32309. serializationObject.uvs._updatable = true;
  32310. }
  32311. }
  32312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32313. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32314. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32315. serializationObject.uv2s._updatable = true;
  32316. }
  32317. }
  32318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32319. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32320. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32321. serializationObject.uv3s._updatable = true;
  32322. }
  32323. }
  32324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32325. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32326. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32327. serializationObject.uv4s._updatable = true;
  32328. }
  32329. }
  32330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32331. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32332. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32333. serializationObject.uv5s._updatable = true;
  32334. }
  32335. }
  32336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32337. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32338. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32339. serializationObject.uv6s._updatable = true;
  32340. }
  32341. }
  32342. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32343. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32344. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32345. serializationObject.colors._updatable = true;
  32346. }
  32347. }
  32348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32349. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32350. serializationObject.matricesIndices._isExpanded = true;
  32351. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32352. serializationObject.matricesIndices._updatable = true;
  32353. }
  32354. }
  32355. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32356. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32357. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32358. serializationObject.matricesWeights._updatable = true;
  32359. }
  32360. }
  32361. serializationObject.indices = this.toNumberArray(this.getIndices());
  32362. return serializationObject;
  32363. };
  32364. // Statics
  32365. Geometry.ExtractFromMesh = function (mesh, id) {
  32366. var geometry = mesh._geometry;
  32367. if (!geometry) {
  32368. return null;
  32369. }
  32370. return geometry.copy(id);
  32371. };
  32372. /**
  32373. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32374. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32375. * Be aware Math.random() could cause collisions, but:
  32376. * "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"
  32377. */
  32378. Geometry.RandomId = function () {
  32379. return BABYLON.Tools.RandomId();
  32380. };
  32381. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32382. var scene = mesh.getScene();
  32383. // Geometry
  32384. var geometryId = parsedGeometry.geometryId;
  32385. if (geometryId) {
  32386. var geometry = scene.getGeometryByID(geometryId);
  32387. if (geometry) {
  32388. geometry.applyToMesh(mesh);
  32389. }
  32390. }
  32391. else if (parsedGeometry instanceof ArrayBuffer) {
  32392. var binaryInfo = mesh._binaryInfo;
  32393. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32394. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32395. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32396. }
  32397. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32398. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32399. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32400. }
  32401. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32402. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32404. }
  32405. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32406. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32407. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32408. }
  32409. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32410. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32411. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32412. }
  32413. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32414. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32415. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32416. }
  32417. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32418. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32419. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32420. }
  32421. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32422. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32423. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32424. }
  32425. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32426. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32427. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32428. }
  32429. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32430. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32431. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32432. }
  32433. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32434. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32436. }
  32437. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32438. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32439. mesh.setIndices(indicesData, null);
  32440. }
  32441. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32442. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32443. mesh.subMeshes = [];
  32444. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32445. var materialIndex = subMeshesData[(i * 5) + 0];
  32446. var verticesStart = subMeshesData[(i * 5) + 1];
  32447. var verticesCount = subMeshesData[(i * 5) + 2];
  32448. var indexStart = subMeshesData[(i * 5) + 3];
  32449. var indexCount = subMeshesData[(i * 5) + 4];
  32450. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32451. }
  32452. }
  32453. }
  32454. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32455. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32456. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32457. if (parsedGeometry.uvs) {
  32458. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32459. }
  32460. if (parsedGeometry.uvs2) {
  32461. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32462. }
  32463. if (parsedGeometry.uvs3) {
  32464. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32465. }
  32466. if (parsedGeometry.uvs4) {
  32467. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32468. }
  32469. if (parsedGeometry.uvs5) {
  32470. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32471. }
  32472. if (parsedGeometry.uvs6) {
  32473. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32474. }
  32475. if (parsedGeometry.colors) {
  32476. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32477. }
  32478. if (parsedGeometry.matricesIndices) {
  32479. if (!parsedGeometry.matricesIndices._isExpanded) {
  32480. var floatIndices = [];
  32481. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32482. var matricesIndex = parsedGeometry.matricesIndices[i];
  32483. floatIndices.push(matricesIndex & 0x000000FF);
  32484. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32485. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32486. floatIndices.push(matricesIndex >> 24);
  32487. }
  32488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32489. }
  32490. else {
  32491. delete parsedGeometry.matricesIndices._isExpanded;
  32492. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32493. }
  32494. }
  32495. if (parsedGeometry.matricesIndicesExtra) {
  32496. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32497. var floatIndices = [];
  32498. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32499. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32500. floatIndices.push(matricesIndex & 0x000000FF);
  32501. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32502. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32503. floatIndices.push(matricesIndex >> 24);
  32504. }
  32505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32506. }
  32507. else {
  32508. delete parsedGeometry.matricesIndices._isExpanded;
  32509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32510. }
  32511. }
  32512. if (parsedGeometry.matricesWeights) {
  32513. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32515. }
  32516. if (parsedGeometry.matricesWeightsExtra) {
  32517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32518. }
  32519. mesh.setIndices(parsedGeometry.indices, null);
  32520. }
  32521. // SubMeshes
  32522. if (parsedGeometry.subMeshes) {
  32523. mesh.subMeshes = [];
  32524. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32525. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32526. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32527. }
  32528. }
  32529. // Flat shading
  32530. if (mesh._shouldGenerateFlatShading) {
  32531. mesh.convertToFlatShadedMesh();
  32532. delete mesh._shouldGenerateFlatShading;
  32533. }
  32534. // Update
  32535. mesh.computeWorldMatrix(true);
  32536. // Octree
  32537. var sceneOctree = scene.selectionOctree;
  32538. if (sceneOctree !== undefined && sceneOctree !== null) {
  32539. sceneOctree.addMesh(mesh);
  32540. }
  32541. };
  32542. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32543. var epsilon = 1e-3;
  32544. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32545. return;
  32546. }
  32547. var noInfluenceBoneIndex = 0.0;
  32548. if (parsedGeometry.skeletonId > -1) {
  32549. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32550. if (!skeleton) {
  32551. return;
  32552. }
  32553. noInfluenceBoneIndex = skeleton.bones.length;
  32554. }
  32555. else {
  32556. return;
  32557. }
  32558. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32559. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32560. var matricesWeights = parsedGeometry.matricesWeights;
  32561. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32562. var influencers = parsedGeometry.numBoneInfluencer;
  32563. var size = matricesWeights.length;
  32564. for (var i = 0; i < size; i += 4) {
  32565. var weight = 0.0;
  32566. var firstZeroWeight = -1;
  32567. for (var j = 0; j < 4; j++) {
  32568. var w = matricesWeights[i + j];
  32569. weight += w;
  32570. if (w < epsilon && firstZeroWeight < 0) {
  32571. firstZeroWeight = j;
  32572. }
  32573. }
  32574. if (matricesWeightsExtra) {
  32575. for (var j = 0; j < 4; j++) {
  32576. var w = matricesWeightsExtra[i + j];
  32577. weight += w;
  32578. if (w < epsilon && firstZeroWeight < 0) {
  32579. firstZeroWeight = j + 4;
  32580. }
  32581. }
  32582. }
  32583. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32584. firstZeroWeight = influencers - 1;
  32585. }
  32586. if (weight > epsilon) {
  32587. var mweight = 1.0 / weight;
  32588. for (var j = 0; j < 4; j++) {
  32589. matricesWeights[i + j] *= mweight;
  32590. }
  32591. if (matricesWeightsExtra) {
  32592. for (var j = 0; j < 4; j++) {
  32593. matricesWeightsExtra[i + j] *= mweight;
  32594. }
  32595. }
  32596. }
  32597. else {
  32598. if (firstZeroWeight >= 4) {
  32599. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32600. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32601. }
  32602. else {
  32603. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32604. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32605. }
  32606. }
  32607. }
  32608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32609. if (parsedGeometry.matricesWeightsExtra) {
  32610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32611. }
  32612. };
  32613. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32614. if (scene.getGeometryByID(parsedVertexData.id)) {
  32615. return null; // null since geometry could be something else than a box...
  32616. }
  32617. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32618. if (BABYLON.Tags) {
  32619. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32620. }
  32621. if (parsedVertexData.delayLoadingFile) {
  32622. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32623. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32624. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32625. geometry._delayInfo = [];
  32626. if (parsedVertexData.hasUVs) {
  32627. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32628. }
  32629. if (parsedVertexData.hasUVs2) {
  32630. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32631. }
  32632. if (parsedVertexData.hasUVs3) {
  32633. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32634. }
  32635. if (parsedVertexData.hasUVs4) {
  32636. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32637. }
  32638. if (parsedVertexData.hasUVs5) {
  32639. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32640. }
  32641. if (parsedVertexData.hasUVs6) {
  32642. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32643. }
  32644. if (parsedVertexData.hasColors) {
  32645. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32646. }
  32647. if (parsedVertexData.hasMatricesIndices) {
  32648. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32649. }
  32650. if (parsedVertexData.hasMatricesWeights) {
  32651. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32652. }
  32653. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32654. }
  32655. else {
  32656. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32657. }
  32658. scene.pushGeometry(geometry, true);
  32659. return geometry;
  32660. };
  32661. return Geometry;
  32662. }());
  32663. BABYLON.Geometry = Geometry;
  32664. /////// Primitives //////////////////////////////////////////////
  32665. //export module Geometry.Primitives {
  32666. /// Abstract class
  32667. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32668. __extends(_PrimitiveGeometry, _super);
  32669. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32670. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32671. if (mesh === void 0) { mesh = null; }
  32672. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32673. _this._canBeRegenerated = _canBeRegenerated;
  32674. _this._beingRegenerated = true;
  32675. _this.regenerate();
  32676. _this._beingRegenerated = false;
  32677. return _this;
  32678. }
  32679. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32680. return this._canBeRegenerated;
  32681. };
  32682. _PrimitiveGeometry.prototype.regenerate = function () {
  32683. if (!this._canBeRegenerated) {
  32684. return;
  32685. }
  32686. this._beingRegenerated = true;
  32687. this.setAllVerticesData(this._regenerateVertexData(), false);
  32688. this._beingRegenerated = false;
  32689. };
  32690. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32691. return _super.prototype.copy.call(this, id);
  32692. };
  32693. // overrides
  32694. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32695. if (!this._beingRegenerated) {
  32696. return;
  32697. }
  32698. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32699. };
  32700. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32701. if (!this._beingRegenerated) {
  32702. return;
  32703. }
  32704. _super.prototype.setVerticesData.call(this, kind, data, false);
  32705. };
  32706. // to override
  32707. // protected
  32708. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32709. throw new Error("Abstract method");
  32710. };
  32711. _PrimitiveGeometry.prototype.copy = function (id) {
  32712. throw new Error("Must be overriden in sub-classes.");
  32713. };
  32714. _PrimitiveGeometry.prototype.serialize = function () {
  32715. var serializationObject = _super.prototype.serialize.call(this);
  32716. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32717. return serializationObject;
  32718. };
  32719. return _PrimitiveGeometry;
  32720. }(Geometry));
  32721. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32722. var RibbonGeometry = /** @class */ (function (_super) {
  32723. __extends(RibbonGeometry, _super);
  32724. // Members
  32725. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32727. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32728. _this.pathArray = pathArray;
  32729. _this.closeArray = closeArray;
  32730. _this.closePath = closePath;
  32731. _this.offset = offset;
  32732. _this.side = side;
  32733. return _this;
  32734. }
  32735. RibbonGeometry.prototype._regenerateVertexData = function () {
  32736. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32737. };
  32738. RibbonGeometry.prototype.copy = function (id) {
  32739. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32740. };
  32741. return RibbonGeometry;
  32742. }(_PrimitiveGeometry));
  32743. BABYLON.RibbonGeometry = RibbonGeometry;
  32744. var BoxGeometry = /** @class */ (function (_super) {
  32745. __extends(BoxGeometry, _super);
  32746. // Members
  32747. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32748. if (mesh === void 0) { mesh = null; }
  32749. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32750. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32751. _this.size = size;
  32752. _this.side = side;
  32753. return _this;
  32754. }
  32755. BoxGeometry.prototype._regenerateVertexData = function () {
  32756. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32757. };
  32758. BoxGeometry.prototype.copy = function (id) {
  32759. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32760. };
  32761. BoxGeometry.prototype.serialize = function () {
  32762. var serializationObject = _super.prototype.serialize.call(this);
  32763. serializationObject.size = this.size;
  32764. return serializationObject;
  32765. };
  32766. BoxGeometry.Parse = function (parsedBox, scene) {
  32767. if (scene.getGeometryByID(parsedBox.id)) {
  32768. return null; // null since geometry could be something else than a box...
  32769. }
  32770. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32771. if (BABYLON.Tags) {
  32772. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32773. }
  32774. scene.pushGeometry(box, true);
  32775. return box;
  32776. };
  32777. return BoxGeometry;
  32778. }(_PrimitiveGeometry));
  32779. BABYLON.BoxGeometry = BoxGeometry;
  32780. var SphereGeometry = /** @class */ (function (_super) {
  32781. __extends(SphereGeometry, _super);
  32782. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32783. if (mesh === void 0) { mesh = null; }
  32784. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32785. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32786. _this.segments = segments;
  32787. _this.diameter = diameter;
  32788. _this.side = side;
  32789. return _this;
  32790. }
  32791. SphereGeometry.prototype._regenerateVertexData = function () {
  32792. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32793. };
  32794. SphereGeometry.prototype.copy = function (id) {
  32795. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32796. };
  32797. SphereGeometry.prototype.serialize = function () {
  32798. var serializationObject = _super.prototype.serialize.call(this);
  32799. serializationObject.segments = this.segments;
  32800. serializationObject.diameter = this.diameter;
  32801. return serializationObject;
  32802. };
  32803. SphereGeometry.Parse = function (parsedSphere, scene) {
  32804. if (scene.getGeometryByID(parsedSphere.id)) {
  32805. return null; // null since geometry could be something else than a sphere...
  32806. }
  32807. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32808. if (BABYLON.Tags) {
  32809. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32810. }
  32811. scene.pushGeometry(sphere, true);
  32812. return sphere;
  32813. };
  32814. return SphereGeometry;
  32815. }(_PrimitiveGeometry));
  32816. BABYLON.SphereGeometry = SphereGeometry;
  32817. var DiscGeometry = /** @class */ (function (_super) {
  32818. __extends(DiscGeometry, _super);
  32819. // Members
  32820. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32821. if (mesh === void 0) { mesh = null; }
  32822. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32823. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32824. _this.radius = radius;
  32825. _this.tessellation = tessellation;
  32826. _this.side = side;
  32827. return _this;
  32828. }
  32829. DiscGeometry.prototype._regenerateVertexData = function () {
  32830. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32831. };
  32832. DiscGeometry.prototype.copy = function (id) {
  32833. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32834. };
  32835. return DiscGeometry;
  32836. }(_PrimitiveGeometry));
  32837. BABYLON.DiscGeometry = DiscGeometry;
  32838. var CylinderGeometry = /** @class */ (function (_super) {
  32839. __extends(CylinderGeometry, _super);
  32840. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32841. if (subdivisions === void 0) { subdivisions = 1; }
  32842. if (mesh === void 0) { mesh = null; }
  32843. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32844. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32845. _this.height = height;
  32846. _this.diameterTop = diameterTop;
  32847. _this.diameterBottom = diameterBottom;
  32848. _this.tessellation = tessellation;
  32849. _this.subdivisions = subdivisions;
  32850. _this.side = side;
  32851. return _this;
  32852. }
  32853. CylinderGeometry.prototype._regenerateVertexData = function () {
  32854. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32855. };
  32856. CylinderGeometry.prototype.copy = function (id) {
  32857. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32858. };
  32859. CylinderGeometry.prototype.serialize = function () {
  32860. var serializationObject = _super.prototype.serialize.call(this);
  32861. serializationObject.height = this.height;
  32862. serializationObject.diameterTop = this.diameterTop;
  32863. serializationObject.diameterBottom = this.diameterBottom;
  32864. serializationObject.tessellation = this.tessellation;
  32865. return serializationObject;
  32866. };
  32867. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32868. if (scene.getGeometryByID(parsedCylinder.id)) {
  32869. return null; // null since geometry could be something else than a cylinder...
  32870. }
  32871. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32872. if (BABYLON.Tags) {
  32873. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32874. }
  32875. scene.pushGeometry(cylinder, true);
  32876. return cylinder;
  32877. };
  32878. return CylinderGeometry;
  32879. }(_PrimitiveGeometry));
  32880. BABYLON.CylinderGeometry = CylinderGeometry;
  32881. var TorusGeometry = /** @class */ (function (_super) {
  32882. __extends(TorusGeometry, _super);
  32883. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32884. if (mesh === void 0) { mesh = null; }
  32885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32887. _this.diameter = diameter;
  32888. _this.thickness = thickness;
  32889. _this.tessellation = tessellation;
  32890. _this.side = side;
  32891. return _this;
  32892. }
  32893. TorusGeometry.prototype._regenerateVertexData = function () {
  32894. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32895. };
  32896. TorusGeometry.prototype.copy = function (id) {
  32897. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32898. };
  32899. TorusGeometry.prototype.serialize = function () {
  32900. var serializationObject = _super.prototype.serialize.call(this);
  32901. serializationObject.diameter = this.diameter;
  32902. serializationObject.thickness = this.thickness;
  32903. serializationObject.tessellation = this.tessellation;
  32904. return serializationObject;
  32905. };
  32906. TorusGeometry.Parse = function (parsedTorus, scene) {
  32907. if (scene.getGeometryByID(parsedTorus.id)) {
  32908. return null; // null since geometry could be something else than a torus...
  32909. }
  32910. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32911. if (BABYLON.Tags) {
  32912. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32913. }
  32914. scene.pushGeometry(torus, true);
  32915. return torus;
  32916. };
  32917. return TorusGeometry;
  32918. }(_PrimitiveGeometry));
  32919. BABYLON.TorusGeometry = TorusGeometry;
  32920. var GroundGeometry = /** @class */ (function (_super) {
  32921. __extends(GroundGeometry, _super);
  32922. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32923. if (mesh === void 0) { mesh = null; }
  32924. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32925. _this.width = width;
  32926. _this.height = height;
  32927. _this.subdivisions = subdivisions;
  32928. return _this;
  32929. }
  32930. GroundGeometry.prototype._regenerateVertexData = function () {
  32931. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32932. };
  32933. GroundGeometry.prototype.copy = function (id) {
  32934. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32935. };
  32936. GroundGeometry.prototype.serialize = function () {
  32937. var serializationObject = _super.prototype.serialize.call(this);
  32938. serializationObject.width = this.width;
  32939. serializationObject.height = this.height;
  32940. serializationObject.subdivisions = this.subdivisions;
  32941. return serializationObject;
  32942. };
  32943. GroundGeometry.Parse = function (parsedGround, scene) {
  32944. if (scene.getGeometryByID(parsedGround.id)) {
  32945. return null; // null since geometry could be something else than a ground...
  32946. }
  32947. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32948. if (BABYLON.Tags) {
  32949. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32950. }
  32951. scene.pushGeometry(ground, true);
  32952. return ground;
  32953. };
  32954. return GroundGeometry;
  32955. }(_PrimitiveGeometry));
  32956. BABYLON.GroundGeometry = GroundGeometry;
  32957. var TiledGroundGeometry = /** @class */ (function (_super) {
  32958. __extends(TiledGroundGeometry, _super);
  32959. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32960. if (mesh === void 0) { mesh = null; }
  32961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32962. _this.xmin = xmin;
  32963. _this.zmin = zmin;
  32964. _this.xmax = xmax;
  32965. _this.zmax = zmax;
  32966. _this.subdivisions = subdivisions;
  32967. _this.precision = precision;
  32968. return _this;
  32969. }
  32970. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32971. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32972. };
  32973. TiledGroundGeometry.prototype.copy = function (id) {
  32974. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32975. };
  32976. return TiledGroundGeometry;
  32977. }(_PrimitiveGeometry));
  32978. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32979. var PlaneGeometry = /** @class */ (function (_super) {
  32980. __extends(PlaneGeometry, _super);
  32981. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32982. if (mesh === void 0) { mesh = null; }
  32983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32984. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32985. _this.size = size;
  32986. _this.side = side;
  32987. return _this;
  32988. }
  32989. PlaneGeometry.prototype._regenerateVertexData = function () {
  32990. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32991. };
  32992. PlaneGeometry.prototype.copy = function (id) {
  32993. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32994. };
  32995. PlaneGeometry.prototype.serialize = function () {
  32996. var serializationObject = _super.prototype.serialize.call(this);
  32997. serializationObject.size = this.size;
  32998. return serializationObject;
  32999. };
  33000. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33001. if (scene.getGeometryByID(parsedPlane.id)) {
  33002. return null; // null since geometry could be something else than a ground...
  33003. }
  33004. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33005. if (BABYLON.Tags) {
  33006. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33007. }
  33008. scene.pushGeometry(plane, true);
  33009. return plane;
  33010. };
  33011. return PlaneGeometry;
  33012. }(_PrimitiveGeometry));
  33013. BABYLON.PlaneGeometry = PlaneGeometry;
  33014. var TorusKnotGeometry = /** @class */ (function (_super) {
  33015. __extends(TorusKnotGeometry, _super);
  33016. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33017. if (mesh === void 0) { mesh = null; }
  33018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33020. _this.radius = radius;
  33021. _this.tube = tube;
  33022. _this.radialSegments = radialSegments;
  33023. _this.tubularSegments = tubularSegments;
  33024. _this.p = p;
  33025. _this.q = q;
  33026. _this.side = side;
  33027. return _this;
  33028. }
  33029. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  33030. 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 });
  33031. };
  33032. TorusKnotGeometry.prototype.copy = function (id) {
  33033. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33034. };
  33035. TorusKnotGeometry.prototype.serialize = function () {
  33036. var serializationObject = _super.prototype.serialize.call(this);
  33037. serializationObject.radius = this.radius;
  33038. serializationObject.tube = this.tube;
  33039. serializationObject.radialSegments = this.radialSegments;
  33040. serializationObject.tubularSegments = this.tubularSegments;
  33041. serializationObject.p = this.p;
  33042. serializationObject.q = this.q;
  33043. return serializationObject;
  33044. };
  33045. ;
  33046. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  33047. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33048. return null; // null since geometry could be something else than a ground...
  33049. }
  33050. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33051. if (BABYLON.Tags) {
  33052. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33053. }
  33054. scene.pushGeometry(torusKnot, true);
  33055. return torusKnot;
  33056. };
  33057. return TorusKnotGeometry;
  33058. }(_PrimitiveGeometry));
  33059. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  33060. //}
  33061. })(BABYLON || (BABYLON = {}));
  33062. //# sourceMappingURL=babylon.geometry.js.map
  33063. var BABYLON;
  33064. (function (BABYLON) {
  33065. var PostProcessManager = /** @class */ (function () {
  33066. function PostProcessManager(scene) {
  33067. this._vertexBuffers = {};
  33068. this._scene = scene;
  33069. }
  33070. PostProcessManager.prototype._prepareBuffers = function () {
  33071. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  33072. return;
  33073. }
  33074. // VBO
  33075. var vertices = [];
  33076. vertices.push(1, 1);
  33077. vertices.push(-1, 1);
  33078. vertices.push(-1, -1);
  33079. vertices.push(1, -1);
  33080. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33081. this._buildIndexBuffer();
  33082. };
  33083. PostProcessManager.prototype._buildIndexBuffer = function () {
  33084. // Indices
  33085. var indices = [];
  33086. indices.push(0);
  33087. indices.push(1);
  33088. indices.push(2);
  33089. indices.push(0);
  33090. indices.push(2);
  33091. indices.push(3);
  33092. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  33093. };
  33094. PostProcessManager.prototype._rebuild = function () {
  33095. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33096. if (!vb) {
  33097. return;
  33098. }
  33099. vb._rebuild();
  33100. this._buildIndexBuffer();
  33101. };
  33102. // Methods
  33103. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  33104. if (sourceTexture === void 0) { sourceTexture = null; }
  33105. if (postProcesses === void 0) { postProcesses = null; }
  33106. var camera = this._scene.activeCamera;
  33107. if (!camera) {
  33108. return false;
  33109. }
  33110. var postProcesses = postProcesses || camera._postProcesses;
  33111. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33112. return false;
  33113. }
  33114. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33115. return true;
  33116. };
  33117. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33118. if (targetTexture === void 0) { targetTexture = null; }
  33119. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33120. var engine = this._scene.getEngine();
  33121. for (var index = 0; index < postProcesses.length; index++) {
  33122. if (index < postProcesses.length - 1) {
  33123. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33124. }
  33125. else {
  33126. if (targetTexture) {
  33127. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33128. }
  33129. else {
  33130. engine.restoreDefaultFramebuffer();
  33131. }
  33132. }
  33133. var pp = postProcesses[index];
  33134. var effect = pp.apply();
  33135. if (effect) {
  33136. pp.onBeforeRenderObservable.notifyObservers(effect);
  33137. // VBOs
  33138. this._prepareBuffers();
  33139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33140. // Draw order
  33141. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33142. pp.onAfterRenderObservable.notifyObservers(effect);
  33143. }
  33144. }
  33145. // Restore depth buffer
  33146. engine.setDepthBuffer(true);
  33147. engine.setDepthWrite(true);
  33148. };
  33149. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33150. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33151. var camera = this._scene.activeCamera;
  33152. if (!camera) {
  33153. return;
  33154. }
  33155. postProcesses = postProcesses || camera._postProcesses;
  33156. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33157. return;
  33158. }
  33159. var engine = this._scene.getEngine();
  33160. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33161. if (index < len - 1) {
  33162. postProcesses[index + 1].activate(camera, targetTexture);
  33163. }
  33164. else {
  33165. if (targetTexture) {
  33166. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33167. }
  33168. else {
  33169. engine.restoreDefaultFramebuffer();
  33170. }
  33171. }
  33172. if (doNotPresent) {
  33173. break;
  33174. }
  33175. var pp = postProcesses[index];
  33176. var effect = pp.apply();
  33177. if (effect) {
  33178. pp.onBeforeRenderObservable.notifyObservers(effect);
  33179. // VBOs
  33180. this._prepareBuffers();
  33181. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33182. // Draw order
  33183. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33184. pp.onAfterRenderObservable.notifyObservers(effect);
  33185. }
  33186. }
  33187. // Restore states
  33188. engine.setDepthBuffer(true);
  33189. engine.setDepthWrite(true);
  33190. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33191. };
  33192. PostProcessManager.prototype.dispose = function () {
  33193. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33194. if (buffer) {
  33195. buffer.dispose();
  33196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33197. }
  33198. if (this._indexBuffer) {
  33199. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33200. this._indexBuffer = null;
  33201. }
  33202. };
  33203. return PostProcessManager;
  33204. }());
  33205. BABYLON.PostProcessManager = PostProcessManager;
  33206. })(BABYLON || (BABYLON = {}));
  33207. //# sourceMappingURL=babylon.postProcessManager.js.map
  33208. var BABYLON;
  33209. (function (BABYLON) {
  33210. /**
  33211. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33212. */
  33213. var PerformanceMonitor = /** @class */ (function () {
  33214. /**
  33215. * constructor
  33216. * @param frameSampleSize The number of samples required to saturate the sliding window
  33217. */
  33218. function PerformanceMonitor(frameSampleSize) {
  33219. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33220. this._enabled = true;
  33221. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33222. }
  33223. /**
  33224. * Samples current frame
  33225. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33226. */
  33227. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33228. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33229. if (!this._enabled)
  33230. return;
  33231. if (this._lastFrameTimeMs != null) {
  33232. var dt = timeMs - this._lastFrameTimeMs;
  33233. this._rollingFrameTime.add(dt);
  33234. }
  33235. this._lastFrameTimeMs = timeMs;
  33236. };
  33237. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33238. /**
  33239. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33240. * @return Average frame time in milliseconds
  33241. */
  33242. get: function () {
  33243. return this._rollingFrameTime.average;
  33244. },
  33245. enumerable: true,
  33246. configurable: true
  33247. });
  33248. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33249. /**
  33250. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33251. * @return Frame time variance in milliseconds squared
  33252. */
  33253. get: function () {
  33254. return this._rollingFrameTime.variance;
  33255. },
  33256. enumerable: true,
  33257. configurable: true
  33258. });
  33259. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33260. /**
  33261. * Returns the frame time of the most recent frame
  33262. * @return Frame time in milliseconds
  33263. */
  33264. get: function () {
  33265. return this._rollingFrameTime.history(0);
  33266. },
  33267. enumerable: true,
  33268. configurable: true
  33269. });
  33270. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33271. /**
  33272. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33273. * @return Framerate in frames per second
  33274. */
  33275. get: function () {
  33276. return 1000.0 / this._rollingFrameTime.average;
  33277. },
  33278. enumerable: true,
  33279. configurable: true
  33280. });
  33281. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33282. /**
  33283. * Returns the average framerate in frames per second using the most recent frame time
  33284. * @return Framerate in frames per second
  33285. */
  33286. get: function () {
  33287. var history = this._rollingFrameTime.history(0);
  33288. if (history === 0) {
  33289. return 0;
  33290. }
  33291. return 1000.0 / history;
  33292. },
  33293. enumerable: true,
  33294. configurable: true
  33295. });
  33296. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33297. /**
  33298. * Returns true if enough samples have been taken to completely fill the sliding window
  33299. * @return true if saturated
  33300. */
  33301. get: function () {
  33302. return this._rollingFrameTime.isSaturated();
  33303. },
  33304. enumerable: true,
  33305. configurable: true
  33306. });
  33307. /**
  33308. * Enables contributions to the sliding window sample set
  33309. */
  33310. PerformanceMonitor.prototype.enable = function () {
  33311. this._enabled = true;
  33312. };
  33313. /**
  33314. * Disables contributions to the sliding window sample set
  33315. * Samples will not be interpolated over the disabled period
  33316. */
  33317. PerformanceMonitor.prototype.disable = function () {
  33318. this._enabled = false;
  33319. //clear last sample to avoid interpolating over the disabled period when next enabled
  33320. this._lastFrameTimeMs = null;
  33321. };
  33322. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33323. /**
  33324. * Returns true if sampling is enabled
  33325. * @return true if enabled
  33326. */
  33327. get: function () {
  33328. return this._enabled;
  33329. },
  33330. enumerable: true,
  33331. configurable: true
  33332. });
  33333. /**
  33334. * Resets performance monitor
  33335. */
  33336. PerformanceMonitor.prototype.reset = function () {
  33337. //clear last sample to avoid interpolating over the disabled period when next enabled
  33338. this._lastFrameTimeMs = null;
  33339. //wipe record
  33340. this._rollingFrameTime.reset();
  33341. };
  33342. return PerformanceMonitor;
  33343. }());
  33344. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33345. /**
  33346. * RollingAverage
  33347. *
  33348. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33349. */
  33350. var RollingAverage = /** @class */ (function () {
  33351. /**
  33352. * constructor
  33353. * @param length The number of samples required to saturate the sliding window
  33354. */
  33355. function RollingAverage(length) {
  33356. this._samples = new Array(length);
  33357. this.reset();
  33358. }
  33359. /**
  33360. * Adds a sample to the sample set
  33361. * @param v The sample value
  33362. */
  33363. RollingAverage.prototype.add = function (v) {
  33364. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33365. var delta;
  33366. //we need to check if we've already wrapped round
  33367. if (this.isSaturated()) {
  33368. //remove bottom of stack from mean
  33369. var bottomValue = this._samples[this._pos];
  33370. delta = bottomValue - this.average;
  33371. this.average -= delta / (this._sampleCount - 1);
  33372. this._m2 -= delta * (bottomValue - this.average);
  33373. }
  33374. else {
  33375. this._sampleCount++;
  33376. }
  33377. //add new value to mean
  33378. delta = v - this.average;
  33379. this.average += delta / (this._sampleCount);
  33380. this._m2 += delta * (v - this.average);
  33381. //set the new variance
  33382. this.variance = this._m2 / (this._sampleCount - 1);
  33383. this._samples[this._pos] = v;
  33384. this._pos++;
  33385. this._pos %= this._samples.length; //positive wrap around
  33386. };
  33387. /**
  33388. * Returns previously added values or null if outside of history or outside the sliding window domain
  33389. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33390. * @return Value previously recorded with add() or null if outside of range
  33391. */
  33392. RollingAverage.prototype.history = function (i) {
  33393. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33394. return 0;
  33395. }
  33396. var i0 = this._wrapPosition(this._pos - 1.0);
  33397. return this._samples[this._wrapPosition(i0 - i)];
  33398. };
  33399. /**
  33400. * Returns true if enough samples have been taken to completely fill the sliding window
  33401. * @return true if sample-set saturated
  33402. */
  33403. RollingAverage.prototype.isSaturated = function () {
  33404. return this._sampleCount >= this._samples.length;
  33405. };
  33406. /**
  33407. * Resets the rolling average (equivalent to 0 samples taken so far)
  33408. */
  33409. RollingAverage.prototype.reset = function () {
  33410. this.average = 0;
  33411. this.variance = 0;
  33412. this._sampleCount = 0;
  33413. this._pos = 0;
  33414. this._m2 = 0;
  33415. };
  33416. /**
  33417. * Wraps a value around the sample range boundaries
  33418. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33419. * @return Wrapped position in sample range
  33420. */
  33421. RollingAverage.prototype._wrapPosition = function (i) {
  33422. var max = this._samples.length;
  33423. return ((i % max) + max) % max;
  33424. };
  33425. return RollingAverage;
  33426. }());
  33427. BABYLON.RollingAverage = RollingAverage;
  33428. })(BABYLON || (BABYLON = {}));
  33429. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33430. var BABYLON;
  33431. (function (BABYLON) {
  33432. /**
  33433. * This groups together the common properties used for image processing either in direct forward pass
  33434. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33435. * or not.
  33436. */
  33437. var ImageProcessingConfiguration = /** @class */ (function () {
  33438. function ImageProcessingConfiguration() {
  33439. /**
  33440. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33441. */
  33442. this.colorCurves = new BABYLON.ColorCurves();
  33443. this._colorCurvesEnabled = false;
  33444. this._colorGradingEnabled = false;
  33445. this._colorGradingWithGreenDepth = true;
  33446. this._colorGradingBGR = true;
  33447. this._exposure = 1.0;
  33448. this._toneMappingEnabled = false;
  33449. this._contrast = 1.0;
  33450. /**
  33451. * Vignette stretch size.
  33452. */
  33453. this.vignetteStretch = 0;
  33454. /**
  33455. * Vignette centre X Offset.
  33456. */
  33457. this.vignetteCentreX = 0;
  33458. /**
  33459. * Vignette centre Y Offset.
  33460. */
  33461. this.vignetteCentreY = 0;
  33462. /**
  33463. * Vignette weight or intensity of the vignette effect.
  33464. */
  33465. this.vignetteWeight = 1.5;
  33466. /**
  33467. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33468. * if vignetteEnabled is set to true.
  33469. */
  33470. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33471. /**
  33472. * Camera field of view used by the Vignette effect.
  33473. */
  33474. this.vignetteCameraFov = 0.5;
  33475. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33476. this._vignetteEnabled = false;
  33477. this._applyByPostProcess = false;
  33478. this._isEnabled = true;
  33479. /**
  33480. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33481. * @type {BABYLON.Observable}
  33482. */
  33483. this.onUpdateParameters = new BABYLON.Observable();
  33484. }
  33485. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33486. /**
  33487. * Gets wether the color curves effect is enabled.
  33488. */
  33489. get: function () {
  33490. return this._colorCurvesEnabled;
  33491. },
  33492. /**
  33493. * Sets wether the color curves effect is enabled.
  33494. */
  33495. set: function (value) {
  33496. if (this._colorCurvesEnabled === value) {
  33497. return;
  33498. }
  33499. this._colorCurvesEnabled = value;
  33500. this._updateParameters();
  33501. },
  33502. enumerable: true,
  33503. configurable: true
  33504. });
  33505. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33506. /**
  33507. * Gets wether the color grading effect is enabled.
  33508. */
  33509. get: function () {
  33510. return this._colorGradingEnabled;
  33511. },
  33512. /**
  33513. * Sets wether the color grading effect is enabled.
  33514. */
  33515. set: function (value) {
  33516. if (this._colorGradingEnabled === value) {
  33517. return;
  33518. }
  33519. this._colorGradingEnabled = value;
  33520. this._updateParameters();
  33521. },
  33522. enumerable: true,
  33523. configurable: true
  33524. });
  33525. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33526. /**
  33527. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33528. */
  33529. get: function () {
  33530. return this._colorGradingWithGreenDepth;
  33531. },
  33532. /**
  33533. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33534. */
  33535. set: function (value) {
  33536. if (this._colorGradingWithGreenDepth === value) {
  33537. return;
  33538. }
  33539. this._colorGradingWithGreenDepth = value;
  33540. this._updateParameters();
  33541. },
  33542. enumerable: true,
  33543. configurable: true
  33544. });
  33545. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33546. /**
  33547. * Gets wether the color grading texture contains BGR values.
  33548. */
  33549. get: function () {
  33550. return this._colorGradingBGR;
  33551. },
  33552. /**
  33553. * Sets wether the color grading texture contains BGR values.
  33554. */
  33555. set: function (value) {
  33556. if (this._colorGradingBGR === value) {
  33557. return;
  33558. }
  33559. this._colorGradingBGR = value;
  33560. this._updateParameters();
  33561. },
  33562. enumerable: true,
  33563. configurable: true
  33564. });
  33565. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33566. /**
  33567. * Gets the Exposure used in the effect.
  33568. */
  33569. get: function () {
  33570. return this._exposure;
  33571. },
  33572. /**
  33573. * Sets the Exposure used in the effect.
  33574. */
  33575. set: function (value) {
  33576. if (this._exposure === value) {
  33577. return;
  33578. }
  33579. this._exposure = value;
  33580. this._updateParameters();
  33581. },
  33582. enumerable: true,
  33583. configurable: true
  33584. });
  33585. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33586. /**
  33587. * Gets wether the tone mapping effect is enabled.
  33588. */
  33589. get: function () {
  33590. return this._toneMappingEnabled;
  33591. },
  33592. /**
  33593. * Sets wether the tone mapping effect is enabled.
  33594. */
  33595. set: function (value) {
  33596. if (this._toneMappingEnabled === value) {
  33597. return;
  33598. }
  33599. this._toneMappingEnabled = value;
  33600. this._updateParameters();
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33606. /**
  33607. * Gets the contrast used in the effect.
  33608. */
  33609. get: function () {
  33610. return this._contrast;
  33611. },
  33612. /**
  33613. * Sets the contrast used in the effect.
  33614. */
  33615. set: function (value) {
  33616. if (this._contrast === value) {
  33617. return;
  33618. }
  33619. this._contrast = value;
  33620. this._updateParameters();
  33621. },
  33622. enumerable: true,
  33623. configurable: true
  33624. });
  33625. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33626. /**
  33627. * Gets the vignette blend mode allowing different kind of effect.
  33628. */
  33629. get: function () {
  33630. return this._vignetteBlendMode;
  33631. },
  33632. /**
  33633. * Sets the vignette blend mode allowing different kind of effect.
  33634. */
  33635. set: function (value) {
  33636. if (this._vignetteBlendMode === value) {
  33637. return;
  33638. }
  33639. this._vignetteBlendMode = value;
  33640. this._updateParameters();
  33641. },
  33642. enumerable: true,
  33643. configurable: true
  33644. });
  33645. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33646. /**
  33647. * Gets wether the vignette effect is enabled.
  33648. */
  33649. get: function () {
  33650. return this._vignetteEnabled;
  33651. },
  33652. /**
  33653. * Sets wether the vignette effect is enabled.
  33654. */
  33655. set: function (value) {
  33656. if (this._vignetteEnabled === value) {
  33657. return;
  33658. }
  33659. this._vignetteEnabled = value;
  33660. this._updateParameters();
  33661. },
  33662. enumerable: true,
  33663. configurable: true
  33664. });
  33665. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33666. /**
  33667. * Gets wether the image processing is applied through a post process or not.
  33668. */
  33669. get: function () {
  33670. return this._applyByPostProcess;
  33671. },
  33672. /**
  33673. * Sets wether the image processing is applied through a post process or not.
  33674. */
  33675. set: function (value) {
  33676. if (this._applyByPostProcess === value) {
  33677. return;
  33678. }
  33679. this._applyByPostProcess = value;
  33680. this._updateParameters();
  33681. },
  33682. enumerable: true,
  33683. configurable: true
  33684. });
  33685. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33686. /**
  33687. * Gets wether the image processing is enabled or not.
  33688. */
  33689. get: function () {
  33690. return this._isEnabled;
  33691. },
  33692. /**
  33693. * Sets wether the image processing is enabled or not.
  33694. */
  33695. set: function (value) {
  33696. if (this._isEnabled === value) {
  33697. return;
  33698. }
  33699. this._isEnabled = value;
  33700. this._updateParameters();
  33701. },
  33702. enumerable: true,
  33703. configurable: true
  33704. });
  33705. /**
  33706. * Method called each time the image processing information changes requires to recompile the effect.
  33707. */
  33708. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33709. this.onUpdateParameters.notifyObservers(this);
  33710. };
  33711. ImageProcessingConfiguration.prototype.getClassName = function () {
  33712. return "ImageProcessingConfiguration";
  33713. };
  33714. /**
  33715. * Prepare the list of uniforms associated with the Image Processing effects.
  33716. * @param uniformsList The list of uniforms used in the effect
  33717. * @param defines the list of defines currently in use
  33718. */
  33719. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33720. if (defines.EXPOSURE) {
  33721. uniforms.push("exposureLinear");
  33722. }
  33723. if (defines.CONTRAST) {
  33724. uniforms.push("contrast");
  33725. }
  33726. if (defines.COLORGRADING) {
  33727. uniforms.push("colorTransformSettings");
  33728. }
  33729. if (defines.VIGNETTE) {
  33730. uniforms.push("vInverseScreenSize");
  33731. uniforms.push("vignetteSettings1");
  33732. uniforms.push("vignetteSettings2");
  33733. }
  33734. if (defines.COLORCURVES) {
  33735. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33736. }
  33737. };
  33738. /**
  33739. * Prepare the list of samplers associated with the Image Processing effects.
  33740. * @param uniformsList The list of uniforms used in the effect
  33741. * @param defines the list of defines currently in use
  33742. */
  33743. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33744. if (defines.COLORGRADING) {
  33745. samplersList.push("txColorTransform");
  33746. }
  33747. };
  33748. /**
  33749. * Prepare the list of defines associated to the shader.
  33750. * @param defines the list of defines to complete
  33751. */
  33752. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33753. if (forPostProcess === void 0) { forPostProcess = false; }
  33754. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33755. defines.VIGNETTE = false;
  33756. defines.TONEMAPPING = false;
  33757. defines.CONTRAST = false;
  33758. defines.EXPOSURE = false;
  33759. defines.COLORCURVES = false;
  33760. defines.COLORGRADING = false;
  33761. defines.COLORGRADING3D = false;
  33762. defines.IMAGEPROCESSING = false;
  33763. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33764. return;
  33765. }
  33766. defines.VIGNETTE = this.vignetteEnabled;
  33767. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33768. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33769. defines.TONEMAPPING = this.toneMappingEnabled;
  33770. defines.CONTRAST = (this.contrast !== 1.0);
  33771. defines.EXPOSURE = (this.exposure !== 1.0);
  33772. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33773. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33774. if (defines.COLORGRADING) {
  33775. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33776. }
  33777. else {
  33778. defines.COLORGRADING3D = false;
  33779. }
  33780. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33781. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33782. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33783. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33784. };
  33785. /**
  33786. * Returns true if all the image processing information are ready.
  33787. */
  33788. ImageProcessingConfiguration.prototype.isReady = function () {
  33789. // Color Grading texure can not be none blocking.
  33790. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33791. };
  33792. /**
  33793. * Binds the image processing to the shader.
  33794. * @param effect The effect to bind to
  33795. */
  33796. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33797. if (aspectRatio === void 0) { aspectRatio = 1; }
  33798. // Color Curves
  33799. if (this._colorCurvesEnabled && this.colorCurves) {
  33800. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33801. }
  33802. // Vignette
  33803. if (this._vignetteEnabled) {
  33804. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33805. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33806. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33807. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33808. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33809. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33810. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33811. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33812. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33813. var vignettePower = -2.0 * this.vignetteWeight;
  33814. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33815. }
  33816. // Exposure
  33817. effect.setFloat("exposureLinear", this.exposure);
  33818. // Contrast
  33819. effect.setFloat("contrast", this.contrast);
  33820. // Color transform settings
  33821. if (this.colorGradingTexture) {
  33822. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33823. var textureSize = this.colorGradingTexture.getSize().height;
  33824. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33825. 0.5 / textureSize, // textureOffset
  33826. textureSize, // textureSize
  33827. this.colorGradingTexture.level // weight
  33828. );
  33829. }
  33830. };
  33831. /**
  33832. * Clones the current image processing instance.
  33833. * @return The cloned image processing
  33834. */
  33835. ImageProcessingConfiguration.prototype.clone = function () {
  33836. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33837. };
  33838. /**
  33839. * Serializes the current image processing instance to a json representation.
  33840. * @return a JSON representation
  33841. */
  33842. ImageProcessingConfiguration.prototype.serialize = function () {
  33843. return BABYLON.SerializationHelper.Serialize(this);
  33844. };
  33845. /**
  33846. * Parses the image processing from a json representation.
  33847. * @param source the JSON source to parse
  33848. * @return The parsed image processing
  33849. */
  33850. ImageProcessingConfiguration.Parse = function (source) {
  33851. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33852. };
  33853. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33854. /**
  33855. * Used to apply the vignette as a mix with the pixel color.
  33856. */
  33857. get: function () {
  33858. return this._VIGNETTEMODE_MULTIPLY;
  33859. },
  33860. enumerable: true,
  33861. configurable: true
  33862. });
  33863. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33864. /**
  33865. * Used to apply the vignette as a replacement of the pixel color.
  33866. */
  33867. get: function () {
  33868. return this._VIGNETTEMODE_OPAQUE;
  33869. },
  33870. enumerable: true,
  33871. configurable: true
  33872. });
  33873. // Static constants associated to the image processing.
  33874. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33875. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33876. __decorate([
  33877. BABYLON.serializeAsColorCurves()
  33878. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33879. __decorate([
  33880. BABYLON.serialize()
  33881. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33882. __decorate([
  33883. BABYLON.serializeAsTexture()
  33884. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33885. __decorate([
  33886. BABYLON.serialize()
  33887. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33888. __decorate([
  33889. BABYLON.serialize()
  33890. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33891. __decorate([
  33892. BABYLON.serialize()
  33893. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33894. __decorate([
  33895. BABYLON.serialize()
  33896. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33897. __decorate([
  33898. BABYLON.serialize()
  33899. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33900. __decorate([
  33901. BABYLON.serialize()
  33902. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33903. __decorate([
  33904. BABYLON.serialize()
  33905. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33906. __decorate([
  33907. BABYLON.serialize()
  33908. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33909. __decorate([
  33910. BABYLON.serialize()
  33911. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33912. __decorate([
  33913. BABYLON.serialize()
  33914. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33915. __decorate([
  33916. BABYLON.serializeAsColor4()
  33917. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33918. __decorate([
  33919. BABYLON.serialize()
  33920. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33921. __decorate([
  33922. BABYLON.serialize()
  33923. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33924. __decorate([
  33925. BABYLON.serialize()
  33926. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33927. __decorate([
  33928. BABYLON.serialize()
  33929. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33930. __decorate([
  33931. BABYLON.serialize()
  33932. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33933. return ImageProcessingConfiguration;
  33934. }());
  33935. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33936. })(BABYLON || (BABYLON = {}));
  33937. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33938. var BABYLON;
  33939. (function (BABYLON) {
  33940. /**
  33941. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33942. * It can help converting any input color in a desired output one. This can then be used to create effects
  33943. * from sepia, black and white to sixties or futuristic rendering...
  33944. *
  33945. * The only supported format is currently 3dl.
  33946. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33947. */
  33948. var ColorGradingTexture = /** @class */ (function (_super) {
  33949. __extends(ColorGradingTexture, _super);
  33950. /**
  33951. * Instantiates a ColorGradingTexture from the following parameters.
  33952. *
  33953. * @param url The location of the color gradind data (currently only supporting 3dl)
  33954. * @param scene The scene the texture will be used in
  33955. */
  33956. function ColorGradingTexture(url, scene) {
  33957. var _this = _super.call(this, scene) || this;
  33958. if (!url) {
  33959. return _this;
  33960. }
  33961. _this._engine = scene.getEngine();
  33962. _this._textureMatrix = BABYLON.Matrix.Identity();
  33963. _this.name = url;
  33964. _this.url = url;
  33965. _this.hasAlpha = false;
  33966. _this.isCube = false;
  33967. _this.is3D = _this._engine.webGLVersion > 1;
  33968. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33969. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33970. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33971. _this.anisotropicFilteringLevel = 1;
  33972. _this._texture = _this._getFromCache(url, true);
  33973. if (!_this._texture) {
  33974. if (!scene.useDelayedTextureLoading) {
  33975. _this.loadTexture();
  33976. }
  33977. else {
  33978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33979. }
  33980. }
  33981. return _this;
  33982. }
  33983. /**
  33984. * Returns the texture matrix used in most of the material.
  33985. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33986. */
  33987. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33988. return this._textureMatrix;
  33989. };
  33990. /**
  33991. * Occurs when the file being loaded is a .3dl LUT file.
  33992. */
  33993. ColorGradingTexture.prototype.load3dlTexture = function () {
  33994. var engine = this._engine;
  33995. var texture;
  33996. if (engine.webGLVersion === 1) {
  33997. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33998. }
  33999. else {
  34000. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34001. }
  34002. this._texture = texture;
  34003. var callback = function (text) {
  34004. if (typeof text !== "string") {
  34005. return;
  34006. }
  34007. var data = null;
  34008. var tempData = null;
  34009. var line;
  34010. var lines = text.split('\n');
  34011. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  34012. var maxColor = 0;
  34013. for (var i = 0; i < lines.length; i++) {
  34014. line = lines[i];
  34015. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  34016. continue;
  34017. if (line.indexOf('#') === 0)
  34018. continue;
  34019. var words = line.split(" ");
  34020. if (size === 0) {
  34021. // Number of space + one
  34022. size = words.length;
  34023. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  34024. tempData = new Float32Array(size * size * size * 4);
  34025. continue;
  34026. }
  34027. if (size != 0) {
  34028. var r = Math.max(parseInt(words[0]), 0);
  34029. var g = Math.max(parseInt(words[1]), 0);
  34030. var b = Math.max(parseInt(words[2]), 0);
  34031. maxColor = Math.max(r, maxColor);
  34032. maxColor = Math.max(g, maxColor);
  34033. maxColor = Math.max(b, maxColor);
  34034. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  34035. if (tempData) {
  34036. tempData[pixelStorageIndex + 0] = r;
  34037. tempData[pixelStorageIndex + 1] = g;
  34038. tempData[pixelStorageIndex + 2] = b;
  34039. }
  34040. pixelIndexSlice++;
  34041. if (pixelIndexSlice % size == 0) {
  34042. pixelIndexH++;
  34043. pixelIndexSlice = 0;
  34044. if (pixelIndexH % size == 0) {
  34045. pixelIndexW++;
  34046. pixelIndexH = 0;
  34047. }
  34048. }
  34049. }
  34050. }
  34051. if (tempData && data) {
  34052. for (var i = 0; i < tempData.length; i++) {
  34053. if (i > 0 && (i + 1) % 4 === 0) {
  34054. data[i] = 255;
  34055. }
  34056. else {
  34057. var value = tempData[i];
  34058. data[i] = (value / maxColor * 255);
  34059. }
  34060. }
  34061. }
  34062. if (texture.is3D) {
  34063. texture.updateSize(size, size, size);
  34064. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34065. }
  34066. else {
  34067. texture.updateSize(size * size, size);
  34068. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34069. }
  34070. };
  34071. var scene = this.getScene();
  34072. if (scene) {
  34073. scene._loadFile(this.url, callback);
  34074. }
  34075. else {
  34076. this._engine._loadFile(this.url, callback);
  34077. }
  34078. return this._texture;
  34079. };
  34080. /**
  34081. * Starts the loading process of the texture.
  34082. */
  34083. ColorGradingTexture.prototype.loadTexture = function () {
  34084. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  34085. this.load3dlTexture();
  34086. }
  34087. };
  34088. /**
  34089. * Clones the color gradind texture.
  34090. */
  34091. ColorGradingTexture.prototype.clone = function () {
  34092. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  34093. // Base texture
  34094. newTexture.level = this.level;
  34095. return newTexture;
  34096. };
  34097. /**
  34098. * Called during delayed load for textures.
  34099. */
  34100. ColorGradingTexture.prototype.delayLoad = function () {
  34101. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34102. return;
  34103. }
  34104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34105. this._texture = this._getFromCache(this.url, true);
  34106. if (!this._texture) {
  34107. this.loadTexture();
  34108. }
  34109. };
  34110. /**
  34111. * Parses a color grading texture serialized by Babylon.
  34112. * @param parsedTexture The texture information being parsedTexture
  34113. * @param scene The scene to load the texture in
  34114. * @param rootUrl The root url of the data assets to load
  34115. * @return A color gradind texture
  34116. */
  34117. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34118. var texture = null;
  34119. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34120. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34121. texture.name = parsedTexture.name;
  34122. texture.level = parsedTexture.level;
  34123. }
  34124. return texture;
  34125. };
  34126. /**
  34127. * Serializes the LUT texture to json format.
  34128. */
  34129. ColorGradingTexture.prototype.serialize = function () {
  34130. if (!this.name) {
  34131. return null;
  34132. }
  34133. var serializationObject = {};
  34134. serializationObject.name = this.name;
  34135. serializationObject.level = this.level;
  34136. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34137. return serializationObject;
  34138. };
  34139. /**
  34140. * Empty line regex stored for GC.
  34141. */
  34142. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34143. return ColorGradingTexture;
  34144. }(BABYLON.BaseTexture));
  34145. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34146. })(BABYLON || (BABYLON = {}));
  34147. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34148. var BABYLON;
  34149. (function (BABYLON) {
  34150. /**
  34151. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34152. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34153. * 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;
  34154. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34155. */
  34156. var ColorCurves = /** @class */ (function () {
  34157. function ColorCurves() {
  34158. this._dirty = true;
  34159. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34160. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34161. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34162. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34163. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34164. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34165. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34166. this._globalHue = 30;
  34167. this._globalDensity = 0;
  34168. this._globalSaturation = 0;
  34169. this._globalExposure = 0;
  34170. this._highlightsHue = 30;
  34171. this._highlightsDensity = 0;
  34172. this._highlightsSaturation = 0;
  34173. this._highlightsExposure = 0;
  34174. this._midtonesHue = 30;
  34175. this._midtonesDensity = 0;
  34176. this._midtonesSaturation = 0;
  34177. this._midtonesExposure = 0;
  34178. this._shadowsHue = 30;
  34179. this._shadowsDensity = 0;
  34180. this._shadowsSaturation = 0;
  34181. this._shadowsExposure = 0;
  34182. }
  34183. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34184. /**
  34185. * Gets the global Hue value.
  34186. * 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).
  34187. */
  34188. get: function () {
  34189. return this._globalHue;
  34190. },
  34191. /**
  34192. * Sets the global Hue value.
  34193. * 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).
  34194. */
  34195. set: function (value) {
  34196. this._globalHue = value;
  34197. this._dirty = true;
  34198. },
  34199. enumerable: true,
  34200. configurable: true
  34201. });
  34202. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34203. /**
  34204. * Gets the global Density value.
  34205. * 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.
  34206. * Values less than zero provide a filter of opposite hue.
  34207. */
  34208. get: function () {
  34209. return this._globalDensity;
  34210. },
  34211. /**
  34212. * Sets the global Density value.
  34213. * 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.
  34214. * Values less than zero provide a filter of opposite hue.
  34215. */
  34216. set: function (value) {
  34217. this._globalDensity = value;
  34218. this._dirty = true;
  34219. },
  34220. enumerable: true,
  34221. configurable: true
  34222. });
  34223. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34224. /**
  34225. * Gets the global Saturation value.
  34226. * 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.
  34227. */
  34228. get: function () {
  34229. return this._globalSaturation;
  34230. },
  34231. /**
  34232. * Sets the global Saturation value.
  34233. * 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.
  34234. */
  34235. set: function (value) {
  34236. this._globalSaturation = value;
  34237. this._dirty = true;
  34238. },
  34239. enumerable: true,
  34240. configurable: true
  34241. });
  34242. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34243. /**
  34244. * Gets the highlights Hue value.
  34245. * 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).
  34246. */
  34247. get: function () {
  34248. return this._highlightsHue;
  34249. },
  34250. /**
  34251. * Sets the highlights Hue value.
  34252. * 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).
  34253. */
  34254. set: function (value) {
  34255. this._highlightsHue = value;
  34256. this._dirty = true;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34262. /**
  34263. * Gets the highlights Density value.
  34264. * 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.
  34265. * Values less than zero provide a filter of opposite hue.
  34266. */
  34267. get: function () {
  34268. return this._highlightsDensity;
  34269. },
  34270. /**
  34271. * Sets the highlights Density value.
  34272. * 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.
  34273. * Values less than zero provide a filter of opposite hue.
  34274. */
  34275. set: function (value) {
  34276. this._highlightsDensity = value;
  34277. this._dirty = true;
  34278. },
  34279. enumerable: true,
  34280. configurable: true
  34281. });
  34282. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34283. /**
  34284. * Gets the highlights Saturation value.
  34285. * 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.
  34286. */
  34287. get: function () {
  34288. return this._highlightsSaturation;
  34289. },
  34290. /**
  34291. * Sets the highlights Saturation value.
  34292. * 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.
  34293. */
  34294. set: function (value) {
  34295. this._highlightsSaturation = value;
  34296. this._dirty = true;
  34297. },
  34298. enumerable: true,
  34299. configurable: true
  34300. });
  34301. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34302. /**
  34303. * Gets the highlights Exposure value.
  34304. * 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.
  34305. */
  34306. get: function () {
  34307. return this._highlightsExposure;
  34308. },
  34309. /**
  34310. * Sets the highlights Exposure value.
  34311. * 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.
  34312. */
  34313. set: function (value) {
  34314. this._highlightsExposure = value;
  34315. this._dirty = true;
  34316. },
  34317. enumerable: true,
  34318. configurable: true
  34319. });
  34320. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34321. /**
  34322. * Gets the midtones Hue value.
  34323. * 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).
  34324. */
  34325. get: function () {
  34326. return this._midtonesHue;
  34327. },
  34328. /**
  34329. * Sets the midtones Hue value.
  34330. * 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).
  34331. */
  34332. set: function (value) {
  34333. this._midtonesHue = value;
  34334. this._dirty = true;
  34335. },
  34336. enumerable: true,
  34337. configurable: true
  34338. });
  34339. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34340. /**
  34341. * Gets the midtones Density value.
  34342. * 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.
  34343. * Values less than zero provide a filter of opposite hue.
  34344. */
  34345. get: function () {
  34346. return this._midtonesDensity;
  34347. },
  34348. /**
  34349. * Sets the midtones Density value.
  34350. * 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.
  34351. * Values less than zero provide a filter of opposite hue.
  34352. */
  34353. set: function (value) {
  34354. this._midtonesDensity = value;
  34355. this._dirty = true;
  34356. },
  34357. enumerable: true,
  34358. configurable: true
  34359. });
  34360. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34361. /**
  34362. * Gets the midtones Saturation value.
  34363. * 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.
  34364. */
  34365. get: function () {
  34366. return this._midtonesSaturation;
  34367. },
  34368. /**
  34369. * Sets the midtones Saturation value.
  34370. * 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.
  34371. */
  34372. set: function (value) {
  34373. this._midtonesSaturation = value;
  34374. this._dirty = true;
  34375. },
  34376. enumerable: true,
  34377. configurable: true
  34378. });
  34379. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34380. /**
  34381. * Gets the midtones Exposure value.
  34382. * 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.
  34383. */
  34384. get: function () {
  34385. return this._midtonesExposure;
  34386. },
  34387. /**
  34388. * Sets the midtones Exposure value.
  34389. * 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.
  34390. */
  34391. set: function (value) {
  34392. this._midtonesExposure = value;
  34393. this._dirty = true;
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34399. /**
  34400. * Gets the shadows Hue value.
  34401. * 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).
  34402. */
  34403. get: function () {
  34404. return this._shadowsHue;
  34405. },
  34406. /**
  34407. * Sets the shadows Hue value.
  34408. * 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).
  34409. */
  34410. set: function (value) {
  34411. this._shadowsHue = value;
  34412. this._dirty = true;
  34413. },
  34414. enumerable: true,
  34415. configurable: true
  34416. });
  34417. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34418. /**
  34419. * Gets the shadows Density value.
  34420. * 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.
  34421. * Values less than zero provide a filter of opposite hue.
  34422. */
  34423. get: function () {
  34424. return this._shadowsDensity;
  34425. },
  34426. /**
  34427. * Sets the shadows Density value.
  34428. * 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.
  34429. * Values less than zero provide a filter of opposite hue.
  34430. */
  34431. set: function (value) {
  34432. this._shadowsDensity = value;
  34433. this._dirty = true;
  34434. },
  34435. enumerable: true,
  34436. configurable: true
  34437. });
  34438. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34439. /**
  34440. * Gets the shadows Saturation value.
  34441. * 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.
  34442. */
  34443. get: function () {
  34444. return this._shadowsSaturation;
  34445. },
  34446. /**
  34447. * Sets the shadows Saturation value.
  34448. * 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.
  34449. */
  34450. set: function (value) {
  34451. this._shadowsSaturation = value;
  34452. this._dirty = true;
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34458. /**
  34459. * Gets the shadows Exposure value.
  34460. * 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.
  34461. */
  34462. get: function () {
  34463. return this._shadowsExposure;
  34464. },
  34465. /**
  34466. * Sets the shadows Exposure value.
  34467. * 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.
  34468. */
  34469. set: function (value) {
  34470. this._shadowsExposure = value;
  34471. this._dirty = true;
  34472. },
  34473. enumerable: true,
  34474. configurable: true
  34475. });
  34476. ColorCurves.prototype.getClassName = function () {
  34477. return "ColorCurves";
  34478. };
  34479. /**
  34480. * Binds the color curves to the shader.
  34481. * @param colorCurves The color curve to bind
  34482. * @param effect The effect to bind to
  34483. */
  34484. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34485. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34486. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34487. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34488. if (colorCurves._dirty) {
  34489. colorCurves._dirty = false;
  34490. // Fill in global info.
  34491. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34492. // Compute highlights info.
  34493. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34494. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34495. // Compute midtones info.
  34496. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34497. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34498. // Compute shadows info.
  34499. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34500. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34501. // Compute deltas (neutral is midtones).
  34502. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34503. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34504. }
  34505. if (effect) {
  34506. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34507. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34508. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34509. }
  34510. };
  34511. /**
  34512. * Prepare the list of uniforms associated with the ColorCurves effects.
  34513. * @param uniformsList The list of uniforms used in the effect
  34514. */
  34515. ColorCurves.PrepareUniforms = function (uniformsList) {
  34516. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34517. };
  34518. /**
  34519. * Returns color grading data based on a hue, density, saturation and exposure value.
  34520. * @param filterHue The hue of the color filter.
  34521. * @param filterDensity The density of the color filter.
  34522. * @param saturation The saturation.
  34523. * @param exposure The exposure.
  34524. * @param result The result data container.
  34525. */
  34526. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34527. if (hue == null) {
  34528. return;
  34529. }
  34530. hue = ColorCurves.clamp(hue, 0, 360);
  34531. density = ColorCurves.clamp(density, -100, 100);
  34532. saturation = ColorCurves.clamp(saturation, -100, 100);
  34533. exposure = ColorCurves.clamp(exposure, -100, 100);
  34534. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34535. // so that the maximum filter density is only 50% control. This provides fine control
  34536. // for small values and reasonable range.
  34537. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34538. density *= 0.5;
  34539. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34540. if (density < 0) {
  34541. density *= -1;
  34542. hue = (hue + 180) % 360;
  34543. }
  34544. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34545. result.scaleToRef(2, result);
  34546. result.a = 1 + 0.01 * saturation;
  34547. };
  34548. /**
  34549. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34550. * @param value The input slider value in range [-100,100].
  34551. * @returns Adjusted value.
  34552. */
  34553. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34554. value /= 100;
  34555. var x = Math.abs(value);
  34556. x = Math.pow(x, 2);
  34557. if (value < 0) {
  34558. x *= -1;
  34559. }
  34560. x *= 100;
  34561. return x;
  34562. };
  34563. /**
  34564. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34565. * @param hue The hue (H) input.
  34566. * @param saturation The saturation (S) input.
  34567. * @param brightness The brightness (B) input.
  34568. * @result An RGBA color represented as Vector4.
  34569. */
  34570. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34571. var h = ColorCurves.clamp(hue, 0, 360);
  34572. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34573. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34574. if (s === 0) {
  34575. result.r = v;
  34576. result.g = v;
  34577. result.b = v;
  34578. }
  34579. else {
  34580. // sector 0 to 5
  34581. h /= 60;
  34582. var i = Math.floor(h);
  34583. // fractional part of h
  34584. var f = h - i;
  34585. var p = v * (1 - s);
  34586. var q = v * (1 - s * f);
  34587. var t = v * (1 - s * (1 - f));
  34588. switch (i) {
  34589. case 0:
  34590. result.r = v;
  34591. result.g = t;
  34592. result.b = p;
  34593. break;
  34594. case 1:
  34595. result.r = q;
  34596. result.g = v;
  34597. result.b = p;
  34598. break;
  34599. case 2:
  34600. result.r = p;
  34601. result.g = v;
  34602. result.b = t;
  34603. break;
  34604. case 3:
  34605. result.r = p;
  34606. result.g = q;
  34607. result.b = v;
  34608. break;
  34609. case 4:
  34610. result.r = t;
  34611. result.g = p;
  34612. result.b = v;
  34613. break;
  34614. default:// case 5:
  34615. result.r = v;
  34616. result.g = p;
  34617. result.b = q;
  34618. break;
  34619. }
  34620. }
  34621. result.a = 1;
  34622. };
  34623. /**
  34624. * Returns a value clamped between min and max
  34625. * @param value The value to clamp
  34626. * @param min The minimum of value
  34627. * @param max The maximum of value
  34628. * @returns The clamped value.
  34629. */
  34630. ColorCurves.clamp = function (value, min, max) {
  34631. return Math.min(Math.max(value, min), max);
  34632. };
  34633. /**
  34634. * Clones the current color curve instance.
  34635. * @return The cloned curves
  34636. */
  34637. ColorCurves.prototype.clone = function () {
  34638. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34639. };
  34640. /**
  34641. * Serializes the current color curve instance to a json representation.
  34642. * @return a JSON representation
  34643. */
  34644. ColorCurves.prototype.serialize = function () {
  34645. return BABYLON.SerializationHelper.Serialize(this);
  34646. };
  34647. /**
  34648. * Parses the color curve from a json representation.
  34649. * @param source the JSON source to parse
  34650. * @return The parsed curves
  34651. */
  34652. ColorCurves.Parse = function (source) {
  34653. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34654. };
  34655. __decorate([
  34656. BABYLON.serialize()
  34657. ], ColorCurves.prototype, "_globalHue", void 0);
  34658. __decorate([
  34659. BABYLON.serialize()
  34660. ], ColorCurves.prototype, "_globalDensity", void 0);
  34661. __decorate([
  34662. BABYLON.serialize()
  34663. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34664. __decorate([
  34665. BABYLON.serialize()
  34666. ], ColorCurves.prototype, "_globalExposure", void 0);
  34667. __decorate([
  34668. BABYLON.serialize()
  34669. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34670. __decorate([
  34671. BABYLON.serialize()
  34672. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34673. __decorate([
  34674. BABYLON.serialize()
  34675. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34676. __decorate([
  34677. BABYLON.serialize()
  34678. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34679. __decorate([
  34680. BABYLON.serialize()
  34681. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34682. __decorate([
  34683. BABYLON.serialize()
  34684. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34685. __decorate([
  34686. BABYLON.serialize()
  34687. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34688. __decorate([
  34689. BABYLON.serialize()
  34690. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34691. return ColorCurves;
  34692. }());
  34693. BABYLON.ColorCurves = ColorCurves;
  34694. })(BABYLON || (BABYLON = {}));
  34695. //# sourceMappingURL=babylon.colorCurves.js.map
  34696. //# sourceMappingURL=babylon.behavior.js.map
  34697. var BABYLON;
  34698. (function (BABYLON) {
  34699. var MaterialHelper = /** @class */ (function () {
  34700. function MaterialHelper() {
  34701. }
  34702. MaterialHelper.BindEyePosition = function (effect, scene) {
  34703. if (scene._forcedViewPosition) {
  34704. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34705. return;
  34706. }
  34707. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34708. };
  34709. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34710. defines._needUVs = true;
  34711. defines[key] = true;
  34712. if (texture.getTextureMatrix().isIdentity(true)) {
  34713. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34714. if (texture.coordinatesIndex === 0) {
  34715. defines["MAINUV1"] = true;
  34716. }
  34717. else {
  34718. defines["MAINUV2"] = true;
  34719. }
  34720. }
  34721. else {
  34722. defines[key + "DIRECTUV"] = 0;
  34723. }
  34724. };
  34725. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34726. var matrix = texture.getTextureMatrix();
  34727. if (!matrix.isIdentity(true)) {
  34728. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34729. }
  34730. };
  34731. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34732. if (defines._areMiscDirty) {
  34733. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34734. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34735. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34736. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34737. }
  34738. };
  34739. /**
  34740. * Helper used to prepare the list of defines for shader compilation
  34741. * @param scene defines the current scene
  34742. * @param engine defines the current engine
  34743. * @param defines specifies the list of active defines
  34744. * @param useInstances defines if instances have to be turned on
  34745. * @param alphaTest defines if alpha testing has to be turned on
  34746. */
  34747. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  34748. var changed = false;
  34749. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34750. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34751. changed = true;
  34752. }
  34753. if (defines["ALPHATEST"] !== alphaTest) {
  34754. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34755. changed = true;
  34756. }
  34757. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34758. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34759. changed = true;
  34760. }
  34761. if (defines["INSTANCES"] !== useInstances) {
  34762. defines["INSTANCES"] = useInstances;
  34763. changed = true;
  34764. }
  34765. if (changed) {
  34766. defines.markAsUnprocessed();
  34767. }
  34768. };
  34769. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34770. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34771. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34772. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34773. return false;
  34774. }
  34775. defines._normals = defines._needNormals;
  34776. defines._uvs = defines._needUVs;
  34777. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34778. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34779. defines["TANGENT"] = true;
  34780. }
  34781. if (defines._needUVs) {
  34782. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34783. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34784. }
  34785. else {
  34786. defines["UV1"] = false;
  34787. defines["UV2"] = false;
  34788. }
  34789. if (useVertexColor) {
  34790. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34791. defines["VERTEXCOLOR"] = hasVertexColors;
  34792. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34793. }
  34794. if (useBones) {
  34795. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34796. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34797. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34798. }
  34799. else {
  34800. defines["NUM_BONE_INFLUENCERS"] = 0;
  34801. defines["BonesPerMesh"] = 0;
  34802. }
  34803. }
  34804. if (useMorphTargets) {
  34805. var manager = mesh.morphTargetManager;
  34806. if (manager) {
  34807. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34808. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34809. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34810. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34811. }
  34812. else {
  34813. defines["MORPHTARGETS_TANGENT"] = false;
  34814. defines["MORPHTARGETS_NORMAL"] = false;
  34815. defines["MORPHTARGETS"] = false;
  34816. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34817. }
  34818. }
  34819. return true;
  34820. };
  34821. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34822. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34823. if (disableLighting === void 0) { disableLighting = false; }
  34824. if (!defines._areLightsDirty) {
  34825. return defines._needNormals;
  34826. }
  34827. var lightIndex = 0;
  34828. var needNormals = false;
  34829. var needRebuild = false;
  34830. var lightmapMode = false;
  34831. var shadowEnabled = false;
  34832. var specularEnabled = false;
  34833. if (scene.lightsEnabled && !disableLighting) {
  34834. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34835. var light = _a[_i];
  34836. needNormals = true;
  34837. if (defines["LIGHT" + lightIndex] === undefined) {
  34838. needRebuild = true;
  34839. }
  34840. defines["LIGHT" + lightIndex] = true;
  34841. defines["SPOTLIGHT" + lightIndex] = false;
  34842. defines["HEMILIGHT" + lightIndex] = false;
  34843. defines["POINTLIGHT" + lightIndex] = false;
  34844. defines["DIRLIGHT" + lightIndex] = false;
  34845. var type;
  34846. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34847. type = "SPOTLIGHT" + lightIndex;
  34848. }
  34849. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34850. type = "HEMILIGHT" + lightIndex;
  34851. }
  34852. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34853. type = "POINTLIGHT" + lightIndex;
  34854. }
  34855. else {
  34856. type = "DIRLIGHT" + lightIndex;
  34857. }
  34858. defines[type] = true;
  34859. // Specular
  34860. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34861. specularEnabled = true;
  34862. }
  34863. // Shadows
  34864. defines["SHADOW" + lightIndex] = false;
  34865. defines["SHADOWPCF" + lightIndex] = false;
  34866. defines["SHADOWESM" + lightIndex] = false;
  34867. defines["SHADOWCUBE" + lightIndex] = false;
  34868. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34869. var shadowGenerator = light.getShadowGenerator();
  34870. if (shadowGenerator) {
  34871. shadowEnabled = true;
  34872. shadowGenerator.prepareDefines(defines, lightIndex);
  34873. }
  34874. }
  34875. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34876. lightmapMode = true;
  34877. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34878. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34879. }
  34880. else {
  34881. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34882. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34883. }
  34884. lightIndex++;
  34885. if (lightIndex === maxSimultaneousLights)
  34886. break;
  34887. }
  34888. }
  34889. defines["SPECULARTERM"] = specularEnabled;
  34890. defines["SHADOWS"] = shadowEnabled;
  34891. // Resetting all other lights if any
  34892. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34893. if (defines["LIGHT" + index] !== undefined) {
  34894. defines["LIGHT" + index] = false;
  34895. defines["HEMILIGHT" + lightIndex] = false;
  34896. defines["POINTLIGHT" + lightIndex] = false;
  34897. defines["DIRLIGHT" + lightIndex] = false;
  34898. defines["SPOTLIGHT" + lightIndex] = false;
  34899. defines["SHADOW" + lightIndex] = false;
  34900. }
  34901. }
  34902. var caps = scene.getEngine().getCaps();
  34903. if (defines["SHADOWFLOAT"] === undefined) {
  34904. needRebuild = true;
  34905. }
  34906. defines["SHADOWFLOAT"] = shadowEnabled &&
  34907. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34908. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34909. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34910. if (needRebuild) {
  34911. defines.rebuild();
  34912. }
  34913. return needNormals;
  34914. };
  34915. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34916. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34917. var uniformsList;
  34918. var uniformBuffersList = null;
  34919. if (uniformsListOrOptions.uniformsNames) {
  34920. var options = uniformsListOrOptions;
  34921. uniformsList = options.uniformsNames;
  34922. uniformBuffersList = options.uniformBuffersNames;
  34923. samplersList = options.samplers;
  34924. defines = options.defines;
  34925. maxSimultaneousLights = options.maxSimultaneousLights;
  34926. }
  34927. else {
  34928. uniformsList = uniformsListOrOptions;
  34929. if (!samplersList) {
  34930. samplersList = [];
  34931. }
  34932. }
  34933. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34934. if (!defines["LIGHT" + lightIndex]) {
  34935. break;
  34936. }
  34937. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34938. if (uniformBuffersList) {
  34939. uniformBuffersList.push("Light" + lightIndex);
  34940. }
  34941. samplersList.push("shadowSampler" + lightIndex);
  34942. }
  34943. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34944. uniformsList.push("morphTargetInfluences");
  34945. }
  34946. };
  34947. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34948. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34949. if (rank === void 0) { rank = 0; }
  34950. var lightFallbackRank = 0;
  34951. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34952. if (!defines["LIGHT" + lightIndex]) {
  34953. break;
  34954. }
  34955. if (lightIndex > 0) {
  34956. lightFallbackRank = rank + lightIndex;
  34957. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34958. }
  34959. if (!defines["SHADOWS"]) {
  34960. if (defines["SHADOW" + lightIndex]) {
  34961. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34962. }
  34963. if (defines["SHADOWPCF" + lightIndex]) {
  34964. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34965. }
  34966. if (defines["SHADOWESM" + lightIndex]) {
  34967. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34968. }
  34969. }
  34970. }
  34971. return lightFallbackRank++;
  34972. };
  34973. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34974. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34975. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34976. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34977. var manager = mesh.morphTargetManager;
  34978. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34979. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34980. for (var index = 0; index < influencers; index++) {
  34981. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34982. if (normal) {
  34983. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34984. }
  34985. if (tangent) {
  34986. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34987. }
  34988. if (attribs.length > maxAttributesCount) {
  34989. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34990. }
  34991. }
  34992. }
  34993. };
  34994. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34995. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34996. fallbacks.addCPUSkinningFallback(0, mesh);
  34997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34999. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  35000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35002. }
  35003. }
  35004. };
  35005. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  35006. if (defines["INSTANCES"]) {
  35007. attribs.push("world0");
  35008. attribs.push("world1");
  35009. attribs.push("world2");
  35010. attribs.push("world3");
  35011. }
  35012. };
  35013. // Bindings
  35014. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  35015. if (light.shadowEnabled && mesh.receiveShadows) {
  35016. var shadowGenerator = light.getShadowGenerator();
  35017. if (shadowGenerator) {
  35018. shadowGenerator.bindShadowLight(lightIndex, effect);
  35019. }
  35020. }
  35021. };
  35022. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  35023. light.transferToEffect(effect, lightIndex + "");
  35024. };
  35025. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  35026. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35027. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  35028. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  35029. for (var i = 0; i < len; i++) {
  35030. var light = mesh._lightSources[i];
  35031. var iAsString = i.toString();
  35032. var scaledIntensity = light.getScaledIntensity();
  35033. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  35034. MaterialHelper.BindLightProperties(light, effect, i);
  35035. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  35036. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  35037. if (defines["SPECULARTERM"]) {
  35038. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  35039. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  35040. }
  35041. // Shadows
  35042. if (scene.shadowsEnabled) {
  35043. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  35044. }
  35045. light._uniformBuffer.update();
  35046. }
  35047. };
  35048. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  35049. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35050. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35051. effect.setColor3("vFogColor", scene.fogColor);
  35052. }
  35053. };
  35054. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  35055. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35056. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  35057. if (matrices && effect) {
  35058. effect.setMatrices("mBones", matrices);
  35059. }
  35060. }
  35061. };
  35062. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  35063. var manager = abstractMesh.morphTargetManager;
  35064. if (!abstractMesh || !manager) {
  35065. return;
  35066. }
  35067. effect.setFloatArray("morphTargetInfluences", manager.influences);
  35068. };
  35069. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  35070. if (defines["LOGARITHMICDEPTH"]) {
  35071. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  35072. }
  35073. };
  35074. MaterialHelper.BindClipPlane = function (effect, scene) {
  35075. if (scene.clipPlane) {
  35076. var clipPlane = scene.clipPlane;
  35077. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35078. }
  35079. };
  35080. return MaterialHelper;
  35081. }());
  35082. BABYLON.MaterialHelper = MaterialHelper;
  35083. })(BABYLON || (BABYLON = {}));
  35084. //# sourceMappingURL=babylon.materialHelper.js.map
  35085. var BABYLON;
  35086. (function (BABYLON) {
  35087. var PushMaterial = /** @class */ (function (_super) {
  35088. __extends(PushMaterial, _super);
  35089. function PushMaterial(name, scene) {
  35090. var _this = _super.call(this, name, scene) || this;
  35091. _this.storeEffectOnSubMeshes = true;
  35092. return _this;
  35093. }
  35094. PushMaterial.prototype.getEffect = function () {
  35095. return this._activeEffect;
  35096. };
  35097. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  35098. if (!mesh) {
  35099. return false;
  35100. }
  35101. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  35102. return true;
  35103. }
  35104. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  35105. };
  35106. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35107. this._activeEffect.setMatrix("world", world);
  35108. };
  35109. PushMaterial.prototype.bind = function (world, mesh) {
  35110. if (!mesh) {
  35111. return;
  35112. }
  35113. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  35114. };
  35115. PushMaterial.prototype._afterBind = function (mesh, effect) {
  35116. if (effect === void 0) { effect = null; }
  35117. _super.prototype._afterBind.call(this, mesh);
  35118. this.getScene()._cachedEffect = effect;
  35119. };
  35120. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35121. if (visibility === void 0) { visibility = 1; }
  35122. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35123. };
  35124. return PushMaterial;
  35125. }(BABYLON.Material));
  35126. BABYLON.PushMaterial = PushMaterial;
  35127. })(BABYLON || (BABYLON = {}));
  35128. //# sourceMappingURL=babylon.pushMaterial.js.map
  35129. var BABYLON;
  35130. (function (BABYLON) {
  35131. var StandardMaterialDefines = /** @class */ (function (_super) {
  35132. __extends(StandardMaterialDefines, _super);
  35133. function StandardMaterialDefines() {
  35134. var _this = _super.call(this) || this;
  35135. _this.MAINUV1 = false;
  35136. _this.MAINUV2 = false;
  35137. _this.DIFFUSE = false;
  35138. _this.DIFFUSEDIRECTUV = 0;
  35139. _this.AMBIENT = false;
  35140. _this.AMBIENTDIRECTUV = 0;
  35141. _this.OPACITY = false;
  35142. _this.OPACITYDIRECTUV = 0;
  35143. _this.OPACITYRGB = false;
  35144. _this.REFLECTION = false;
  35145. _this.EMISSIVE = false;
  35146. _this.EMISSIVEDIRECTUV = 0;
  35147. _this.SPECULAR = false;
  35148. _this.SPECULARDIRECTUV = 0;
  35149. _this.BUMP = false;
  35150. _this.BUMPDIRECTUV = 0;
  35151. _this.PARALLAX = false;
  35152. _this.PARALLAXOCCLUSION = false;
  35153. _this.SPECULAROVERALPHA = false;
  35154. _this.CLIPPLANE = false;
  35155. _this.ALPHATEST = false;
  35156. _this.DEPTHPREPASS = false;
  35157. _this.ALPHAFROMDIFFUSE = false;
  35158. _this.POINTSIZE = false;
  35159. _this.FOG = false;
  35160. _this.SPECULARTERM = false;
  35161. _this.DIFFUSEFRESNEL = false;
  35162. _this.OPACITYFRESNEL = false;
  35163. _this.REFLECTIONFRESNEL = false;
  35164. _this.REFRACTIONFRESNEL = false;
  35165. _this.EMISSIVEFRESNEL = false;
  35166. _this.FRESNEL = false;
  35167. _this.NORMAL = false;
  35168. _this.UV1 = false;
  35169. _this.UV2 = false;
  35170. _this.VERTEXCOLOR = false;
  35171. _this.VERTEXALPHA = false;
  35172. _this.NUM_BONE_INFLUENCERS = 0;
  35173. _this.BonesPerMesh = 0;
  35174. _this.INSTANCES = false;
  35175. _this.GLOSSINESS = false;
  35176. _this.ROUGHNESS = false;
  35177. _this.EMISSIVEASILLUMINATION = false;
  35178. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35179. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35180. _this.LIGHTMAP = false;
  35181. _this.LIGHTMAPDIRECTUV = 0;
  35182. _this.USELIGHTMAPASSHADOWMAP = false;
  35183. _this.REFLECTIONMAP_3D = false;
  35184. _this.REFLECTIONMAP_SPHERICAL = false;
  35185. _this.REFLECTIONMAP_PLANAR = false;
  35186. _this.REFLECTIONMAP_CUBIC = false;
  35187. _this.REFLECTIONMAP_PROJECTION = false;
  35188. _this.REFLECTIONMAP_SKYBOX = false;
  35189. _this.REFLECTIONMAP_EXPLICIT = false;
  35190. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35191. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35192. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35193. _this.INVERTCUBICMAP = false;
  35194. _this.LOGARITHMICDEPTH = false;
  35195. _this.REFRACTION = false;
  35196. _this.REFRACTIONMAP_3D = false;
  35197. _this.REFLECTIONOVERALPHA = false;
  35198. _this.TWOSIDEDLIGHTING = false;
  35199. _this.SHADOWFLOAT = false;
  35200. _this.MORPHTARGETS = false;
  35201. _this.MORPHTARGETS_NORMAL = false;
  35202. _this.MORPHTARGETS_TANGENT = false;
  35203. _this.NUM_MORPH_INFLUENCERS = 0;
  35204. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35205. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35206. _this.IMAGEPROCESSING = false;
  35207. _this.VIGNETTE = false;
  35208. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35209. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35210. _this.TONEMAPPING = false;
  35211. _this.CONTRAST = false;
  35212. _this.COLORCURVES = false;
  35213. _this.COLORGRADING = false;
  35214. _this.COLORGRADING3D = false;
  35215. _this.SAMPLER3DGREENDEPTH = false;
  35216. _this.SAMPLER3DBGRMAP = false;
  35217. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35218. _this.EXPOSURE = false;
  35219. _this.rebuild();
  35220. return _this;
  35221. }
  35222. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35223. var modes = [
  35224. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35225. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35226. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35227. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35228. ];
  35229. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35230. var mode = modes_1[_i];
  35231. this[mode] = (mode === modeToEnable);
  35232. }
  35233. };
  35234. return StandardMaterialDefines;
  35235. }(BABYLON.MaterialDefines));
  35236. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35237. var StandardMaterial = /** @class */ (function (_super) {
  35238. __extends(StandardMaterial, _super);
  35239. function StandardMaterial(name, scene) {
  35240. var _this = _super.call(this, name, scene) || this;
  35241. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35242. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35243. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35244. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35245. _this.specularPower = 64;
  35246. _this._useAlphaFromDiffuseTexture = false;
  35247. _this._useEmissiveAsIllumination = false;
  35248. _this._linkEmissiveWithDiffuse = false;
  35249. _this._useSpecularOverAlpha = false;
  35250. _this._useReflectionOverAlpha = false;
  35251. _this._disableLighting = false;
  35252. _this._useParallax = false;
  35253. _this._useParallaxOcclusion = false;
  35254. _this.parallaxScaleBias = 0.05;
  35255. _this._roughness = 0;
  35256. _this.indexOfRefraction = 0.98;
  35257. _this.invertRefractionY = true;
  35258. _this._useLightmapAsShadowmap = false;
  35259. _this._useReflectionFresnelFromSpecular = false;
  35260. _this._useGlossinessFromSpecularMapAlpha = false;
  35261. _this._maxSimultaneousLights = 4;
  35262. /**
  35263. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35264. */
  35265. _this._invertNormalMapX = false;
  35266. /**
  35267. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35268. */
  35269. _this._invertNormalMapY = false;
  35270. /**
  35271. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35272. */
  35273. _this._twoSidedLighting = false;
  35274. _this._renderTargets = new BABYLON.SmartArray(16);
  35275. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35276. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35277. // Setup the default processing configuration to the scene.
  35278. _this._attachImageProcessingConfiguration(null);
  35279. _this.getRenderTargetTextures = function () {
  35280. _this._renderTargets.reset();
  35281. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35282. _this._renderTargets.push(_this._reflectionTexture);
  35283. }
  35284. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35285. _this._renderTargets.push(_this._refractionTexture);
  35286. }
  35287. return _this._renderTargets;
  35288. };
  35289. return _this;
  35290. }
  35291. ;
  35292. ;
  35293. ;
  35294. ;
  35295. ;
  35296. ;
  35297. ;
  35298. ;
  35299. ;
  35300. ;
  35301. ;
  35302. ;
  35303. ;
  35304. ;
  35305. ;
  35306. ;
  35307. ;
  35308. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35309. /**
  35310. * Gets the image processing configuration used either in this material.
  35311. */
  35312. get: function () {
  35313. return this._imageProcessingConfiguration;
  35314. },
  35315. /**
  35316. * Sets the Default image processing configuration used either in the this material.
  35317. *
  35318. * If sets to null, the scene one is in use.
  35319. */
  35320. set: function (value) {
  35321. this._attachImageProcessingConfiguration(value);
  35322. // Ensure the effect will be rebuilt.
  35323. this._markAllSubMeshesAsTexturesDirty();
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. /**
  35329. * Attaches a new image processing configuration to the Standard Material.
  35330. * @param configuration
  35331. */
  35332. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35333. var _this = this;
  35334. if (configuration === this._imageProcessingConfiguration) {
  35335. return;
  35336. }
  35337. // Detaches observer.
  35338. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35339. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35340. }
  35341. // Pick the scene configuration if needed.
  35342. if (!configuration) {
  35343. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35344. }
  35345. else {
  35346. this._imageProcessingConfiguration = configuration;
  35347. }
  35348. // Attaches observer.
  35349. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35350. _this._markAllSubMeshesAsImageProcessingDirty();
  35351. });
  35352. };
  35353. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35354. /**
  35355. * Gets wether the color curves effect is enabled.
  35356. */
  35357. get: function () {
  35358. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35359. },
  35360. /**
  35361. * Sets wether the color curves effect is enabled.
  35362. */
  35363. set: function (value) {
  35364. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35365. },
  35366. enumerable: true,
  35367. configurable: true
  35368. });
  35369. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35370. /**
  35371. * Gets wether the color grading effect is enabled.
  35372. */
  35373. get: function () {
  35374. return this.imageProcessingConfiguration.colorGradingEnabled;
  35375. },
  35376. /**
  35377. * Gets wether the color grading effect is enabled.
  35378. */
  35379. set: function (value) {
  35380. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35381. },
  35382. enumerable: true,
  35383. configurable: true
  35384. });
  35385. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35386. /**
  35387. * Gets wether tonemapping is enabled or not.
  35388. */
  35389. get: function () {
  35390. return this._imageProcessingConfiguration.toneMappingEnabled;
  35391. },
  35392. /**
  35393. * Sets wether tonemapping is enabled or not
  35394. */
  35395. set: function (value) {
  35396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. ;
  35402. ;
  35403. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35404. /**
  35405. * The camera exposure used on this material.
  35406. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35407. * This corresponds to a photographic exposure.
  35408. */
  35409. get: function () {
  35410. return this._imageProcessingConfiguration.exposure;
  35411. },
  35412. /**
  35413. * The camera exposure used on this material.
  35414. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35415. * This corresponds to a photographic exposure.
  35416. */
  35417. set: function (value) {
  35418. this._imageProcessingConfiguration.exposure = value;
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. ;
  35424. ;
  35425. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35426. /**
  35427. * Gets The camera contrast used on this material.
  35428. */
  35429. get: function () {
  35430. return this._imageProcessingConfiguration.contrast;
  35431. },
  35432. /**
  35433. * Sets The camera contrast used on this material.
  35434. */
  35435. set: function (value) {
  35436. this._imageProcessingConfiguration.contrast = value;
  35437. },
  35438. enumerable: true,
  35439. configurable: true
  35440. });
  35441. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35442. /**
  35443. * Gets the Color Grading 2D Lookup Texture.
  35444. */
  35445. get: function () {
  35446. return this._imageProcessingConfiguration.colorGradingTexture;
  35447. },
  35448. /**
  35449. * Sets the Color Grading 2D Lookup Texture.
  35450. */
  35451. set: function (value) {
  35452. this._imageProcessingConfiguration.colorGradingTexture = value;
  35453. },
  35454. enumerable: true,
  35455. configurable: true
  35456. });
  35457. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35458. /**
  35459. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35460. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35461. * 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;
  35462. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35463. */
  35464. get: function () {
  35465. return this._imageProcessingConfiguration.colorCurves;
  35466. },
  35467. /**
  35468. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35469. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35470. * 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;
  35471. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35472. */
  35473. set: function (value) {
  35474. this._imageProcessingConfiguration.colorCurves = value;
  35475. },
  35476. enumerable: true,
  35477. configurable: true
  35478. });
  35479. StandardMaterial.prototype.getClassName = function () {
  35480. return "StandardMaterial";
  35481. };
  35482. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35483. get: function () {
  35484. return this._useLogarithmicDepth;
  35485. },
  35486. set: function (value) {
  35487. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35488. this._markAllSubMeshesAsMiscDirty();
  35489. },
  35490. enumerable: true,
  35491. configurable: true
  35492. });
  35493. StandardMaterial.prototype.needAlphaBlending = function () {
  35494. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35495. };
  35496. StandardMaterial.prototype.needAlphaTesting = function () {
  35497. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35498. };
  35499. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35500. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35501. };
  35502. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35503. return this._diffuseTexture;
  35504. };
  35505. /**
  35506. * Child classes can use it to update shaders
  35507. */
  35508. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35509. if (useInstances === void 0) { useInstances = false; }
  35510. if (subMesh.effect && this.isFrozen) {
  35511. if (this._wasPreviouslyReady && subMesh.effect) {
  35512. return true;
  35513. }
  35514. }
  35515. if (!subMesh._materialDefines) {
  35516. subMesh._materialDefines = new StandardMaterialDefines();
  35517. }
  35518. var scene = this.getScene();
  35519. var defines = subMesh._materialDefines;
  35520. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35521. if (defines._renderId === scene.getRenderId()) {
  35522. return true;
  35523. }
  35524. }
  35525. var engine = scene.getEngine();
  35526. // Lights
  35527. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35528. // Textures
  35529. if (defines._areTexturesDirty) {
  35530. defines._needUVs = false;
  35531. defines.MAINUV1 = false;
  35532. defines.MAINUV2 = false;
  35533. if (scene.texturesEnabled) {
  35534. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35535. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35536. return false;
  35537. }
  35538. else {
  35539. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35540. }
  35541. }
  35542. else {
  35543. defines.DIFFUSE = false;
  35544. }
  35545. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35546. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35547. return false;
  35548. }
  35549. else {
  35550. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35551. }
  35552. }
  35553. else {
  35554. defines.AMBIENT = false;
  35555. }
  35556. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35557. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35558. return false;
  35559. }
  35560. else {
  35561. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35562. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35563. }
  35564. }
  35565. else {
  35566. defines.OPACITY = false;
  35567. }
  35568. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35569. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35570. return false;
  35571. }
  35572. else {
  35573. defines._needNormals = true;
  35574. defines.REFLECTION = true;
  35575. defines.ROUGHNESS = (this._roughness > 0);
  35576. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35577. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35578. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35579. switch (this._reflectionTexture.coordinatesMode) {
  35580. case BABYLON.Texture.CUBIC_MODE:
  35581. case BABYLON.Texture.INVCUBIC_MODE:
  35582. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35583. break;
  35584. case BABYLON.Texture.EXPLICIT_MODE:
  35585. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35586. break;
  35587. case BABYLON.Texture.PLANAR_MODE:
  35588. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35589. break;
  35590. case BABYLON.Texture.PROJECTION_MODE:
  35591. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35592. break;
  35593. case BABYLON.Texture.SKYBOX_MODE:
  35594. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35595. break;
  35596. case BABYLON.Texture.SPHERICAL_MODE:
  35597. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35598. break;
  35599. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35600. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35601. break;
  35602. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35603. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35604. break;
  35605. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35606. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35607. break;
  35608. }
  35609. }
  35610. }
  35611. else {
  35612. defines.REFLECTION = false;
  35613. }
  35614. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35615. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35616. return false;
  35617. }
  35618. else {
  35619. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35620. }
  35621. }
  35622. else {
  35623. defines.EMISSIVE = false;
  35624. }
  35625. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35626. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35627. return false;
  35628. }
  35629. else {
  35630. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35631. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35632. }
  35633. }
  35634. else {
  35635. defines.LIGHTMAP = false;
  35636. }
  35637. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35638. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35639. return false;
  35640. }
  35641. else {
  35642. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35643. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35644. }
  35645. }
  35646. else {
  35647. defines.SPECULAR = false;
  35648. }
  35649. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35650. // Bump texure can not be not blocking.
  35651. if (!this._bumpTexture.isReady()) {
  35652. return false;
  35653. }
  35654. else {
  35655. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35656. defines.PARALLAX = this._useParallax;
  35657. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35658. }
  35659. }
  35660. else {
  35661. defines.BUMP = false;
  35662. }
  35663. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35664. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35665. return false;
  35666. }
  35667. else {
  35668. defines._needUVs = true;
  35669. defines.REFRACTION = true;
  35670. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35671. }
  35672. }
  35673. else {
  35674. defines.REFRACTION = false;
  35675. }
  35676. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35677. }
  35678. else {
  35679. defines.DIFFUSE = false;
  35680. defines.AMBIENT = false;
  35681. defines.OPACITY = false;
  35682. defines.REFLECTION = false;
  35683. defines.EMISSIVE = false;
  35684. defines.LIGHTMAP = false;
  35685. defines.BUMP = false;
  35686. defines.REFRACTION = false;
  35687. }
  35688. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35689. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35690. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35691. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35692. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35693. }
  35694. if (defines._areImageProcessingDirty) {
  35695. if (!this._imageProcessingConfiguration.isReady()) {
  35696. return false;
  35697. }
  35698. this._imageProcessingConfiguration.prepareDefines(defines);
  35699. }
  35700. if (defines._areFresnelDirty) {
  35701. if (StandardMaterial.FresnelEnabled) {
  35702. // Fresnel
  35703. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35704. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35705. this._reflectionFresnelParameters) {
  35706. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35707. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35708. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35709. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35710. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35711. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35712. defines._needNormals = true;
  35713. defines.FRESNEL = true;
  35714. }
  35715. }
  35716. else {
  35717. defines.FRESNEL = false;
  35718. }
  35719. }
  35720. // Misc.
  35721. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35722. // Attribs
  35723. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35724. // Values that need to be evaluated on every frame
  35725. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  35726. // Get correct effect
  35727. if (defines.isDirty) {
  35728. defines.markAsProcessed();
  35729. scene.resetCachedMaterial();
  35730. // Fallbacks
  35731. var fallbacks = new BABYLON.EffectFallbacks();
  35732. if (defines.REFLECTION) {
  35733. fallbacks.addFallback(0, "REFLECTION");
  35734. }
  35735. if (defines.SPECULAR) {
  35736. fallbacks.addFallback(0, "SPECULAR");
  35737. }
  35738. if (defines.BUMP) {
  35739. fallbacks.addFallback(0, "BUMP");
  35740. }
  35741. if (defines.PARALLAX) {
  35742. fallbacks.addFallback(1, "PARALLAX");
  35743. }
  35744. if (defines.PARALLAXOCCLUSION) {
  35745. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35746. }
  35747. if (defines.SPECULAROVERALPHA) {
  35748. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35749. }
  35750. if (defines.FOG) {
  35751. fallbacks.addFallback(1, "FOG");
  35752. }
  35753. if (defines.POINTSIZE) {
  35754. fallbacks.addFallback(0, "POINTSIZE");
  35755. }
  35756. if (defines.LOGARITHMICDEPTH) {
  35757. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35758. }
  35759. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35760. if (defines.SPECULARTERM) {
  35761. fallbacks.addFallback(0, "SPECULARTERM");
  35762. }
  35763. if (defines.DIFFUSEFRESNEL) {
  35764. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35765. }
  35766. if (defines.OPACITYFRESNEL) {
  35767. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35768. }
  35769. if (defines.REFLECTIONFRESNEL) {
  35770. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35771. }
  35772. if (defines.EMISSIVEFRESNEL) {
  35773. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35774. }
  35775. if (defines.FRESNEL) {
  35776. fallbacks.addFallback(4, "FRESNEL");
  35777. }
  35778. //Attributes
  35779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35780. if (defines.NORMAL) {
  35781. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35782. }
  35783. if (defines.UV1) {
  35784. attribs.push(BABYLON.VertexBuffer.UVKind);
  35785. }
  35786. if (defines.UV2) {
  35787. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35788. }
  35789. if (defines.VERTEXCOLOR) {
  35790. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35791. }
  35792. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35793. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35794. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35795. var shaderName = "default";
  35796. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35797. "vFogInfos", "vFogColor", "pointSize",
  35798. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35799. "mBones",
  35800. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35801. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35802. "logarithmicDepthConstant", "vTangentSpaceParams"
  35803. ];
  35804. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35805. var uniformBuffers = ["Material", "Scene"];
  35806. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35807. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35808. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35809. uniformsNames: uniforms,
  35810. uniformBuffersNames: uniformBuffers,
  35811. samplers: samplers,
  35812. defines: defines,
  35813. maxSimultaneousLights: this._maxSimultaneousLights
  35814. });
  35815. if (this.customShaderNameResolve) {
  35816. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35817. }
  35818. var join = defines.toString();
  35819. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35820. attributes: attribs,
  35821. uniformsNames: uniforms,
  35822. uniformBuffersNames: uniformBuffers,
  35823. samplers: samplers,
  35824. defines: join,
  35825. fallbacks: fallbacks,
  35826. onCompiled: this.onCompiled,
  35827. onError: this.onError,
  35828. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35829. }, engine), defines);
  35830. this.buildUniformLayout();
  35831. }
  35832. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35833. return false;
  35834. }
  35835. defines._renderId = scene.getRenderId();
  35836. this._wasPreviouslyReady = true;
  35837. return true;
  35838. };
  35839. StandardMaterial.prototype.buildUniformLayout = function () {
  35840. // Order is important !
  35841. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35842. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35843. this._uniformBuffer.addUniform("opacityParts", 4);
  35844. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35845. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35846. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35847. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35848. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35849. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35850. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35851. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35852. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35853. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35854. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35855. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35856. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35857. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35858. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35859. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35860. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35861. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35862. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35863. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35864. this._uniformBuffer.addUniform("specularMatrix", 16);
  35865. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35866. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35867. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35868. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35869. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35870. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35871. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35872. this._uniformBuffer.addUniform("pointSize", 1);
  35873. this._uniformBuffer.create();
  35874. };
  35875. StandardMaterial.prototype.unbind = function () {
  35876. if (this._activeEffect) {
  35877. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35878. this._activeEffect.setTexture("reflection2DSampler", null);
  35879. }
  35880. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35881. this._activeEffect.setTexture("refraction2DSampler", null);
  35882. }
  35883. }
  35884. _super.prototype.unbind.call(this);
  35885. };
  35886. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35887. var scene = this.getScene();
  35888. var defines = subMesh._materialDefines;
  35889. if (!defines) {
  35890. return;
  35891. }
  35892. var effect = subMesh.effect;
  35893. if (!effect) {
  35894. return;
  35895. }
  35896. this._activeEffect = effect;
  35897. // Matrices
  35898. this.bindOnlyWorldMatrix(world);
  35899. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35900. // Bones
  35901. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35902. if (mustRebind) {
  35903. this._uniformBuffer.bindToEffect(effect, "Material");
  35904. this.bindViewProjection(effect);
  35905. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35906. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35907. // Fresnel
  35908. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35909. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35910. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35911. }
  35912. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35913. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35914. }
  35915. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35916. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35917. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35918. }
  35919. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35920. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35921. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35922. }
  35923. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35924. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35925. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35926. }
  35927. }
  35928. // Textures
  35929. if (scene.texturesEnabled) {
  35930. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35931. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35932. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35933. }
  35934. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35935. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35936. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35937. }
  35938. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35939. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35940. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35941. }
  35942. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35943. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35944. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35945. }
  35946. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35947. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35948. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35949. }
  35950. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35951. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35952. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35953. }
  35954. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35955. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35956. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35957. }
  35958. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35959. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35960. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35961. if (scene._mirroredCameraPosition) {
  35962. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35963. }
  35964. else {
  35965. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35966. }
  35967. }
  35968. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35969. var depth = 1.0;
  35970. if (!this._refractionTexture.isCube) {
  35971. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35972. if (this._refractionTexture.depth) {
  35973. depth = this._refractionTexture.depth;
  35974. }
  35975. }
  35976. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35977. }
  35978. }
  35979. // Point size
  35980. if (this.pointsCloud) {
  35981. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35982. }
  35983. if (defines.SPECULARTERM) {
  35984. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35985. }
  35986. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35987. // Diffuse
  35988. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35989. }
  35990. // Textures
  35991. if (scene.texturesEnabled) {
  35992. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35993. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35994. }
  35995. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35996. effect.setTexture("ambientSampler", this._ambientTexture);
  35997. }
  35998. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35999. effect.setTexture("opacitySampler", this._opacityTexture);
  36000. }
  36001. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36002. if (this._reflectionTexture.isCube) {
  36003. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  36004. }
  36005. else {
  36006. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  36007. }
  36008. }
  36009. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36010. effect.setTexture("emissiveSampler", this._emissiveTexture);
  36011. }
  36012. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36013. effect.setTexture("lightmapSampler", this._lightmapTexture);
  36014. }
  36015. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36016. effect.setTexture("specularSampler", this._specularTexture);
  36017. }
  36018. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36019. effect.setTexture("bumpSampler", this._bumpTexture);
  36020. }
  36021. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36022. var depth = 1.0;
  36023. if (this._refractionTexture.isCube) {
  36024. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  36025. }
  36026. else {
  36027. effect.setTexture("refraction2DSampler", this._refractionTexture);
  36028. }
  36029. }
  36030. }
  36031. // Clip plane
  36032. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  36033. // Colors
  36034. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  36035. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  36036. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36037. }
  36038. if (mustRebind || !this.isFrozen) {
  36039. // Lights
  36040. if (scene.lightsEnabled && !this._disableLighting) {
  36041. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  36042. }
  36043. // View
  36044. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  36045. this.bindView(effect);
  36046. }
  36047. // Fog
  36048. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  36049. // Morph targets
  36050. if (defines.NUM_MORPH_INFLUENCERS) {
  36051. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  36052. }
  36053. // Log. depth
  36054. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  36055. // image processing
  36056. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  36057. this._imageProcessingConfiguration.bind(this._activeEffect);
  36058. }
  36059. }
  36060. this._uniformBuffer.update();
  36061. this._afterBind(mesh, this._activeEffect);
  36062. };
  36063. StandardMaterial.prototype.getAnimatables = function () {
  36064. var results = [];
  36065. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  36066. results.push(this._diffuseTexture);
  36067. }
  36068. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36069. results.push(this._ambientTexture);
  36070. }
  36071. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36072. results.push(this._opacityTexture);
  36073. }
  36074. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36075. results.push(this._reflectionTexture);
  36076. }
  36077. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36078. results.push(this._emissiveTexture);
  36079. }
  36080. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  36081. results.push(this._specularTexture);
  36082. }
  36083. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36084. results.push(this._bumpTexture);
  36085. }
  36086. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36087. results.push(this._lightmapTexture);
  36088. }
  36089. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36090. results.push(this._refractionTexture);
  36091. }
  36092. return results;
  36093. };
  36094. StandardMaterial.prototype.getActiveTextures = function () {
  36095. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36096. if (this._diffuseTexture) {
  36097. activeTextures.push(this._diffuseTexture);
  36098. }
  36099. if (this._ambientTexture) {
  36100. activeTextures.push(this._ambientTexture);
  36101. }
  36102. if (this._opacityTexture) {
  36103. activeTextures.push(this._opacityTexture);
  36104. }
  36105. if (this._reflectionTexture) {
  36106. activeTextures.push(this._reflectionTexture);
  36107. }
  36108. if (this._emissiveTexture) {
  36109. activeTextures.push(this._emissiveTexture);
  36110. }
  36111. if (this._specularTexture) {
  36112. activeTextures.push(this._specularTexture);
  36113. }
  36114. if (this._bumpTexture) {
  36115. activeTextures.push(this._bumpTexture);
  36116. }
  36117. if (this._lightmapTexture) {
  36118. activeTextures.push(this._lightmapTexture);
  36119. }
  36120. if (this._refractionTexture) {
  36121. activeTextures.push(this._refractionTexture);
  36122. }
  36123. return activeTextures;
  36124. };
  36125. StandardMaterial.prototype.hasTexture = function (texture) {
  36126. if (_super.prototype.hasTexture.call(this, texture)) {
  36127. return true;
  36128. }
  36129. if (this._diffuseTexture === texture) {
  36130. return true;
  36131. }
  36132. if (this._ambientTexture === texture) {
  36133. return true;
  36134. }
  36135. if (this._opacityTexture === texture) {
  36136. return true;
  36137. }
  36138. if (this._reflectionTexture === texture) {
  36139. return true;
  36140. }
  36141. if (this._emissiveTexture === texture) {
  36142. return true;
  36143. }
  36144. if (this._specularTexture === texture) {
  36145. return true;
  36146. }
  36147. if (this._bumpTexture === texture) {
  36148. return true;
  36149. }
  36150. if (this._lightmapTexture === texture) {
  36151. return true;
  36152. }
  36153. if (this._refractionTexture === texture) {
  36154. return true;
  36155. }
  36156. return false;
  36157. };
  36158. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36159. if (forceDisposeTextures) {
  36160. if (this._diffuseTexture) {
  36161. this._diffuseTexture.dispose();
  36162. }
  36163. if (this._ambientTexture) {
  36164. this._ambientTexture.dispose();
  36165. }
  36166. if (this._opacityTexture) {
  36167. this._opacityTexture.dispose();
  36168. }
  36169. if (this._reflectionTexture) {
  36170. this._reflectionTexture.dispose();
  36171. }
  36172. if (this._emissiveTexture) {
  36173. this._emissiveTexture.dispose();
  36174. }
  36175. if (this._specularTexture) {
  36176. this._specularTexture.dispose();
  36177. }
  36178. if (this._bumpTexture) {
  36179. this._bumpTexture.dispose();
  36180. }
  36181. if (this._lightmapTexture) {
  36182. this._lightmapTexture.dispose();
  36183. }
  36184. if (this._refractionTexture) {
  36185. this._refractionTexture.dispose();
  36186. }
  36187. }
  36188. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36189. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36190. }
  36191. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36192. };
  36193. StandardMaterial.prototype.clone = function (name) {
  36194. var _this = this;
  36195. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36196. result.name = name;
  36197. result.id = name;
  36198. return result;
  36199. };
  36200. StandardMaterial.prototype.serialize = function () {
  36201. return BABYLON.SerializationHelper.Serialize(this);
  36202. };
  36203. // Statics
  36204. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36205. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36206. };
  36207. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36208. get: function () {
  36209. return StandardMaterial._DiffuseTextureEnabled;
  36210. },
  36211. set: function (value) {
  36212. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36213. return;
  36214. }
  36215. StandardMaterial._DiffuseTextureEnabled = value;
  36216. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36217. },
  36218. enumerable: true,
  36219. configurable: true
  36220. });
  36221. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36222. get: function () {
  36223. return StandardMaterial._AmbientTextureEnabled;
  36224. },
  36225. set: function (value) {
  36226. if (StandardMaterial._AmbientTextureEnabled === value) {
  36227. return;
  36228. }
  36229. StandardMaterial._AmbientTextureEnabled = value;
  36230. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36231. },
  36232. enumerable: true,
  36233. configurable: true
  36234. });
  36235. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36236. get: function () {
  36237. return StandardMaterial._OpacityTextureEnabled;
  36238. },
  36239. set: function (value) {
  36240. if (StandardMaterial._OpacityTextureEnabled === value) {
  36241. return;
  36242. }
  36243. StandardMaterial._OpacityTextureEnabled = value;
  36244. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36245. },
  36246. enumerable: true,
  36247. configurable: true
  36248. });
  36249. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36250. get: function () {
  36251. return StandardMaterial._ReflectionTextureEnabled;
  36252. },
  36253. set: function (value) {
  36254. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36255. return;
  36256. }
  36257. StandardMaterial._ReflectionTextureEnabled = value;
  36258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36259. },
  36260. enumerable: true,
  36261. configurable: true
  36262. });
  36263. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36264. get: function () {
  36265. return StandardMaterial._EmissiveTextureEnabled;
  36266. },
  36267. set: function (value) {
  36268. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36269. return;
  36270. }
  36271. StandardMaterial._EmissiveTextureEnabled = value;
  36272. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36273. },
  36274. enumerable: true,
  36275. configurable: true
  36276. });
  36277. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36278. get: function () {
  36279. return StandardMaterial._SpecularTextureEnabled;
  36280. },
  36281. set: function (value) {
  36282. if (StandardMaterial._SpecularTextureEnabled === value) {
  36283. return;
  36284. }
  36285. StandardMaterial._SpecularTextureEnabled = value;
  36286. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36292. get: function () {
  36293. return StandardMaterial._BumpTextureEnabled;
  36294. },
  36295. set: function (value) {
  36296. if (StandardMaterial._BumpTextureEnabled === value) {
  36297. return;
  36298. }
  36299. StandardMaterial._BumpTextureEnabled = value;
  36300. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36301. },
  36302. enumerable: true,
  36303. configurable: true
  36304. });
  36305. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36306. get: function () {
  36307. return StandardMaterial._LightmapTextureEnabled;
  36308. },
  36309. set: function (value) {
  36310. if (StandardMaterial._LightmapTextureEnabled === value) {
  36311. return;
  36312. }
  36313. StandardMaterial._LightmapTextureEnabled = value;
  36314. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36320. get: function () {
  36321. return StandardMaterial._RefractionTextureEnabled;
  36322. },
  36323. set: function (value) {
  36324. if (StandardMaterial._RefractionTextureEnabled === value) {
  36325. return;
  36326. }
  36327. StandardMaterial._RefractionTextureEnabled = value;
  36328. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36329. },
  36330. enumerable: true,
  36331. configurable: true
  36332. });
  36333. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36334. get: function () {
  36335. return StandardMaterial._ColorGradingTextureEnabled;
  36336. },
  36337. set: function (value) {
  36338. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36339. return;
  36340. }
  36341. StandardMaterial._ColorGradingTextureEnabled = value;
  36342. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36343. },
  36344. enumerable: true,
  36345. configurable: true
  36346. });
  36347. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36348. get: function () {
  36349. return StandardMaterial._FresnelEnabled;
  36350. },
  36351. set: function (value) {
  36352. if (StandardMaterial._FresnelEnabled === value) {
  36353. return;
  36354. }
  36355. StandardMaterial._FresnelEnabled = value;
  36356. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36357. },
  36358. enumerable: true,
  36359. configurable: true
  36360. });
  36361. // Flags used to enable or disable a type of texture for all Standard Materials
  36362. StandardMaterial._DiffuseTextureEnabled = true;
  36363. StandardMaterial._AmbientTextureEnabled = true;
  36364. StandardMaterial._OpacityTextureEnabled = true;
  36365. StandardMaterial._ReflectionTextureEnabled = true;
  36366. StandardMaterial._EmissiveTextureEnabled = true;
  36367. StandardMaterial._SpecularTextureEnabled = true;
  36368. StandardMaterial._BumpTextureEnabled = true;
  36369. StandardMaterial._LightmapTextureEnabled = true;
  36370. StandardMaterial._RefractionTextureEnabled = true;
  36371. StandardMaterial._ColorGradingTextureEnabled = true;
  36372. StandardMaterial._FresnelEnabled = true;
  36373. __decorate([
  36374. BABYLON.serializeAsTexture("diffuseTexture")
  36375. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36376. __decorate([
  36377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36378. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36379. __decorate([
  36380. BABYLON.serializeAsTexture("ambientTexture")
  36381. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36382. __decorate([
  36383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36384. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36385. __decorate([
  36386. BABYLON.serializeAsTexture("opacityTexture")
  36387. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36388. __decorate([
  36389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36390. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36391. __decorate([
  36392. BABYLON.serializeAsTexture("reflectionTexture")
  36393. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36394. __decorate([
  36395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36396. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36397. __decorate([
  36398. BABYLON.serializeAsTexture("emissiveTexture")
  36399. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36400. __decorate([
  36401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36402. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36403. __decorate([
  36404. BABYLON.serializeAsTexture("specularTexture")
  36405. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36406. __decorate([
  36407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36408. ], StandardMaterial.prototype, "specularTexture", void 0);
  36409. __decorate([
  36410. BABYLON.serializeAsTexture("bumpTexture")
  36411. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36412. __decorate([
  36413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36414. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36415. __decorate([
  36416. BABYLON.serializeAsTexture("lightmapTexture")
  36417. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36418. __decorate([
  36419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36420. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36421. __decorate([
  36422. BABYLON.serializeAsTexture("refractionTexture")
  36423. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36424. __decorate([
  36425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36426. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36427. __decorate([
  36428. BABYLON.serializeAsColor3("ambient")
  36429. ], StandardMaterial.prototype, "ambientColor", void 0);
  36430. __decorate([
  36431. BABYLON.serializeAsColor3("diffuse")
  36432. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36433. __decorate([
  36434. BABYLON.serializeAsColor3("specular")
  36435. ], StandardMaterial.prototype, "specularColor", void 0);
  36436. __decorate([
  36437. BABYLON.serializeAsColor3("emissive")
  36438. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36439. __decorate([
  36440. BABYLON.serialize()
  36441. ], StandardMaterial.prototype, "specularPower", void 0);
  36442. __decorate([
  36443. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36444. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36445. __decorate([
  36446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36447. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36448. __decorate([
  36449. BABYLON.serialize("useEmissiveAsIllumination")
  36450. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36451. __decorate([
  36452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36453. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36454. __decorate([
  36455. BABYLON.serialize("linkEmissiveWithDiffuse")
  36456. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36457. __decorate([
  36458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36459. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36460. __decorate([
  36461. BABYLON.serialize("useSpecularOverAlpha")
  36462. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36463. __decorate([
  36464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36465. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36466. __decorate([
  36467. BABYLON.serialize("useReflectionOverAlpha")
  36468. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36469. __decorate([
  36470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36471. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36472. __decorate([
  36473. BABYLON.serialize("disableLighting")
  36474. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36475. __decorate([
  36476. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36477. ], StandardMaterial.prototype, "disableLighting", void 0);
  36478. __decorate([
  36479. BABYLON.serialize("useParallax")
  36480. ], StandardMaterial.prototype, "_useParallax", void 0);
  36481. __decorate([
  36482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36483. ], StandardMaterial.prototype, "useParallax", void 0);
  36484. __decorate([
  36485. BABYLON.serialize("useParallaxOcclusion")
  36486. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36487. __decorate([
  36488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36489. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36490. __decorate([
  36491. BABYLON.serialize()
  36492. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36493. __decorate([
  36494. BABYLON.serialize("roughness")
  36495. ], StandardMaterial.prototype, "_roughness", void 0);
  36496. __decorate([
  36497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36498. ], StandardMaterial.prototype, "roughness", void 0);
  36499. __decorate([
  36500. BABYLON.serialize()
  36501. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36502. __decorate([
  36503. BABYLON.serialize()
  36504. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36505. __decorate([
  36506. BABYLON.serialize("useLightmapAsShadowmap")
  36507. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36508. __decorate([
  36509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36510. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36511. __decorate([
  36512. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36513. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36514. __decorate([
  36515. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36516. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36517. __decorate([
  36518. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36519. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36520. __decorate([
  36521. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36522. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36523. __decorate([
  36524. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36525. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36526. __decorate([
  36527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36528. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36529. __decorate([
  36530. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36531. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36532. __decorate([
  36533. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36534. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36535. __decorate([
  36536. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36537. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36538. __decorate([
  36539. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36540. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36541. __decorate([
  36542. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36543. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36544. __decorate([
  36545. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36546. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36547. __decorate([
  36548. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36549. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36550. __decorate([
  36551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36552. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36553. __decorate([
  36554. BABYLON.serialize("maxSimultaneousLights")
  36555. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36556. __decorate([
  36557. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36558. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36559. __decorate([
  36560. BABYLON.serialize("invertNormalMapX")
  36561. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36562. __decorate([
  36563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36564. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36565. __decorate([
  36566. BABYLON.serialize("invertNormalMapY")
  36567. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36568. __decorate([
  36569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36570. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36571. __decorate([
  36572. BABYLON.serialize("twoSidedLighting")
  36573. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36574. __decorate([
  36575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36576. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36577. __decorate([
  36578. BABYLON.serialize()
  36579. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36580. return StandardMaterial;
  36581. }(BABYLON.PushMaterial));
  36582. BABYLON.StandardMaterial = StandardMaterial;
  36583. })(BABYLON || (BABYLON = {}));
  36584. //# sourceMappingURL=babylon.standardMaterial.js.map
  36585. var BABYLON;
  36586. (function (BABYLON) {
  36587. var PBRMaterialDefines = /** @class */ (function (_super) {
  36588. __extends(PBRMaterialDefines, _super);
  36589. function PBRMaterialDefines() {
  36590. var _this = _super.call(this) || this;
  36591. _this.PBR = true;
  36592. _this.MAINUV1 = false;
  36593. _this.MAINUV2 = false;
  36594. _this.UV1 = false;
  36595. _this.UV2 = false;
  36596. _this.ALBEDO = false;
  36597. _this.ALBEDODIRECTUV = 0;
  36598. _this.VERTEXCOLOR = false;
  36599. _this.AMBIENT = false;
  36600. _this.AMBIENTDIRECTUV = 0;
  36601. _this.AMBIENTINGRAYSCALE = false;
  36602. _this.OPACITY = false;
  36603. _this.VERTEXALPHA = false;
  36604. _this.OPACITYDIRECTUV = 0;
  36605. _this.OPACITYRGB = false;
  36606. _this.ALPHATEST = false;
  36607. _this.DEPTHPREPASS = false;
  36608. _this.ALPHABLEND = false;
  36609. _this.ALPHAFROMALBEDO = false;
  36610. _this.ALPHATESTVALUE = 0.5;
  36611. _this.SPECULAROVERALPHA = false;
  36612. _this.RADIANCEOVERALPHA = false;
  36613. _this.ALPHAFRESNEL = false;
  36614. _this.LINEARALPHAFRESNEL = false;
  36615. _this.PREMULTIPLYALPHA = false;
  36616. _this.EMISSIVE = false;
  36617. _this.EMISSIVEDIRECTUV = 0;
  36618. _this.REFLECTIVITY = false;
  36619. _this.REFLECTIVITYDIRECTUV = 0;
  36620. _this.SPECULARTERM = false;
  36621. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36622. _this.MICROSURFACEAUTOMATIC = false;
  36623. _this.LODBASEDMICROSFURACE = false;
  36624. _this.MICROSURFACEMAP = false;
  36625. _this.MICROSURFACEMAPDIRECTUV = 0;
  36626. _this.METALLICWORKFLOW = false;
  36627. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36628. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36629. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36630. _this.AOSTOREINMETALMAPRED = false;
  36631. _this.ENVIRONMENTBRDF = false;
  36632. _this.NORMAL = false;
  36633. _this.TANGENT = false;
  36634. _this.BUMP = false;
  36635. _this.BUMPDIRECTUV = 0;
  36636. _this.PARALLAX = false;
  36637. _this.PARALLAXOCCLUSION = false;
  36638. _this.NORMALXYSCALE = true;
  36639. _this.LIGHTMAP = false;
  36640. _this.LIGHTMAPDIRECTUV = 0;
  36641. _this.USELIGHTMAPASSHADOWMAP = false;
  36642. _this.REFLECTION = false;
  36643. _this.REFLECTIONMAP_3D = false;
  36644. _this.REFLECTIONMAP_SPHERICAL = false;
  36645. _this.REFLECTIONMAP_PLANAR = false;
  36646. _this.REFLECTIONMAP_CUBIC = false;
  36647. _this.REFLECTIONMAP_PROJECTION = false;
  36648. _this.REFLECTIONMAP_SKYBOX = false;
  36649. _this.REFLECTIONMAP_EXPLICIT = false;
  36650. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36651. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36652. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36653. _this.INVERTCUBICMAP = false;
  36654. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36655. _this.USESPHERICALINVERTEX = false;
  36656. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36657. _this.LODINREFLECTIONALPHA = false;
  36658. _this.GAMMAREFLECTION = false;
  36659. _this.RADIANCEOCCLUSION = false;
  36660. _this.HORIZONOCCLUSION = false;
  36661. _this.REFRACTION = false;
  36662. _this.REFRACTIONMAP_3D = false;
  36663. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36664. _this.LODINREFRACTIONALPHA = false;
  36665. _this.GAMMAREFRACTION = false;
  36666. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36667. _this.INSTANCES = false;
  36668. _this.NUM_BONE_INFLUENCERS = 0;
  36669. _this.BonesPerMesh = 0;
  36670. _this.NONUNIFORMSCALING = false;
  36671. _this.MORPHTARGETS = false;
  36672. _this.MORPHTARGETS_NORMAL = false;
  36673. _this.MORPHTARGETS_TANGENT = false;
  36674. _this.NUM_MORPH_INFLUENCERS = 0;
  36675. _this.IMAGEPROCESSING = false;
  36676. _this.VIGNETTE = false;
  36677. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36678. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36679. _this.TONEMAPPING = false;
  36680. _this.CONTRAST = false;
  36681. _this.COLORCURVES = false;
  36682. _this.COLORGRADING = false;
  36683. _this.COLORGRADING3D = false;
  36684. _this.SAMPLER3DGREENDEPTH = false;
  36685. _this.SAMPLER3DBGRMAP = false;
  36686. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36687. _this.EXPOSURE = false;
  36688. _this.USEPHYSICALLIGHTFALLOFF = false;
  36689. _this.TWOSIDEDLIGHTING = false;
  36690. _this.SHADOWFLOAT = false;
  36691. _this.CLIPPLANE = false;
  36692. _this.POINTSIZE = false;
  36693. _this.FOG = false;
  36694. _this.LOGARITHMICDEPTH = false;
  36695. _this.FORCENORMALFORWARD = false;
  36696. _this.rebuild();
  36697. return _this;
  36698. }
  36699. PBRMaterialDefines.prototype.reset = function () {
  36700. _super.prototype.reset.call(this);
  36701. this.ALPHATESTVALUE = 0.5;
  36702. this.PBR = true;
  36703. };
  36704. return PBRMaterialDefines;
  36705. }(BABYLON.MaterialDefines));
  36706. /**
  36707. * The Physically based material base class of BJS.
  36708. *
  36709. * This offers the main features of a standard PBR material.
  36710. * For more information, please refer to the documentation :
  36711. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36712. */
  36713. var PBRBaseMaterial = /** @class */ (function (_super) {
  36714. __extends(PBRBaseMaterial, _super);
  36715. /**
  36716. * Instantiates a new PBRMaterial instance.
  36717. *
  36718. * @param name The material name
  36719. * @param scene The scene the material will be use in.
  36720. */
  36721. function PBRBaseMaterial(name, scene) {
  36722. var _this = _super.call(this, name, scene) || this;
  36723. /**
  36724. * Intensity of the direct lights e.g. the four lights available in your scene.
  36725. * This impacts both the direct diffuse and specular highlights.
  36726. */
  36727. _this._directIntensity = 1.0;
  36728. /**
  36729. * Intensity of the emissive part of the material.
  36730. * This helps controlling the emissive effect without modifying the emissive color.
  36731. */
  36732. _this._emissiveIntensity = 1.0;
  36733. /**
  36734. * Intensity of the environment e.g. how much the environment will light the object
  36735. * either through harmonics for rough material or through the refelction for shiny ones.
  36736. */
  36737. _this._environmentIntensity = 1.0;
  36738. /**
  36739. * This is a special control allowing the reduction of the specular highlights coming from the
  36740. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36741. */
  36742. _this._specularIntensity = 1.0;
  36743. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36744. /**
  36745. * Debug Control allowing disabling the bump map on this material.
  36746. */
  36747. _this._disableBumpMap = false;
  36748. /**
  36749. * AKA Occlusion Texture Intensity in other nomenclature.
  36750. */
  36751. _this._ambientTextureStrength = 1.0;
  36752. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36753. /**
  36754. * AKA Diffuse Color in other nomenclature.
  36755. */
  36756. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36757. /**
  36758. * AKA Specular Color in other nomenclature.
  36759. */
  36760. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36761. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36762. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36763. /**
  36764. * AKA Glossiness in other nomenclature.
  36765. */
  36766. _this._microSurface = 0.9;
  36767. /**
  36768. * source material index of refraction (IOR)' / 'destination material IOR.
  36769. */
  36770. _this._indexOfRefraction = 0.66;
  36771. /**
  36772. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36773. */
  36774. _this._invertRefractionY = false;
  36775. /**
  36776. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36777. * Materials half opaque for instance using refraction could benefit from this control.
  36778. */
  36779. _this._linkRefractionWithTransparency = false;
  36780. _this._useLightmapAsShadowmap = false;
  36781. /**
  36782. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36783. * makes the reflect vector face the model (under horizon).
  36784. */
  36785. _this._useHorizonOcclusion = true;
  36786. /**
  36787. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36788. * too much the area relying on ambient texture to define their ambient occlusion.
  36789. */
  36790. _this._useRadianceOcclusion = true;
  36791. /**
  36792. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36793. */
  36794. _this._useAlphaFromAlbedoTexture = false;
  36795. /**
  36796. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36797. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36798. */
  36799. _this._useSpecularOverAlpha = true;
  36800. /**
  36801. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36802. */
  36803. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36804. /**
  36805. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36806. */
  36807. _this._useRoughnessFromMetallicTextureAlpha = true;
  36808. /**
  36809. * Specifies if the metallic texture contains the roughness information in its green channel.
  36810. */
  36811. _this._useRoughnessFromMetallicTextureGreen = false;
  36812. /**
  36813. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36814. */
  36815. _this._useMetallnessFromMetallicTextureBlue = false;
  36816. /**
  36817. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36818. */
  36819. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36820. /**
  36821. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36822. */
  36823. _this._useAmbientInGrayScale = false;
  36824. /**
  36825. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36826. * The material will try to infer what glossiness each pixel should be.
  36827. */
  36828. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36829. /**
  36830. * BJS is using an harcoded light falloff based on a manually sets up range.
  36831. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36832. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36833. */
  36834. _this._usePhysicalLightFalloff = true;
  36835. /**
  36836. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36837. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36838. */
  36839. _this._useRadianceOverAlpha = true;
  36840. /**
  36841. * Allows using the bump map in parallax mode.
  36842. */
  36843. _this._useParallax = false;
  36844. /**
  36845. * Allows using the bump map in parallax occlusion mode.
  36846. */
  36847. _this._useParallaxOcclusion = false;
  36848. /**
  36849. * Controls the scale bias of the parallax mode.
  36850. */
  36851. _this._parallaxScaleBias = 0.05;
  36852. /**
  36853. * If sets to true, disables all the lights affecting the material.
  36854. */
  36855. _this._disableLighting = false;
  36856. /**
  36857. * Number of Simultaneous lights allowed on the material.
  36858. */
  36859. _this._maxSimultaneousLights = 4;
  36860. /**
  36861. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36862. */
  36863. _this._invertNormalMapX = false;
  36864. /**
  36865. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36866. */
  36867. _this._invertNormalMapY = false;
  36868. /**
  36869. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36870. */
  36871. _this._twoSidedLighting = false;
  36872. /**
  36873. * Defines the alpha limits in alpha test mode.
  36874. */
  36875. _this._alphaCutOff = 0.4;
  36876. /**
  36877. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36878. */
  36879. _this._forceAlphaTest = false;
  36880. /**
  36881. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36882. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36883. */
  36884. _this._useAlphaFresnel = false;
  36885. /**
  36886. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36887. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36888. */
  36889. _this._useLinearAlphaFresnel = false;
  36890. /**
  36891. * The transparency mode of the material.
  36892. */
  36893. _this._transparencyMode = null;
  36894. /**
  36895. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36896. * from cos thetav and roughness:
  36897. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36898. */
  36899. _this._environmentBRDFTexture = null;
  36900. /**
  36901. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36902. */
  36903. _this._forceIrradianceInFragment = false;
  36904. /**
  36905. * Force normal to face away from face.
  36906. */
  36907. _this._forceNormalForward = false;
  36908. /**
  36909. * Force metallic workflow.
  36910. */
  36911. _this._forceMetallicWorkflow = false;
  36912. _this._renderTargets = new BABYLON.SmartArray(16);
  36913. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36914. // Setup the default processing configuration to the scene.
  36915. _this._attachImageProcessingConfiguration(null);
  36916. _this.getRenderTargetTextures = function () {
  36917. _this._renderTargets.reset();
  36918. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36919. _this._renderTargets.push(_this._reflectionTexture);
  36920. }
  36921. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36922. _this._renderTargets.push(_this._refractionTexture);
  36923. }
  36924. return _this._renderTargets;
  36925. };
  36926. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36927. return _this;
  36928. }
  36929. /**
  36930. * Attaches a new image processing configuration to the PBR Material.
  36931. * @param configuration
  36932. */
  36933. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36934. var _this = this;
  36935. if (configuration === this._imageProcessingConfiguration) {
  36936. return;
  36937. }
  36938. // Detaches observer.
  36939. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36940. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36941. }
  36942. // Pick the scene configuration if needed.
  36943. if (!configuration) {
  36944. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36945. }
  36946. else {
  36947. this._imageProcessingConfiguration = configuration;
  36948. }
  36949. // Attaches observer.
  36950. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36951. _this._markAllSubMeshesAsImageProcessingDirty();
  36952. });
  36953. };
  36954. PBRBaseMaterial.prototype.getClassName = function () {
  36955. return "PBRBaseMaterial";
  36956. };
  36957. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36958. get: function () {
  36959. return this._useLogarithmicDepth;
  36960. },
  36961. set: function (value) {
  36962. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36963. },
  36964. enumerable: true,
  36965. configurable: true
  36966. });
  36967. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36968. /**
  36969. * Gets the current transparency mode.
  36970. */
  36971. get: function () {
  36972. return this._transparencyMode;
  36973. },
  36974. /**
  36975. * Sets the transparency mode of the material.
  36976. */
  36977. set: function (value) {
  36978. if (this._transparencyMode === value) {
  36979. return;
  36980. }
  36981. this._transparencyMode = value;
  36982. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36983. this._markAllSubMeshesAsTexturesDirty();
  36984. },
  36985. enumerable: true,
  36986. configurable: true
  36987. });
  36988. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36989. /**
  36990. * Returns true if alpha blending should be disabled.
  36991. */
  36992. get: function () {
  36993. return (this._linkRefractionWithTransparency ||
  36994. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36995. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36996. },
  36997. enumerable: true,
  36998. configurable: true
  36999. });
  37000. /**
  37001. * Specifies whether or not this material should be rendered in alpha blend mode.
  37002. */
  37003. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37004. if (this._disableAlphaBlending) {
  37005. return false;
  37006. }
  37007. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37008. };
  37009. /**
  37010. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  37011. */
  37012. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  37013. if (this._disableAlphaBlending) {
  37014. return false;
  37015. }
  37016. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  37017. };
  37018. /**
  37019. * Specifies whether or not this material should be rendered in alpha test mode.
  37020. */
  37021. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37022. if (this._forceAlphaTest) {
  37023. return true;
  37024. }
  37025. if (this._linkRefractionWithTransparency) {
  37026. return false;
  37027. }
  37028. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37029. };
  37030. /**
  37031. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  37032. */
  37033. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37034. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37035. };
  37036. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37037. return this._albedoTexture;
  37038. };
  37039. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37040. var _this = this;
  37041. if (subMesh.effect && this.isFrozen) {
  37042. if (this._wasPreviouslyReady) {
  37043. return true;
  37044. }
  37045. }
  37046. if (!subMesh._materialDefines) {
  37047. subMesh._materialDefines = new PBRMaterialDefines();
  37048. }
  37049. var scene = this.getScene();
  37050. var defines = subMesh._materialDefines;
  37051. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37052. if (defines._renderId === scene.getRenderId()) {
  37053. return true;
  37054. }
  37055. }
  37056. var engine = scene.getEngine();
  37057. // Lights
  37058. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37059. defines._needNormals = true;
  37060. // Textures
  37061. if (defines._areTexturesDirty) {
  37062. defines._needUVs = false;
  37063. if (scene.texturesEnabled) {
  37064. if (scene.getEngine().getCaps().textureLOD) {
  37065. defines.LODBASEDMICROSFURACE = true;
  37066. }
  37067. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37068. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37069. return false;
  37070. }
  37071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37072. }
  37073. else {
  37074. defines.ALBEDO = false;
  37075. }
  37076. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37077. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37078. return false;
  37079. }
  37080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37081. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37082. }
  37083. else {
  37084. defines.AMBIENT = false;
  37085. }
  37086. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37087. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37088. return false;
  37089. }
  37090. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37091. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37092. }
  37093. else {
  37094. defines.OPACITY = false;
  37095. }
  37096. var reflectionTexture = this._getReflectionTexture();
  37097. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37098. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37099. return false;
  37100. }
  37101. defines.REFLECTION = true;
  37102. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37103. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37104. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37105. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37106. defines.INVERTCUBICMAP = true;
  37107. }
  37108. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37109. switch (reflectionTexture.coordinatesMode) {
  37110. case BABYLON.Texture.CUBIC_MODE:
  37111. case BABYLON.Texture.INVCUBIC_MODE:
  37112. defines.REFLECTIONMAP_CUBIC = true;
  37113. break;
  37114. case BABYLON.Texture.EXPLICIT_MODE:
  37115. defines.REFLECTIONMAP_EXPLICIT = true;
  37116. break;
  37117. case BABYLON.Texture.PLANAR_MODE:
  37118. defines.REFLECTIONMAP_PLANAR = true;
  37119. break;
  37120. case BABYLON.Texture.PROJECTION_MODE:
  37121. defines.REFLECTIONMAP_PROJECTION = true;
  37122. break;
  37123. case BABYLON.Texture.SKYBOX_MODE:
  37124. defines.REFLECTIONMAP_SKYBOX = true;
  37125. break;
  37126. case BABYLON.Texture.SPHERICAL_MODE:
  37127. defines.REFLECTIONMAP_SPHERICAL = true;
  37128. break;
  37129. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37130. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37131. break;
  37132. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37133. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37134. break;
  37135. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37136. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37137. break;
  37138. }
  37139. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37140. if (reflectionTexture.sphericalPolynomial) {
  37141. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37142. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37143. defines.USESPHERICALINVERTEX = false;
  37144. }
  37145. else {
  37146. defines.USESPHERICALINVERTEX = true;
  37147. }
  37148. }
  37149. }
  37150. }
  37151. else {
  37152. defines.REFLECTION = false;
  37153. defines.REFLECTIONMAP_3D = false;
  37154. defines.REFLECTIONMAP_SPHERICAL = false;
  37155. defines.REFLECTIONMAP_PLANAR = false;
  37156. defines.REFLECTIONMAP_CUBIC = false;
  37157. defines.REFLECTIONMAP_PROJECTION = false;
  37158. defines.REFLECTIONMAP_SKYBOX = false;
  37159. defines.REFLECTIONMAP_EXPLICIT = false;
  37160. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37161. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37162. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37163. defines.INVERTCUBICMAP = false;
  37164. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37165. defines.USESPHERICALINVERTEX = false;
  37166. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37167. defines.LODINREFLECTIONALPHA = false;
  37168. defines.GAMMAREFLECTION = false;
  37169. }
  37170. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37171. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37172. return false;
  37173. }
  37174. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37175. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37176. }
  37177. else {
  37178. defines.LIGHTMAP = false;
  37179. }
  37180. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37181. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37182. return false;
  37183. }
  37184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37185. }
  37186. else {
  37187. defines.EMISSIVE = false;
  37188. }
  37189. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37190. if (this._metallicTexture) {
  37191. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37192. return false;
  37193. }
  37194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37195. defines.METALLICWORKFLOW = true;
  37196. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37197. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37198. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37199. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37200. }
  37201. else if (this._reflectivityTexture) {
  37202. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37203. return false;
  37204. }
  37205. defines.METALLICWORKFLOW = false;
  37206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37207. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37208. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37209. }
  37210. else {
  37211. defines.METALLICWORKFLOW = false;
  37212. defines.REFLECTIVITY = false;
  37213. }
  37214. if (this._microSurfaceTexture) {
  37215. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37216. return false;
  37217. }
  37218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37219. }
  37220. else {
  37221. defines.MICROSURFACEMAP = false;
  37222. }
  37223. }
  37224. else {
  37225. defines.REFLECTIVITY = false;
  37226. defines.MICROSURFACEMAP = false;
  37227. }
  37228. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37229. // Bump texure can not be none blocking.
  37230. if (!this._bumpTexture.isReady()) {
  37231. return false;
  37232. }
  37233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37234. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37235. defines.PARALLAX = true;
  37236. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37237. }
  37238. else {
  37239. defines.PARALLAX = false;
  37240. }
  37241. }
  37242. else {
  37243. defines.BUMP = false;
  37244. }
  37245. var refractionTexture = this._getRefractionTexture();
  37246. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37247. if (!refractionTexture.isReadyOrNotBlocking()) {
  37248. return false;
  37249. }
  37250. defines.REFRACTION = true;
  37251. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37252. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37253. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37254. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37255. if (this._linkRefractionWithTransparency) {
  37256. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37257. }
  37258. }
  37259. else {
  37260. defines.REFRACTION = false;
  37261. }
  37262. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37263. // This is blocking.
  37264. if (!this._environmentBRDFTexture.isReady()) {
  37265. return false;
  37266. }
  37267. defines.ENVIRONMENTBRDF = true;
  37268. }
  37269. else {
  37270. defines.ENVIRONMENTBRDF = false;
  37271. }
  37272. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37273. defines.ALPHAFROMALBEDO = true;
  37274. }
  37275. else {
  37276. defines.ALPHAFROMALBEDO = false;
  37277. }
  37278. }
  37279. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37280. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37281. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37282. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37283. defines.METALLICWORKFLOW = true;
  37284. }
  37285. else {
  37286. defines.METALLICWORKFLOW = false;
  37287. }
  37288. if (!this.backFaceCulling && this._twoSidedLighting) {
  37289. defines.TWOSIDEDLIGHTING = true;
  37290. }
  37291. else {
  37292. defines.TWOSIDEDLIGHTING = false;
  37293. }
  37294. defines.ALPHATESTVALUE = this._alphaCutOff;
  37295. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37296. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37297. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37298. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37299. }
  37300. if (defines._areImageProcessingDirty) {
  37301. if (!this._imageProcessingConfiguration.isReady()) {
  37302. return false;
  37303. }
  37304. this._imageProcessingConfiguration.prepareDefines(defines);
  37305. }
  37306. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37307. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37308. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37309. // Misc.
  37310. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37311. // Values that need to be evaluated on every frame
  37312. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  37313. // Attribs
  37314. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37315. var bufferMesh = null;
  37316. if (mesh instanceof BABYLON.InstancedMesh) {
  37317. bufferMesh = mesh.sourceMesh;
  37318. }
  37319. else if (mesh instanceof BABYLON.Mesh) {
  37320. bufferMesh = mesh;
  37321. }
  37322. if (bufferMesh) {
  37323. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37324. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37325. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37326. var normals = normalVertexBuffer.getData();
  37327. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37328. var strideSize = normalVertexBuffer.getStrideSize();
  37329. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37330. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37331. defines.NORMAL = false;
  37332. }
  37333. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37334. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37335. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37336. var tangents = tangentVertexBuffer.getData();
  37337. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37338. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37339. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37340. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37341. defines.TANGENT = false;
  37342. }
  37343. }
  37344. }
  37345. else {
  37346. if (!scene.getEngine().getCaps().standardDerivatives) {
  37347. bufferMesh.createNormals(true);
  37348. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37349. }
  37350. }
  37351. }
  37352. }
  37353. // Get correct effect
  37354. if (defines.isDirty) {
  37355. defines.markAsProcessed();
  37356. scene.resetCachedMaterial();
  37357. // Fallbacks
  37358. var fallbacks = new BABYLON.EffectFallbacks();
  37359. var fallbackRank = 0;
  37360. if (defines.USESPHERICALINVERTEX) {
  37361. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37362. }
  37363. if (defines.FOG) {
  37364. fallbacks.addFallback(fallbackRank, "FOG");
  37365. }
  37366. if (defines.POINTSIZE) {
  37367. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37368. }
  37369. if (defines.LOGARITHMICDEPTH) {
  37370. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37371. }
  37372. if (defines.PARALLAX) {
  37373. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37374. }
  37375. if (defines.PARALLAXOCCLUSION) {
  37376. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37377. }
  37378. if (defines.ENVIRONMENTBRDF) {
  37379. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37380. }
  37381. if (defines.TANGENT) {
  37382. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37383. }
  37384. if (defines.BUMP) {
  37385. fallbacks.addFallback(fallbackRank++, "BUMP");
  37386. }
  37387. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37388. if (defines.SPECULARTERM) {
  37389. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37390. }
  37391. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37392. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37393. }
  37394. if (defines.LIGHTMAP) {
  37395. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37396. }
  37397. if (defines.NORMAL) {
  37398. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37399. }
  37400. if (defines.AMBIENT) {
  37401. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37402. }
  37403. if (defines.EMISSIVE) {
  37404. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37405. }
  37406. if (defines.VERTEXCOLOR) {
  37407. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37408. }
  37409. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37410. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37411. }
  37412. if (defines.MORPHTARGETS) {
  37413. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37414. }
  37415. //Attributes
  37416. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37417. if (defines.NORMAL) {
  37418. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37419. }
  37420. if (defines.TANGENT) {
  37421. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37422. }
  37423. if (defines.UV1) {
  37424. attribs.push(BABYLON.VertexBuffer.UVKind);
  37425. }
  37426. if (defines.UV2) {
  37427. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37428. }
  37429. if (defines.VERTEXCOLOR) {
  37430. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37431. }
  37432. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37433. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37434. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37435. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37436. "vFogInfos", "vFogColor", "pointSize",
  37437. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37438. "mBones",
  37439. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37440. "vLightingIntensity",
  37441. "logarithmicDepthConstant",
  37442. "vSphericalX", "vSphericalY", "vSphericalZ",
  37443. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37444. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37445. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37446. "vTangentSpaceParams"
  37447. ];
  37448. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37449. "bumpSampler", "lightmapSampler", "opacitySampler",
  37450. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37451. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37452. "microSurfaceSampler", "environmentBrdfSampler"];
  37453. var uniformBuffers = ["Material", "Scene"];
  37454. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37455. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37456. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37457. uniformsNames: uniforms,
  37458. uniformBuffersNames: uniformBuffers,
  37459. samplers: samplers,
  37460. defines: defines,
  37461. maxSimultaneousLights: this._maxSimultaneousLights
  37462. });
  37463. var onCompiled = function (effect) {
  37464. if (_this.onCompiled) {
  37465. _this.onCompiled(effect);
  37466. }
  37467. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37468. };
  37469. var join = defines.toString();
  37470. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37471. attributes: attribs,
  37472. uniformsNames: uniforms,
  37473. uniformBuffersNames: uniformBuffers,
  37474. samplers: samplers,
  37475. defines: join,
  37476. fallbacks: fallbacks,
  37477. onCompiled: onCompiled,
  37478. onError: this.onError,
  37479. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37480. }, engine), defines);
  37481. this.buildUniformLayout();
  37482. }
  37483. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37484. return false;
  37485. }
  37486. defines._renderId = scene.getRenderId();
  37487. this._wasPreviouslyReady = true;
  37488. return true;
  37489. };
  37490. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37491. // Order is important !
  37492. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37493. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37494. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37495. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37496. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37497. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37498. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37499. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37500. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37501. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37502. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37503. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37504. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37505. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37506. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37507. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37508. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37509. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37510. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37511. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37512. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37513. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37514. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37515. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37516. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37517. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37518. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37519. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37520. this._uniformBuffer.addUniform("pointSize", 1);
  37521. this._uniformBuffer.create();
  37522. };
  37523. PBRBaseMaterial.prototype.unbind = function () {
  37524. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37525. this._uniformBuffer.setTexture("reflectionSampler", null);
  37526. }
  37527. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37528. this._uniformBuffer.setTexture("refractionSampler", null);
  37529. }
  37530. _super.prototype.unbind.call(this);
  37531. };
  37532. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37533. this._activeEffect.setMatrix("world", world);
  37534. };
  37535. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37536. var scene = this.getScene();
  37537. var defines = subMesh._materialDefines;
  37538. if (!defines) {
  37539. return;
  37540. }
  37541. var effect = subMesh.effect;
  37542. if (!effect) {
  37543. return;
  37544. }
  37545. this._activeEffect = effect;
  37546. // Matrices
  37547. this.bindOnlyWorldMatrix(world);
  37548. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37549. // Bones
  37550. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37551. var reflectionTexture = null;
  37552. if (mustRebind) {
  37553. this._uniformBuffer.bindToEffect(effect, "Material");
  37554. this.bindViewProjection(effect);
  37555. reflectionTexture = this._getReflectionTexture();
  37556. var refractionTexture = this._getRefractionTexture();
  37557. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37558. // Texture uniforms
  37559. if (scene.texturesEnabled) {
  37560. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37561. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37562. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37563. }
  37564. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37565. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37566. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37567. }
  37568. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37569. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37570. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37571. }
  37572. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37573. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37574. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37575. var polynomials = reflectionTexture.sphericalPolynomial;
  37576. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37577. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37578. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37579. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37580. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37581. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37582. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37583. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37584. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37585. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37586. }
  37587. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37588. }
  37589. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37590. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37591. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37592. }
  37593. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37594. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37595. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37596. }
  37597. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37598. if (this._metallicTexture) {
  37599. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37600. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37601. }
  37602. else if (this._reflectivityTexture) {
  37603. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37604. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37605. }
  37606. if (this._microSurfaceTexture) {
  37607. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37608. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37609. }
  37610. }
  37611. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37612. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37613. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37614. if (scene._mirroredCameraPosition) {
  37615. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37616. }
  37617. else {
  37618. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37619. }
  37620. }
  37621. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37622. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37623. var depth = 1.0;
  37624. if (!refractionTexture.isCube) {
  37625. if (refractionTexture.depth) {
  37626. depth = refractionTexture.depth;
  37627. }
  37628. }
  37629. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37630. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37631. }
  37632. }
  37633. // Point size
  37634. if (this.pointsCloud) {
  37635. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37636. }
  37637. // Colors
  37638. if (defines.METALLICWORKFLOW) {
  37639. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37640. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37641. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37642. }
  37643. else {
  37644. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37645. }
  37646. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37647. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37648. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37649. // Misc
  37650. this._lightingInfos.x = this._directIntensity;
  37651. this._lightingInfos.y = this._emissiveIntensity;
  37652. this._lightingInfos.z = this._environmentIntensity;
  37653. this._lightingInfos.w = this._specularIntensity;
  37654. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37655. }
  37656. // Textures
  37657. if (scene.texturesEnabled) {
  37658. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37659. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37660. }
  37661. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37662. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37663. }
  37664. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37665. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37666. }
  37667. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37668. if (defines.LODBASEDMICROSFURACE) {
  37669. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37670. }
  37671. else {
  37672. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37673. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37674. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37675. }
  37676. }
  37677. if (defines.ENVIRONMENTBRDF) {
  37678. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37679. }
  37680. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37681. if (defines.LODBASEDMICROSFURACE) {
  37682. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37683. }
  37684. else {
  37685. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37686. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37687. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37688. }
  37689. }
  37690. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37691. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37692. }
  37693. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37694. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37695. }
  37696. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37697. if (this._metallicTexture) {
  37698. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37699. }
  37700. else if (this._reflectivityTexture) {
  37701. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37702. }
  37703. if (this._microSurfaceTexture) {
  37704. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37705. }
  37706. }
  37707. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37708. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37709. }
  37710. }
  37711. // Clip plane
  37712. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37713. // Colors
  37714. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37715. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37716. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37717. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37718. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37719. }
  37720. if (mustRebind || !this.isFrozen) {
  37721. // Lights
  37722. if (scene.lightsEnabled && !this._disableLighting) {
  37723. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37724. }
  37725. // View
  37726. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37727. this.bindView(effect);
  37728. }
  37729. // Fog
  37730. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37731. // Morph targets
  37732. if (defines.NUM_MORPH_INFLUENCERS) {
  37733. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37734. }
  37735. // image processing
  37736. this._imageProcessingConfiguration.bind(this._activeEffect);
  37737. // Log. depth
  37738. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37739. }
  37740. this._uniformBuffer.update();
  37741. this._afterBind(mesh);
  37742. };
  37743. PBRBaseMaterial.prototype.getAnimatables = function () {
  37744. var results = [];
  37745. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37746. results.push(this._albedoTexture);
  37747. }
  37748. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37749. results.push(this._ambientTexture);
  37750. }
  37751. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37752. results.push(this._opacityTexture);
  37753. }
  37754. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37755. results.push(this._reflectionTexture);
  37756. }
  37757. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37758. results.push(this._emissiveTexture);
  37759. }
  37760. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37761. results.push(this._metallicTexture);
  37762. }
  37763. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37764. results.push(this._reflectivityTexture);
  37765. }
  37766. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37767. results.push(this._bumpTexture);
  37768. }
  37769. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37770. results.push(this._lightmapTexture);
  37771. }
  37772. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37773. results.push(this._refractionTexture);
  37774. }
  37775. return results;
  37776. };
  37777. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37778. if (this._reflectionTexture) {
  37779. return this._reflectionTexture;
  37780. }
  37781. return this.getScene().environmentTexture;
  37782. };
  37783. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37784. if (this._refractionTexture) {
  37785. return this._refractionTexture;
  37786. }
  37787. if (this._linkRefractionWithTransparency) {
  37788. return this.getScene().environmentTexture;
  37789. }
  37790. return null;
  37791. };
  37792. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37793. if (forceDisposeTextures) {
  37794. if (this._albedoTexture) {
  37795. this._albedoTexture.dispose();
  37796. }
  37797. if (this._ambientTexture) {
  37798. this._ambientTexture.dispose();
  37799. }
  37800. if (this._opacityTexture) {
  37801. this._opacityTexture.dispose();
  37802. }
  37803. if (this._reflectionTexture) {
  37804. this._reflectionTexture.dispose();
  37805. }
  37806. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37807. this._environmentBRDFTexture.dispose();
  37808. }
  37809. if (this._emissiveTexture) {
  37810. this._emissiveTexture.dispose();
  37811. }
  37812. if (this._metallicTexture) {
  37813. this._metallicTexture.dispose();
  37814. }
  37815. if (this._reflectivityTexture) {
  37816. this._reflectivityTexture.dispose();
  37817. }
  37818. if (this._bumpTexture) {
  37819. this._bumpTexture.dispose();
  37820. }
  37821. if (this._lightmapTexture) {
  37822. this._lightmapTexture.dispose();
  37823. }
  37824. if (this._refractionTexture) {
  37825. this._refractionTexture.dispose();
  37826. }
  37827. }
  37828. this._renderTargets.dispose();
  37829. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37830. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37831. }
  37832. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37833. };
  37834. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37835. __decorate([
  37836. BABYLON.serializeAsImageProcessingConfiguration()
  37837. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37838. __decorate([
  37839. BABYLON.serialize()
  37840. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37841. __decorate([
  37842. BABYLON.serialize()
  37843. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37844. return PBRBaseMaterial;
  37845. }(BABYLON.PushMaterial));
  37846. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37847. })(BABYLON || (BABYLON = {}));
  37848. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37849. var BABYLON;
  37850. (function (BABYLON) {
  37851. /**
  37852. * The Physically based simple base material of BJS.
  37853. *
  37854. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37855. * It is used as the base class for both the specGloss and metalRough conventions.
  37856. */
  37857. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37858. __extends(PBRBaseSimpleMaterial, _super);
  37859. /**
  37860. * Instantiates a new PBRMaterial instance.
  37861. *
  37862. * @param name The material name
  37863. * @param scene The scene the material will be use in.
  37864. */
  37865. function PBRBaseSimpleMaterial(name, scene) {
  37866. var _this = _super.call(this, name, scene) || this;
  37867. /**
  37868. * Number of Simultaneous lights allowed on the material.
  37869. */
  37870. _this.maxSimultaneousLights = 4;
  37871. /**
  37872. * If sets to true, disables all the lights affecting the material.
  37873. */
  37874. _this.disableLighting = false;
  37875. /**
  37876. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37877. */
  37878. _this.invertNormalMapX = false;
  37879. /**
  37880. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37881. */
  37882. _this.invertNormalMapY = false;
  37883. /**
  37884. * Emissivie color used to self-illuminate the model.
  37885. */
  37886. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37887. /**
  37888. * Occlusion Channel Strenght.
  37889. */
  37890. _this.occlusionStrength = 1.0;
  37891. _this.useLightmapAsShadowmap = false;
  37892. _this._useAlphaFromAlbedoTexture = true;
  37893. _this._useAmbientInGrayScale = true;
  37894. return _this;
  37895. }
  37896. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37897. /**
  37898. * Gets the current double sided mode.
  37899. */
  37900. get: function () {
  37901. return this._twoSidedLighting;
  37902. },
  37903. /**
  37904. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37905. */
  37906. set: function (value) {
  37907. if (this._twoSidedLighting === value) {
  37908. return;
  37909. }
  37910. this._twoSidedLighting = value;
  37911. this.backFaceCulling = !value;
  37912. this._markAllSubMeshesAsTexturesDirty();
  37913. },
  37914. enumerable: true,
  37915. configurable: true
  37916. });
  37917. /**
  37918. * Return the active textures of the material.
  37919. */
  37920. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37921. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37922. if (this.environmentTexture) {
  37923. activeTextures.push(this.environmentTexture);
  37924. }
  37925. if (this.normalTexture) {
  37926. activeTextures.push(this.normalTexture);
  37927. }
  37928. if (this.emissiveTexture) {
  37929. activeTextures.push(this.emissiveTexture);
  37930. }
  37931. if (this.occlusionTexture) {
  37932. activeTextures.push(this.occlusionTexture);
  37933. }
  37934. if (this.lightmapTexture) {
  37935. activeTextures.push(this.lightmapTexture);
  37936. }
  37937. return activeTextures;
  37938. };
  37939. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37940. if (_super.prototype.hasTexture.call(this, texture)) {
  37941. return true;
  37942. }
  37943. if (this.lightmapTexture === texture) {
  37944. return true;
  37945. }
  37946. return false;
  37947. };
  37948. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37949. return "PBRBaseSimpleMaterial";
  37950. };
  37951. __decorate([
  37952. BABYLON.serialize(),
  37953. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37954. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37955. __decorate([
  37956. BABYLON.serialize(),
  37957. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37958. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37959. __decorate([
  37960. BABYLON.serializeAsTexture(),
  37961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37962. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37963. __decorate([
  37964. BABYLON.serialize(),
  37965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37966. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37967. __decorate([
  37968. BABYLON.serialize(),
  37969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37970. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37971. __decorate([
  37972. BABYLON.serializeAsTexture(),
  37973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37974. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37975. __decorate([
  37976. BABYLON.serializeAsColor3("emissive"),
  37977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37978. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37979. __decorate([
  37980. BABYLON.serializeAsTexture(),
  37981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37982. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37983. __decorate([
  37984. BABYLON.serialize(),
  37985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37986. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37987. __decorate([
  37988. BABYLON.serializeAsTexture(),
  37989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37990. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37991. __decorate([
  37992. BABYLON.serialize(),
  37993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37994. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37995. __decorate([
  37996. BABYLON.serialize()
  37997. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37998. __decorate([
  37999. BABYLON.serializeAsTexture(),
  38000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38001. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  38002. __decorate([
  38003. BABYLON.serialize(),
  38004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38005. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38006. return PBRBaseSimpleMaterial;
  38007. }(BABYLON.PBRBaseMaterial));
  38008. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38009. })(BABYLON || (BABYLON = {}));
  38010. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38011. var BABYLON;
  38012. (function (BABYLON) {
  38013. /**
  38014. * The Physically based material of BJS.
  38015. *
  38016. * This offers the main features of a standard PBR material.
  38017. * For more information, please refer to the documentation :
  38018. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38019. */
  38020. var PBRMaterial = /** @class */ (function (_super) {
  38021. __extends(PBRMaterial, _super);
  38022. /**
  38023. * Instantiates a new PBRMaterial instance.
  38024. *
  38025. * @param name The material name
  38026. * @param scene The scene the material will be use in.
  38027. */
  38028. function PBRMaterial(name, scene) {
  38029. var _this = _super.call(this, name, scene) || this;
  38030. /**
  38031. * Intensity of the direct lights e.g. the four lights available in your scene.
  38032. * This impacts both the direct diffuse and specular highlights.
  38033. */
  38034. _this.directIntensity = 1.0;
  38035. /**
  38036. * Intensity of the emissive part of the material.
  38037. * This helps controlling the emissive effect without modifying the emissive color.
  38038. */
  38039. _this.emissiveIntensity = 1.0;
  38040. /**
  38041. * Intensity of the environment e.g. how much the environment will light the object
  38042. * either through harmonics for rough material or through the refelction for shiny ones.
  38043. */
  38044. _this.environmentIntensity = 1.0;
  38045. /**
  38046. * This is a special control allowing the reduction of the specular highlights coming from the
  38047. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38048. */
  38049. _this.specularIntensity = 1.0;
  38050. /**
  38051. * Debug Control allowing disabling the bump map on this material.
  38052. */
  38053. _this.disableBumpMap = false;
  38054. /**
  38055. * AKA Occlusion Texture Intensity in other nomenclature.
  38056. */
  38057. _this.ambientTextureStrength = 1.0;
  38058. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38059. /**
  38060. * AKA Diffuse Color in other nomenclature.
  38061. */
  38062. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38063. /**
  38064. * AKA Specular Color in other nomenclature.
  38065. */
  38066. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38067. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38068. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38069. /**
  38070. * AKA Glossiness in other nomenclature.
  38071. */
  38072. _this.microSurface = 1.0;
  38073. /**
  38074. * source material index of refraction (IOR)' / 'destination material IOR.
  38075. */
  38076. _this.indexOfRefraction = 0.66;
  38077. /**
  38078. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38079. */
  38080. _this.invertRefractionY = false;
  38081. /**
  38082. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38083. * Materials half opaque for instance using refraction could benefit from this control.
  38084. */
  38085. _this.linkRefractionWithTransparency = false;
  38086. _this.useLightmapAsShadowmap = false;
  38087. /**
  38088. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38089. */
  38090. _this.useAlphaFromAlbedoTexture = false;
  38091. /**
  38092. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38093. */
  38094. _this.forceAlphaTest = false;
  38095. /**
  38096. * Defines the alpha limits in alpha test mode.
  38097. */
  38098. _this.alphaCutOff = 0.4;
  38099. /**
  38100. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38101. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38102. */
  38103. _this.useSpecularOverAlpha = true;
  38104. /**
  38105. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38106. */
  38107. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38108. /**
  38109. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38110. */
  38111. _this.useRoughnessFromMetallicTextureAlpha = true;
  38112. /**
  38113. * Specifies if the metallic texture contains the roughness information in its green channel.
  38114. */
  38115. _this.useRoughnessFromMetallicTextureGreen = false;
  38116. /**
  38117. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38118. */
  38119. _this.useMetallnessFromMetallicTextureBlue = false;
  38120. /**
  38121. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38122. */
  38123. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38124. /**
  38125. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38126. */
  38127. _this.useAmbientInGrayScale = false;
  38128. /**
  38129. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38130. * The material will try to infer what glossiness each pixel should be.
  38131. */
  38132. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38133. /**
  38134. * BJS is using an harcoded light falloff based on a manually sets up range.
  38135. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38136. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38137. */
  38138. _this.usePhysicalLightFalloff = true;
  38139. /**
  38140. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38141. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38142. */
  38143. _this.useRadianceOverAlpha = true;
  38144. /**
  38145. * Allows using the bump map in parallax mode.
  38146. */
  38147. _this.useParallax = false;
  38148. /**
  38149. * Allows using the bump map in parallax occlusion mode.
  38150. */
  38151. _this.useParallaxOcclusion = false;
  38152. /**
  38153. * Controls the scale bias of the parallax mode.
  38154. */
  38155. _this.parallaxScaleBias = 0.05;
  38156. /**
  38157. * If sets to true, disables all the lights affecting the material.
  38158. */
  38159. _this.disableLighting = false;
  38160. /**
  38161. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38162. */
  38163. _this.forceIrradianceInFragment = false;
  38164. /**
  38165. * Number of Simultaneous lights allowed on the material.
  38166. */
  38167. _this.maxSimultaneousLights = 4;
  38168. /**
  38169. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38170. */
  38171. _this.invertNormalMapX = false;
  38172. /**
  38173. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38174. */
  38175. _this.invertNormalMapY = false;
  38176. /**
  38177. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38178. */
  38179. _this.twoSidedLighting = false;
  38180. /**
  38181. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38182. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38183. */
  38184. _this.useAlphaFresnel = false;
  38185. /**
  38186. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38187. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38188. */
  38189. _this.useLinearAlphaFresnel = false;
  38190. /**
  38191. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38192. * And/Or occlude the blended part.
  38193. */
  38194. _this.environmentBRDFTexture = null;
  38195. /**
  38196. * Force normal to face away from face.
  38197. */
  38198. _this.forceNormalForward = false;
  38199. /**
  38200. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38201. * makes the reflect vector face the model (under horizon).
  38202. */
  38203. _this.useHorizonOcclusion = true;
  38204. /**
  38205. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38206. * too much the area relying on ambient texture to define their ambient occlusion.
  38207. */
  38208. _this.useRadianceOcclusion = true;
  38209. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38210. return _this;
  38211. }
  38212. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38213. /**
  38214. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38215. */
  38216. get: function () {
  38217. return this._PBRMATERIAL_OPAQUE;
  38218. },
  38219. enumerable: true,
  38220. configurable: true
  38221. });
  38222. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38223. /**
  38224. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38225. */
  38226. get: function () {
  38227. return this._PBRMATERIAL_ALPHATEST;
  38228. },
  38229. enumerable: true,
  38230. configurable: true
  38231. });
  38232. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38233. /**
  38234. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38235. */
  38236. get: function () {
  38237. return this._PBRMATERIAL_ALPHABLEND;
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38243. /**
  38244. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38245. * They are also discarded below the alpha cutoff threshold to improve performances.
  38246. */
  38247. get: function () {
  38248. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38249. },
  38250. enumerable: true,
  38251. configurable: true
  38252. });
  38253. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38254. /**
  38255. * Gets the image processing configuration used either in this material.
  38256. */
  38257. get: function () {
  38258. return this._imageProcessingConfiguration;
  38259. },
  38260. /**
  38261. * Sets the Default image processing configuration used either in the this material.
  38262. *
  38263. * If sets to null, the scene one is in use.
  38264. */
  38265. set: function (value) {
  38266. this._attachImageProcessingConfiguration(value);
  38267. // Ensure the effect will be rebuilt.
  38268. this._markAllSubMeshesAsTexturesDirty();
  38269. },
  38270. enumerable: true,
  38271. configurable: true
  38272. });
  38273. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38274. /**
  38275. * Gets wether the color curves effect is enabled.
  38276. */
  38277. get: function () {
  38278. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38279. },
  38280. /**
  38281. * Sets wether the color curves effect is enabled.
  38282. */
  38283. set: function (value) {
  38284. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38285. },
  38286. enumerable: true,
  38287. configurable: true
  38288. });
  38289. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38290. /**
  38291. * Gets wether the color grading effect is enabled.
  38292. */
  38293. get: function () {
  38294. return this.imageProcessingConfiguration.colorGradingEnabled;
  38295. },
  38296. /**
  38297. * Gets wether the color grading effect is enabled.
  38298. */
  38299. set: function (value) {
  38300. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38301. },
  38302. enumerable: true,
  38303. configurable: true
  38304. });
  38305. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38306. /**
  38307. * Gets wether tonemapping is enabled or not.
  38308. */
  38309. get: function () {
  38310. return this._imageProcessingConfiguration.toneMappingEnabled;
  38311. },
  38312. /**
  38313. * Sets wether tonemapping is enabled or not
  38314. */
  38315. set: function (value) {
  38316. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38317. },
  38318. enumerable: true,
  38319. configurable: true
  38320. });
  38321. ;
  38322. ;
  38323. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38324. /**
  38325. * The camera exposure used on this material.
  38326. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38327. * This corresponds to a photographic exposure.
  38328. */
  38329. get: function () {
  38330. return this._imageProcessingConfiguration.exposure;
  38331. },
  38332. /**
  38333. * The camera exposure used on this material.
  38334. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38335. * This corresponds to a photographic exposure.
  38336. */
  38337. set: function (value) {
  38338. this._imageProcessingConfiguration.exposure = value;
  38339. },
  38340. enumerable: true,
  38341. configurable: true
  38342. });
  38343. ;
  38344. ;
  38345. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38346. /**
  38347. * Gets The camera contrast used on this material.
  38348. */
  38349. get: function () {
  38350. return this._imageProcessingConfiguration.contrast;
  38351. },
  38352. /**
  38353. * Sets The camera contrast used on this material.
  38354. */
  38355. set: function (value) {
  38356. this._imageProcessingConfiguration.contrast = value;
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38362. /**
  38363. * Gets the Color Grading 2D Lookup Texture.
  38364. */
  38365. get: function () {
  38366. return this._imageProcessingConfiguration.colorGradingTexture;
  38367. },
  38368. /**
  38369. * Sets the Color Grading 2D Lookup Texture.
  38370. */
  38371. set: function (value) {
  38372. this._imageProcessingConfiguration.colorGradingTexture = value;
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38378. /**
  38379. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38380. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38381. * 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;
  38382. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38383. */
  38384. get: function () {
  38385. return this._imageProcessingConfiguration.colorCurves;
  38386. },
  38387. /**
  38388. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38389. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38390. * 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;
  38391. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38392. */
  38393. set: function (value) {
  38394. this._imageProcessingConfiguration.colorCurves = value;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. PBRMaterial.prototype.getClassName = function () {
  38400. return "PBRMaterial";
  38401. };
  38402. PBRMaterial.prototype.getActiveTextures = function () {
  38403. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38404. if (this._albedoTexture) {
  38405. activeTextures.push(this._albedoTexture);
  38406. }
  38407. if (this._ambientTexture) {
  38408. activeTextures.push(this._ambientTexture);
  38409. }
  38410. if (this._opacityTexture) {
  38411. activeTextures.push(this._opacityTexture);
  38412. }
  38413. if (this._reflectionTexture) {
  38414. activeTextures.push(this._reflectionTexture);
  38415. }
  38416. if (this._emissiveTexture) {
  38417. activeTextures.push(this._emissiveTexture);
  38418. }
  38419. if (this._reflectivityTexture) {
  38420. activeTextures.push(this._reflectivityTexture);
  38421. }
  38422. if (this._metallicTexture) {
  38423. activeTextures.push(this._metallicTexture);
  38424. }
  38425. if (this._microSurfaceTexture) {
  38426. activeTextures.push(this._microSurfaceTexture);
  38427. }
  38428. if (this._bumpTexture) {
  38429. activeTextures.push(this._bumpTexture);
  38430. }
  38431. if (this._lightmapTexture) {
  38432. activeTextures.push(this._lightmapTexture);
  38433. }
  38434. if (this._refractionTexture) {
  38435. activeTextures.push(this._refractionTexture);
  38436. }
  38437. return activeTextures;
  38438. };
  38439. PBRMaterial.prototype.hasTexture = function (texture) {
  38440. if (_super.prototype.hasTexture.call(this, texture)) {
  38441. return true;
  38442. }
  38443. if (this._albedoTexture === texture) {
  38444. return true;
  38445. }
  38446. if (this._ambientTexture === texture) {
  38447. return true;
  38448. }
  38449. if (this._opacityTexture === texture) {
  38450. return true;
  38451. }
  38452. if (this._reflectionTexture === texture) {
  38453. return true;
  38454. }
  38455. if (this._reflectivityTexture === texture) {
  38456. return true;
  38457. }
  38458. if (this._metallicTexture === texture) {
  38459. return true;
  38460. }
  38461. if (this._microSurfaceTexture === texture) {
  38462. return true;
  38463. }
  38464. if (this._bumpTexture === texture) {
  38465. return true;
  38466. }
  38467. if (this._lightmapTexture === texture) {
  38468. return true;
  38469. }
  38470. if (this._refractionTexture === texture) {
  38471. return true;
  38472. }
  38473. return false;
  38474. };
  38475. PBRMaterial.prototype.clone = function (name) {
  38476. var _this = this;
  38477. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38478. clone.id = name;
  38479. clone.name = name;
  38480. return clone;
  38481. };
  38482. PBRMaterial.prototype.serialize = function () {
  38483. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38484. serializationObject.customType = "BABYLON.PBRMaterial";
  38485. return serializationObject;
  38486. };
  38487. // Statics
  38488. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38489. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38490. };
  38491. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38492. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38493. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38494. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38495. __decorate([
  38496. BABYLON.serialize(),
  38497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38498. ], PBRMaterial.prototype, "directIntensity", void 0);
  38499. __decorate([
  38500. BABYLON.serialize(),
  38501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38502. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38503. __decorate([
  38504. BABYLON.serialize(),
  38505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38506. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38507. __decorate([
  38508. BABYLON.serialize(),
  38509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38510. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38511. __decorate([
  38512. BABYLON.serialize(),
  38513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38514. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38515. __decorate([
  38516. BABYLON.serializeAsTexture(),
  38517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38518. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38519. __decorate([
  38520. BABYLON.serializeAsTexture(),
  38521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38522. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38523. __decorate([
  38524. BABYLON.serialize(),
  38525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38526. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38527. __decorate([
  38528. BABYLON.serializeAsTexture(),
  38529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38530. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38531. __decorate([
  38532. BABYLON.serializeAsTexture(),
  38533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38534. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38535. __decorate([
  38536. BABYLON.serializeAsTexture(),
  38537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38538. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38539. __decorate([
  38540. BABYLON.serializeAsTexture(),
  38541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38542. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38543. __decorate([
  38544. BABYLON.serializeAsTexture(),
  38545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38546. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38547. __decorate([
  38548. BABYLON.serialize(),
  38549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38550. ], PBRMaterial.prototype, "metallic", void 0);
  38551. __decorate([
  38552. BABYLON.serialize(),
  38553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38554. ], PBRMaterial.prototype, "roughness", void 0);
  38555. __decorate([
  38556. BABYLON.serializeAsTexture(),
  38557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38558. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38559. __decorate([
  38560. BABYLON.serializeAsTexture(),
  38561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38562. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38563. __decorate([
  38564. BABYLON.serializeAsTexture(),
  38565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38566. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38567. __decorate([
  38568. BABYLON.serializeAsTexture(),
  38569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38570. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38571. __decorate([
  38572. BABYLON.serializeAsColor3("ambient"),
  38573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38574. ], PBRMaterial.prototype, "ambientColor", void 0);
  38575. __decorate([
  38576. BABYLON.serializeAsColor3("albedo"),
  38577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38578. ], PBRMaterial.prototype, "albedoColor", void 0);
  38579. __decorate([
  38580. BABYLON.serializeAsColor3("reflectivity"),
  38581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38582. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38583. __decorate([
  38584. BABYLON.serializeAsColor3("reflection"),
  38585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38586. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38587. __decorate([
  38588. BABYLON.serializeAsColor3("emissive"),
  38589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38590. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38591. __decorate([
  38592. BABYLON.serialize(),
  38593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38594. ], PBRMaterial.prototype, "microSurface", void 0);
  38595. __decorate([
  38596. BABYLON.serialize(),
  38597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38598. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38599. __decorate([
  38600. BABYLON.serialize(),
  38601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38602. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38603. __decorate([
  38604. BABYLON.serialize(),
  38605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38606. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38607. __decorate([
  38608. BABYLON.serialize(),
  38609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38610. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38611. __decorate([
  38612. BABYLON.serialize(),
  38613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38614. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38615. __decorate([
  38616. BABYLON.serialize(),
  38617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38618. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38619. __decorate([
  38620. BABYLON.serialize(),
  38621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38622. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38623. __decorate([
  38624. BABYLON.serialize(),
  38625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38626. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38627. __decorate([
  38628. BABYLON.serialize(),
  38629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38630. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38631. __decorate([
  38632. BABYLON.serialize(),
  38633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38634. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38635. __decorate([
  38636. BABYLON.serialize(),
  38637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38638. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38639. __decorate([
  38640. BABYLON.serialize(),
  38641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38642. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38643. __decorate([
  38644. BABYLON.serialize(),
  38645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38646. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38647. __decorate([
  38648. BABYLON.serialize(),
  38649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38650. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38651. __decorate([
  38652. BABYLON.serialize(),
  38653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38654. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38655. __decorate([
  38656. BABYLON.serialize(),
  38657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38658. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38659. __decorate([
  38660. BABYLON.serialize(),
  38661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38662. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38663. __decorate([
  38664. BABYLON.serialize(),
  38665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38666. ], PBRMaterial.prototype, "useParallax", void 0);
  38667. __decorate([
  38668. BABYLON.serialize(),
  38669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38670. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38671. __decorate([
  38672. BABYLON.serialize(),
  38673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38674. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38675. __decorate([
  38676. BABYLON.serialize(),
  38677. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38678. ], PBRMaterial.prototype, "disableLighting", void 0);
  38679. __decorate([
  38680. BABYLON.serialize(),
  38681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38682. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38683. __decorate([
  38684. BABYLON.serialize(),
  38685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38686. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38687. __decorate([
  38688. BABYLON.serialize(),
  38689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38690. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38691. __decorate([
  38692. BABYLON.serialize(),
  38693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38694. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38695. __decorate([
  38696. BABYLON.serialize(),
  38697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38698. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38699. __decorate([
  38700. BABYLON.serialize(),
  38701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38702. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38703. __decorate([
  38704. BABYLON.serialize(),
  38705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38706. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38707. __decorate([
  38708. BABYLON.serializeAsTexture(),
  38709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38710. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38711. __decorate([
  38712. BABYLON.serialize(),
  38713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38714. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38715. __decorate([
  38716. BABYLON.serialize(),
  38717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38718. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38719. __decorate([
  38720. BABYLON.serialize(),
  38721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38722. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38723. return PBRMaterial;
  38724. }(BABYLON.PBRBaseMaterial));
  38725. BABYLON.PBRMaterial = PBRMaterial;
  38726. })(BABYLON || (BABYLON = {}));
  38727. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38728. var BABYLON;
  38729. (function (BABYLON) {
  38730. /**
  38731. * The PBR material of BJS following the metal roughness convention.
  38732. *
  38733. * This fits to the PBR convention in the GLTF definition:
  38734. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38735. */
  38736. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38737. __extends(PBRMetallicRoughnessMaterial, _super);
  38738. /**
  38739. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38740. *
  38741. * @param name The material name
  38742. * @param scene The scene the material will be use in.
  38743. */
  38744. function PBRMetallicRoughnessMaterial(name, scene) {
  38745. var _this = _super.call(this, name, scene) || this;
  38746. _this._useRoughnessFromMetallicTextureAlpha = false;
  38747. _this._useRoughnessFromMetallicTextureGreen = true;
  38748. _this._useMetallnessFromMetallicTextureBlue = true;
  38749. _this._forceMetallicWorkflow = true;
  38750. return _this;
  38751. }
  38752. /**
  38753. * Return the currrent class name of the material.
  38754. */
  38755. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38756. return "PBRMetallicRoughnessMaterial";
  38757. };
  38758. /**
  38759. * Return the active textures of the material.
  38760. */
  38761. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38762. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38763. if (this.baseTexture) {
  38764. activeTextures.push(this.baseTexture);
  38765. }
  38766. if (this.metallicRoughnessTexture) {
  38767. activeTextures.push(this.metallicRoughnessTexture);
  38768. }
  38769. return activeTextures;
  38770. };
  38771. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38772. if (_super.prototype.hasTexture.call(this, texture)) {
  38773. return true;
  38774. }
  38775. if (this.baseTexture === texture) {
  38776. return true;
  38777. }
  38778. if (this.metallicRoughnessTexture === texture) {
  38779. return true;
  38780. }
  38781. return false;
  38782. };
  38783. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38784. var _this = this;
  38785. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38786. clone.id = name;
  38787. clone.name = name;
  38788. return clone;
  38789. };
  38790. /**
  38791. * Serialize the material to a parsable JSON object.
  38792. */
  38793. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38795. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38796. return serializationObject;
  38797. };
  38798. /**
  38799. * Parses a JSON object correponding to the serialize function.
  38800. */
  38801. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38802. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38803. };
  38804. __decorate([
  38805. BABYLON.serializeAsColor3(),
  38806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38807. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38808. __decorate([
  38809. BABYLON.serializeAsTexture(),
  38810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38811. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38812. __decorate([
  38813. BABYLON.serialize(),
  38814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38815. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38816. __decorate([
  38817. BABYLON.serialize(),
  38818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38819. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38820. __decorate([
  38821. BABYLON.serializeAsTexture(),
  38822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38823. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38824. return PBRMetallicRoughnessMaterial;
  38825. }(BABYLON.PBRBaseSimpleMaterial));
  38826. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38827. })(BABYLON || (BABYLON = {}));
  38828. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38829. var BABYLON;
  38830. (function (BABYLON) {
  38831. /**
  38832. * The PBR material of BJS following the specular glossiness convention.
  38833. *
  38834. * This fits to the PBR convention in the GLTF definition:
  38835. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38836. */
  38837. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38838. __extends(PBRSpecularGlossinessMaterial, _super);
  38839. /**
  38840. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38841. *
  38842. * @param name The material name
  38843. * @param scene The scene the material will be use in.
  38844. */
  38845. function PBRSpecularGlossinessMaterial(name, scene) {
  38846. var _this = _super.call(this, name, scene) || this;
  38847. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38848. return _this;
  38849. }
  38850. /**
  38851. * Return the currrent class name of the material.
  38852. */
  38853. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38854. return "PBRSpecularGlossinessMaterial";
  38855. };
  38856. /**
  38857. * Return the active textures of the material.
  38858. */
  38859. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38860. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38861. if (this.diffuseTexture) {
  38862. activeTextures.push(this.diffuseTexture);
  38863. }
  38864. if (this.specularGlossinessTexture) {
  38865. activeTextures.push(this.specularGlossinessTexture);
  38866. }
  38867. return activeTextures;
  38868. };
  38869. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38870. if (_super.prototype.hasTexture.call(this, texture)) {
  38871. return true;
  38872. }
  38873. if (this.diffuseTexture === texture) {
  38874. return true;
  38875. }
  38876. if (this.specularGlossinessTexture === texture) {
  38877. return true;
  38878. }
  38879. return false;
  38880. };
  38881. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38882. var _this = this;
  38883. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38884. clone.id = name;
  38885. clone.name = name;
  38886. return clone;
  38887. };
  38888. /**
  38889. * Serialize the material to a parsable JSON object.
  38890. */
  38891. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38892. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38893. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38894. return serializationObject;
  38895. };
  38896. /**
  38897. * Parses a JSON object correponding to the serialize function.
  38898. */
  38899. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38900. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38901. };
  38902. __decorate([
  38903. BABYLON.serializeAsColor3("diffuse"),
  38904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38905. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38906. __decorate([
  38907. BABYLON.serializeAsTexture(),
  38908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38909. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38910. __decorate([
  38911. BABYLON.serializeAsColor3("specular"),
  38912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38913. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38914. __decorate([
  38915. BABYLON.serialize(),
  38916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38917. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38918. __decorate([
  38919. BABYLON.serializeAsTexture(),
  38920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38921. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38922. return PBRSpecularGlossinessMaterial;
  38923. }(BABYLON.PBRBaseSimpleMaterial));
  38924. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38925. })(BABYLON || (BABYLON = {}));
  38926. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38927. var BABYLON;
  38928. (function (BABYLON) {
  38929. BABYLON.CameraInputTypes = {};
  38930. var CameraInputsManager = /** @class */ (function () {
  38931. function CameraInputsManager(camera) {
  38932. this.attached = {};
  38933. this.camera = camera;
  38934. this.checkInputs = function () { };
  38935. }
  38936. CameraInputsManager.prototype.add = function (input) {
  38937. var type = input.getSimpleName();
  38938. if (this.attached[type]) {
  38939. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38940. return;
  38941. }
  38942. this.attached[type] = input;
  38943. input.camera = this.camera;
  38944. //for checkInputs, we are dynamically creating a function
  38945. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38946. if (input.checkInputs) {
  38947. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38948. }
  38949. if (this.attachedElement) {
  38950. input.attachControl(this.attachedElement);
  38951. }
  38952. };
  38953. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38954. for (var cam in this.attached) {
  38955. var input = this.attached[cam];
  38956. if (input === inputToRemove) {
  38957. input.detachControl(this.attachedElement);
  38958. input.camera = null;
  38959. delete this.attached[cam];
  38960. this.rebuildInputCheck();
  38961. }
  38962. }
  38963. };
  38964. CameraInputsManager.prototype.removeByType = function (inputType) {
  38965. for (var cam in this.attached) {
  38966. var input = this.attached[cam];
  38967. if (input.getClassName() === inputType) {
  38968. input.detachControl(this.attachedElement);
  38969. input.camera = null;
  38970. delete this.attached[cam];
  38971. this.rebuildInputCheck();
  38972. }
  38973. }
  38974. };
  38975. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38976. var current = this.checkInputs;
  38977. return function () {
  38978. current();
  38979. fn();
  38980. };
  38981. };
  38982. CameraInputsManager.prototype.attachInput = function (input) {
  38983. if (this.attachedElement) {
  38984. input.attachControl(this.attachedElement, this.noPreventDefault);
  38985. }
  38986. };
  38987. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38988. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38989. if (this.attachedElement) {
  38990. return;
  38991. }
  38992. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38993. this.attachedElement = element;
  38994. this.noPreventDefault = noPreventDefault;
  38995. for (var cam in this.attached) {
  38996. this.attached[cam].attachControl(element, noPreventDefault);
  38997. }
  38998. };
  38999. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  39000. if (disconnect === void 0) { disconnect = false; }
  39001. if (this.attachedElement !== element) {
  39002. return;
  39003. }
  39004. for (var cam in this.attached) {
  39005. this.attached[cam].detachControl(element);
  39006. if (disconnect) {
  39007. this.attached[cam].camera = null;
  39008. }
  39009. }
  39010. this.attachedElement = null;
  39011. };
  39012. CameraInputsManager.prototype.rebuildInputCheck = function () {
  39013. this.checkInputs = function () { };
  39014. for (var cam in this.attached) {
  39015. var input = this.attached[cam];
  39016. if (input.checkInputs) {
  39017. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39018. }
  39019. }
  39020. };
  39021. CameraInputsManager.prototype.clear = function () {
  39022. if (this.attachedElement) {
  39023. this.detachElement(this.attachedElement, true);
  39024. }
  39025. this.attached = {};
  39026. this.attachedElement = null;
  39027. this.checkInputs = function () { };
  39028. };
  39029. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  39030. var inputs = {};
  39031. for (var cam in this.attached) {
  39032. var input = this.attached[cam];
  39033. var res = BABYLON.SerializationHelper.Serialize(input);
  39034. inputs[input.getClassName()] = res;
  39035. }
  39036. serializedCamera.inputsmgr = inputs;
  39037. };
  39038. CameraInputsManager.prototype.parse = function (parsedCamera) {
  39039. var parsedInputs = parsedCamera.inputsmgr;
  39040. if (parsedInputs) {
  39041. this.clear();
  39042. for (var n in parsedInputs) {
  39043. var construct = BABYLON.CameraInputTypes[n];
  39044. if (construct) {
  39045. var parsedinput = parsedInputs[n];
  39046. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  39047. this.add(input);
  39048. }
  39049. }
  39050. }
  39051. else {
  39052. //2016-03-08 this part is for managing backward compatibility
  39053. for (var n in this.attached) {
  39054. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  39055. if (construct) {
  39056. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  39057. this.remove(this.attached[n]);
  39058. this.add(input);
  39059. }
  39060. }
  39061. }
  39062. };
  39063. return CameraInputsManager;
  39064. }());
  39065. BABYLON.CameraInputsManager = CameraInputsManager;
  39066. })(BABYLON || (BABYLON = {}));
  39067. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  39068. var BABYLON;
  39069. (function (BABYLON) {
  39070. var TargetCamera = /** @class */ (function (_super) {
  39071. __extends(TargetCamera, _super);
  39072. function TargetCamera(name, position, scene) {
  39073. var _this = _super.call(this, name, position, scene) || this;
  39074. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39075. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  39076. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  39077. _this.speed = 2.0;
  39078. _this.noRotationConstraint = false;
  39079. _this.lockedTarget = null;
  39080. _this._currentTarget = BABYLON.Vector3.Zero();
  39081. _this._viewMatrix = BABYLON.Matrix.Zero();
  39082. _this._camMatrix = BABYLON.Matrix.Zero();
  39083. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  39084. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  39085. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  39086. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  39087. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  39088. _this._lookAtTemp = BABYLON.Matrix.Zero();
  39089. _this._tempMatrix = BABYLON.Matrix.Zero();
  39090. return _this;
  39091. }
  39092. TargetCamera.prototype.getFrontPosition = function (distance) {
  39093. this.getWorldMatrix();
  39094. var direction = this.getTarget().subtract(this.position);
  39095. direction.normalize();
  39096. direction.scaleInPlace(distance);
  39097. return this.globalPosition.add(direction);
  39098. };
  39099. TargetCamera.prototype._getLockedTargetPosition = function () {
  39100. if (!this.lockedTarget) {
  39101. return null;
  39102. }
  39103. if (this.lockedTarget.absolutePosition) {
  39104. this.lockedTarget.computeWorldMatrix();
  39105. }
  39106. return this.lockedTarget.absolutePosition || this.lockedTarget;
  39107. };
  39108. TargetCamera.prototype.storeState = function () {
  39109. this._storedPosition = this.position.clone();
  39110. this._storedRotation = this.rotation.clone();
  39111. if (this.rotationQuaternion) {
  39112. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  39113. }
  39114. return _super.prototype.storeState.call(this);
  39115. };
  39116. /**
  39117. * Restored camera state. You must call storeState() first
  39118. */
  39119. TargetCamera.prototype._restoreStateValues = function () {
  39120. if (!_super.prototype._restoreStateValues.call(this)) {
  39121. return false;
  39122. }
  39123. this.position = this._storedPosition.clone();
  39124. this.rotation = this._storedRotation.clone();
  39125. if (this.rotationQuaternion) {
  39126. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39127. }
  39128. this.cameraDirection.copyFromFloats(0, 0, 0);
  39129. this.cameraRotation.copyFromFloats(0, 0);
  39130. return true;
  39131. };
  39132. // Cache
  39133. TargetCamera.prototype._initCache = function () {
  39134. _super.prototype._initCache.call(this);
  39135. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39136. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39137. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39138. };
  39139. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39140. if (!ignoreParentClass) {
  39141. _super.prototype._updateCache.call(this);
  39142. }
  39143. var lockedTargetPosition = this._getLockedTargetPosition();
  39144. if (!lockedTargetPosition) {
  39145. this._cache.lockedTarget = null;
  39146. }
  39147. else {
  39148. if (!this._cache.lockedTarget) {
  39149. this._cache.lockedTarget = lockedTargetPosition.clone();
  39150. }
  39151. else {
  39152. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39153. }
  39154. }
  39155. this._cache.rotation.copyFrom(this.rotation);
  39156. if (this.rotationQuaternion)
  39157. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39158. };
  39159. // Synchronized
  39160. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39161. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39162. return false;
  39163. }
  39164. var lockedTargetPosition = this._getLockedTargetPosition();
  39165. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39166. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39167. };
  39168. // Methods
  39169. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39170. var engine = this.getEngine();
  39171. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39172. };
  39173. // Target
  39174. TargetCamera.prototype.setTarget = function (target) {
  39175. this.upVector.normalize();
  39176. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39177. this._camMatrix.invert();
  39178. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39179. var vDir = target.subtract(this.position);
  39180. if (vDir.x >= 0.0) {
  39181. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39182. }
  39183. else {
  39184. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39185. }
  39186. this.rotation.z = 0;
  39187. if (isNaN(this.rotation.x)) {
  39188. this.rotation.x = 0;
  39189. }
  39190. if (isNaN(this.rotation.y)) {
  39191. this.rotation.y = 0;
  39192. }
  39193. if (isNaN(this.rotation.z)) {
  39194. this.rotation.z = 0;
  39195. }
  39196. if (this.rotationQuaternion) {
  39197. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39198. }
  39199. };
  39200. /**
  39201. * Return the current target position of the camera. This value is expressed in local space.
  39202. */
  39203. TargetCamera.prototype.getTarget = function () {
  39204. return this._currentTarget;
  39205. };
  39206. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39207. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39208. };
  39209. TargetCamera.prototype._updatePosition = function () {
  39210. if (this.parent) {
  39211. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39212. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39213. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39214. return;
  39215. }
  39216. this.position.addInPlace(this.cameraDirection);
  39217. };
  39218. TargetCamera.prototype._checkInputs = function () {
  39219. var needToMove = this._decideIfNeedsToMove();
  39220. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39221. // Move
  39222. if (needToMove) {
  39223. this._updatePosition();
  39224. }
  39225. // Rotate
  39226. if (needToRotate) {
  39227. this.rotation.x += this.cameraRotation.x;
  39228. this.rotation.y += this.cameraRotation.y;
  39229. //rotate, if quaternion is set and rotation was used
  39230. if (this.rotationQuaternion) {
  39231. var len = this.rotation.lengthSquared();
  39232. if (len) {
  39233. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39234. }
  39235. }
  39236. if (!this.noRotationConstraint) {
  39237. var limit = (Math.PI / 2) * 0.95;
  39238. if (this.rotation.x > limit)
  39239. this.rotation.x = limit;
  39240. if (this.rotation.x < -limit)
  39241. this.rotation.x = -limit;
  39242. }
  39243. }
  39244. // Inertia
  39245. if (needToMove) {
  39246. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39247. this.cameraDirection.x = 0;
  39248. }
  39249. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39250. this.cameraDirection.y = 0;
  39251. }
  39252. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39253. this.cameraDirection.z = 0;
  39254. }
  39255. this.cameraDirection.scaleInPlace(this.inertia);
  39256. }
  39257. if (needToRotate) {
  39258. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39259. this.cameraRotation.x = 0;
  39260. }
  39261. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39262. this.cameraRotation.y = 0;
  39263. }
  39264. this.cameraRotation.scaleInPlace(this.inertia);
  39265. }
  39266. _super.prototype._checkInputs.call(this);
  39267. };
  39268. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39269. if (this.rotationQuaternion) {
  39270. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39271. }
  39272. else {
  39273. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39274. }
  39275. //update the up vector!
  39276. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39277. };
  39278. TargetCamera.prototype._getViewMatrix = function () {
  39279. if (this.lockedTarget) {
  39280. this.setTarget(this._getLockedTargetPosition());
  39281. }
  39282. // Compute
  39283. this._updateCameraRotationMatrix();
  39284. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39285. // Computing target and final matrix
  39286. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39287. if (this.getScene().useRightHandedSystem) {
  39288. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39289. }
  39290. else {
  39291. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39292. }
  39293. return this._viewMatrix;
  39294. };
  39295. /**
  39296. * @override
  39297. * Override Camera.createRigCamera
  39298. */
  39299. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39300. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39301. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39302. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39303. if (!this.rotationQuaternion) {
  39304. this.rotationQuaternion = new BABYLON.Quaternion();
  39305. }
  39306. rigCamera._cameraRigParams = {};
  39307. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39308. }
  39309. return rigCamera;
  39310. }
  39311. return null;
  39312. };
  39313. /**
  39314. * @override
  39315. * Override Camera._updateRigCameras
  39316. */
  39317. TargetCamera.prototype._updateRigCameras = function () {
  39318. var camLeft = this._rigCameras[0];
  39319. var camRight = this._rigCameras[1];
  39320. switch (this.cameraRigMode) {
  39321. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39322. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39323. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39324. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39325. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39326. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39327. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39328. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39329. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39330. camLeft.setTarget(this.getTarget());
  39331. camRight.setTarget(this.getTarget());
  39332. break;
  39333. case BABYLON.Camera.RIG_MODE_VR:
  39334. if (camLeft.rotationQuaternion) {
  39335. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39336. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39337. }
  39338. else {
  39339. camLeft.rotation.copyFrom(this.rotation);
  39340. camRight.rotation.copyFrom(this.rotation);
  39341. }
  39342. camLeft.position.copyFrom(this.position);
  39343. camRight.position.copyFrom(this.position);
  39344. break;
  39345. }
  39346. _super.prototype._updateRigCameras.call(this);
  39347. };
  39348. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39349. if (!this._rigCamTransformMatrix) {
  39350. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39351. }
  39352. var target = this.getTarget();
  39353. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39354. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39355. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39356. };
  39357. TargetCamera.prototype.getClassName = function () {
  39358. return "TargetCamera";
  39359. };
  39360. __decorate([
  39361. BABYLON.serializeAsVector3()
  39362. ], TargetCamera.prototype, "rotation", void 0);
  39363. __decorate([
  39364. BABYLON.serialize()
  39365. ], TargetCamera.prototype, "speed", void 0);
  39366. __decorate([
  39367. BABYLON.serializeAsMeshReference("lockedTargetId")
  39368. ], TargetCamera.prototype, "lockedTarget", void 0);
  39369. return TargetCamera;
  39370. }(BABYLON.Camera));
  39371. BABYLON.TargetCamera = TargetCamera;
  39372. })(BABYLON || (BABYLON = {}));
  39373. //# sourceMappingURL=babylon.targetCamera.js.map
  39374. var BABYLON;
  39375. (function (BABYLON) {
  39376. var FreeCameraMouseInput = /** @class */ (function () {
  39377. function FreeCameraMouseInput(touchEnabled) {
  39378. if (touchEnabled === void 0) { touchEnabled = true; }
  39379. this.touchEnabled = touchEnabled;
  39380. this.buttons = [0, 1, 2];
  39381. this.angularSensibility = 2000.0;
  39382. this.previousPosition = null;
  39383. }
  39384. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39385. var _this = this;
  39386. var engine = this.camera.getEngine();
  39387. if (!this._pointerInput) {
  39388. this._pointerInput = function (p, s) {
  39389. var evt = p.event;
  39390. if (engine.isInVRExclusivePointerMode) {
  39391. return;
  39392. }
  39393. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39394. return;
  39395. }
  39396. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39397. return;
  39398. }
  39399. var srcElement = (evt.srcElement || evt.target);
  39400. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39401. try {
  39402. srcElement.setPointerCapture(evt.pointerId);
  39403. }
  39404. catch (e) {
  39405. //Nothing to do with the error. Execution will continue.
  39406. }
  39407. _this.previousPosition = {
  39408. x: evt.clientX,
  39409. y: evt.clientY
  39410. };
  39411. if (!noPreventDefault) {
  39412. evt.preventDefault();
  39413. element.focus();
  39414. }
  39415. }
  39416. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39417. try {
  39418. srcElement.releasePointerCapture(evt.pointerId);
  39419. }
  39420. catch (e) {
  39421. //Nothing to do with the error.
  39422. }
  39423. _this.previousPosition = null;
  39424. if (!noPreventDefault) {
  39425. evt.preventDefault();
  39426. }
  39427. }
  39428. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39429. if (!_this.previousPosition || engine.isPointerLock) {
  39430. return;
  39431. }
  39432. var offsetX = evt.clientX - _this.previousPosition.x;
  39433. var offsetY = evt.clientY - _this.previousPosition.y;
  39434. if (_this.camera.getScene().useRightHandedSystem) {
  39435. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39436. }
  39437. else {
  39438. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39439. }
  39440. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39441. _this.previousPosition = {
  39442. x: evt.clientX,
  39443. y: evt.clientY
  39444. };
  39445. if (!noPreventDefault) {
  39446. evt.preventDefault();
  39447. }
  39448. }
  39449. };
  39450. }
  39451. this._onMouseMove = function (evt) {
  39452. if (!engine.isPointerLock) {
  39453. return;
  39454. }
  39455. if (engine.isInVRExclusivePointerMode) {
  39456. return;
  39457. }
  39458. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39459. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39460. if (_this.camera.getScene().useRightHandedSystem) {
  39461. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39462. }
  39463. else {
  39464. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39465. }
  39466. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39467. _this.previousPosition = null;
  39468. if (!noPreventDefault) {
  39469. evt.preventDefault();
  39470. }
  39471. };
  39472. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39473. element.addEventListener("mousemove", this._onMouseMove, false);
  39474. };
  39475. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39476. if (this._observer && element) {
  39477. this.camera.getScene().onPointerObservable.remove(this._observer);
  39478. if (this._onMouseMove) {
  39479. element.removeEventListener("mousemove", this._onMouseMove);
  39480. }
  39481. this._observer = null;
  39482. this._onMouseMove = null;
  39483. this.previousPosition = null;
  39484. }
  39485. };
  39486. FreeCameraMouseInput.prototype.getClassName = function () {
  39487. return "FreeCameraMouseInput";
  39488. };
  39489. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39490. return "mouse";
  39491. };
  39492. __decorate([
  39493. BABYLON.serialize()
  39494. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39495. __decorate([
  39496. BABYLON.serialize()
  39497. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39498. return FreeCameraMouseInput;
  39499. }());
  39500. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39501. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39502. })(BABYLON || (BABYLON = {}));
  39503. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39504. var BABYLON;
  39505. (function (BABYLON) {
  39506. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39507. function FreeCameraKeyboardMoveInput() {
  39508. this._keys = new Array();
  39509. this.keysUp = [38];
  39510. this.keysDown = [40];
  39511. this.keysLeft = [37];
  39512. this.keysRight = [39];
  39513. }
  39514. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39515. var _this = this;
  39516. if (this._onCanvasBlurObserver) {
  39517. return;
  39518. }
  39519. this._scene = this.camera.getScene();
  39520. this._engine = this._scene.getEngine();
  39521. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39522. _this._keys = [];
  39523. });
  39524. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39525. var evt = info.event;
  39526. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39527. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39528. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39529. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39530. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39531. var index = _this._keys.indexOf(evt.keyCode);
  39532. if (index === -1) {
  39533. _this._keys.push(evt.keyCode);
  39534. }
  39535. if (!noPreventDefault) {
  39536. evt.preventDefault();
  39537. }
  39538. }
  39539. }
  39540. else {
  39541. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39542. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39543. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39544. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39545. var index = _this._keys.indexOf(evt.keyCode);
  39546. if (index >= 0) {
  39547. _this._keys.splice(index, 1);
  39548. }
  39549. if (!noPreventDefault) {
  39550. evt.preventDefault();
  39551. }
  39552. }
  39553. }
  39554. });
  39555. };
  39556. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39557. if (this._scene) {
  39558. if (this._onKeyboardObserver) {
  39559. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39560. }
  39561. if (this._onCanvasBlurObserver) {
  39562. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39563. }
  39564. this._onKeyboardObserver = null;
  39565. this._onCanvasBlurObserver = null;
  39566. }
  39567. this._keys = [];
  39568. };
  39569. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39570. if (this._onKeyboardObserver) {
  39571. var camera = this.camera;
  39572. // Keyboard
  39573. for (var index = 0; index < this._keys.length; index++) {
  39574. var keyCode = this._keys[index];
  39575. var speed = camera._computeLocalCameraSpeed();
  39576. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39577. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39578. }
  39579. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39580. camera._localDirection.copyFromFloats(0, 0, speed);
  39581. }
  39582. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39583. camera._localDirection.copyFromFloats(speed, 0, 0);
  39584. }
  39585. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39586. camera._localDirection.copyFromFloats(0, 0, -speed);
  39587. }
  39588. if (camera.getScene().useRightHandedSystem) {
  39589. camera._localDirection.z *= -1;
  39590. }
  39591. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39592. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39593. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39594. }
  39595. }
  39596. };
  39597. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39598. return "FreeCameraKeyboardMoveInput";
  39599. };
  39600. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39601. this._keys = [];
  39602. };
  39603. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39604. return "keyboard";
  39605. };
  39606. __decorate([
  39607. BABYLON.serialize()
  39608. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39609. __decorate([
  39610. BABYLON.serialize()
  39611. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39612. __decorate([
  39613. BABYLON.serialize()
  39614. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39615. __decorate([
  39616. BABYLON.serialize()
  39617. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39618. return FreeCameraKeyboardMoveInput;
  39619. }());
  39620. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39621. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39622. })(BABYLON || (BABYLON = {}));
  39623. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39624. var BABYLON;
  39625. (function (BABYLON) {
  39626. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39627. __extends(FreeCameraInputsManager, _super);
  39628. function FreeCameraInputsManager(camera) {
  39629. return _super.call(this, camera) || this;
  39630. }
  39631. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39632. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39633. return this;
  39634. };
  39635. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39636. if (touchEnabled === void 0) { touchEnabled = true; }
  39637. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39638. return this;
  39639. };
  39640. FreeCameraInputsManager.prototype.addGamepad = function () {
  39641. this.add(new BABYLON.FreeCameraGamepadInput());
  39642. return this;
  39643. };
  39644. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39645. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39646. return this;
  39647. };
  39648. FreeCameraInputsManager.prototype.addTouch = function () {
  39649. this.add(new BABYLON.FreeCameraTouchInput());
  39650. return this;
  39651. };
  39652. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39653. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39654. return this;
  39655. };
  39656. return FreeCameraInputsManager;
  39657. }(BABYLON.CameraInputsManager));
  39658. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39659. })(BABYLON || (BABYLON = {}));
  39660. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39661. var BABYLON;
  39662. (function (BABYLON) {
  39663. var FreeCamera = /** @class */ (function (_super) {
  39664. __extends(FreeCamera, _super);
  39665. function FreeCamera(name, position, scene) {
  39666. var _this = _super.call(this, name, position, scene) || this;
  39667. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39668. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39669. _this.checkCollisions = false;
  39670. _this.applyGravity = false;
  39671. _this._needMoveForGravity = false;
  39672. _this._oldPosition = BABYLON.Vector3.Zero();
  39673. _this._diffPosition = BABYLON.Vector3.Zero();
  39674. _this._newPosition = BABYLON.Vector3.Zero();
  39675. // Collisions
  39676. _this._collisionMask = -1;
  39677. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39678. if (collidedMesh === void 0) { collidedMesh = null; }
  39679. //TODO move this to the collision coordinator!
  39680. if (_this.getScene().workerCollisions)
  39681. newPosition.multiplyInPlace(_this._collider._radius);
  39682. var updatePosition = function (newPos) {
  39683. _this._newPosition.copyFrom(newPos);
  39684. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39685. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39686. _this.position.addInPlace(_this._diffPosition);
  39687. if (_this.onCollide && collidedMesh) {
  39688. _this.onCollide(collidedMesh);
  39689. }
  39690. }
  39691. };
  39692. updatePosition(newPosition);
  39693. };
  39694. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39695. _this.inputs.addKeyboard().addMouse();
  39696. return _this;
  39697. }
  39698. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39699. //-- begin properties for backward compatibility for inputs
  39700. get: function () {
  39701. var mouse = this.inputs.attached["mouse"];
  39702. if (mouse)
  39703. return mouse.angularSensibility;
  39704. return 0;
  39705. },
  39706. set: function (value) {
  39707. var mouse = this.inputs.attached["mouse"];
  39708. if (mouse)
  39709. mouse.angularSensibility = value;
  39710. },
  39711. enumerable: true,
  39712. configurable: true
  39713. });
  39714. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39715. get: function () {
  39716. var keyboard = this.inputs.attached["keyboard"];
  39717. if (keyboard)
  39718. return keyboard.keysUp;
  39719. return [];
  39720. },
  39721. set: function (value) {
  39722. var keyboard = this.inputs.attached["keyboard"];
  39723. if (keyboard)
  39724. keyboard.keysUp = value;
  39725. },
  39726. enumerable: true,
  39727. configurable: true
  39728. });
  39729. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39730. get: function () {
  39731. var keyboard = this.inputs.attached["keyboard"];
  39732. if (keyboard)
  39733. return keyboard.keysDown;
  39734. return [];
  39735. },
  39736. set: function (value) {
  39737. var keyboard = this.inputs.attached["keyboard"];
  39738. if (keyboard)
  39739. keyboard.keysDown = value;
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39745. get: function () {
  39746. var keyboard = this.inputs.attached["keyboard"];
  39747. if (keyboard)
  39748. return keyboard.keysLeft;
  39749. return [];
  39750. },
  39751. set: function (value) {
  39752. var keyboard = this.inputs.attached["keyboard"];
  39753. if (keyboard)
  39754. keyboard.keysLeft = value;
  39755. },
  39756. enumerable: true,
  39757. configurable: true
  39758. });
  39759. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39760. get: function () {
  39761. var keyboard = this.inputs.attached["keyboard"];
  39762. if (keyboard)
  39763. return keyboard.keysRight;
  39764. return [];
  39765. },
  39766. set: function (value) {
  39767. var keyboard = this.inputs.attached["keyboard"];
  39768. if (keyboard)
  39769. keyboard.keysRight = value;
  39770. },
  39771. enumerable: true,
  39772. configurable: true
  39773. });
  39774. // Controls
  39775. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39776. this.inputs.attachElement(element, noPreventDefault);
  39777. };
  39778. FreeCamera.prototype.detachControl = function (element) {
  39779. this.inputs.detachElement(element);
  39780. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39781. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39782. };
  39783. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39784. get: function () {
  39785. return this._collisionMask;
  39786. },
  39787. set: function (mask) {
  39788. this._collisionMask = !isNaN(mask) ? mask : -1;
  39789. },
  39790. enumerable: true,
  39791. configurable: true
  39792. });
  39793. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39794. var globalPosition;
  39795. if (this.parent) {
  39796. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39797. }
  39798. else {
  39799. globalPosition = this.position;
  39800. }
  39801. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39802. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39803. if (!this._collider) {
  39804. this._collider = new BABYLON.Collider();
  39805. }
  39806. this._collider._radius = this.ellipsoid;
  39807. this._collider.collisionMask = this._collisionMask;
  39808. //no need for clone, as long as gravity is not on.
  39809. var actualDisplacement = displacement;
  39810. //add gravity to the direction to prevent the dual-collision checking
  39811. if (this.applyGravity) {
  39812. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39813. actualDisplacement = displacement.add(this.getScene().gravity);
  39814. }
  39815. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39816. };
  39817. FreeCamera.prototype._checkInputs = function () {
  39818. if (!this._localDirection) {
  39819. this._localDirection = BABYLON.Vector3.Zero();
  39820. this._transformedDirection = BABYLON.Vector3.Zero();
  39821. }
  39822. this.inputs.checkInputs();
  39823. _super.prototype._checkInputs.call(this);
  39824. };
  39825. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39826. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39827. };
  39828. FreeCamera.prototype._updatePosition = function () {
  39829. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39830. this._collideWithWorld(this.cameraDirection);
  39831. }
  39832. else {
  39833. _super.prototype._updatePosition.call(this);
  39834. }
  39835. };
  39836. FreeCamera.prototype.dispose = function () {
  39837. this.inputs.clear();
  39838. _super.prototype.dispose.call(this);
  39839. };
  39840. FreeCamera.prototype.getClassName = function () {
  39841. return "FreeCamera";
  39842. };
  39843. __decorate([
  39844. BABYLON.serializeAsVector3()
  39845. ], FreeCamera.prototype, "ellipsoid", void 0);
  39846. __decorate([
  39847. BABYLON.serializeAsVector3()
  39848. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39849. __decorate([
  39850. BABYLON.serialize()
  39851. ], FreeCamera.prototype, "checkCollisions", void 0);
  39852. __decorate([
  39853. BABYLON.serialize()
  39854. ], FreeCamera.prototype, "applyGravity", void 0);
  39855. return FreeCamera;
  39856. }(BABYLON.TargetCamera));
  39857. BABYLON.FreeCamera = FreeCamera;
  39858. })(BABYLON || (BABYLON = {}));
  39859. //# sourceMappingURL=babylon.freeCamera.js.map
  39860. var BABYLON;
  39861. (function (BABYLON) {
  39862. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39863. function ArcRotateCameraKeyboardMoveInput() {
  39864. this._keys = new Array();
  39865. this.keysUp = [38];
  39866. this.keysDown = [40];
  39867. this.keysLeft = [37];
  39868. this.keysRight = [39];
  39869. this.keysReset = [220];
  39870. this.panningSensibility = 50.0;
  39871. this.zoomingSensibility = 25.0;
  39872. this.useAltToZoom = true;
  39873. }
  39874. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39875. var _this = this;
  39876. if (this._onCanvasBlurObserver) {
  39877. return;
  39878. }
  39879. this._scene = this.camera.getScene();
  39880. this._engine = this._scene.getEngine();
  39881. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39882. _this._keys = [];
  39883. });
  39884. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39885. var evt = info.event;
  39886. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39887. _this._ctrlPressed = evt.ctrlKey;
  39888. _this._altPressed = evt.altKey;
  39889. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39890. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39891. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39892. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39893. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39894. var index = _this._keys.indexOf(evt.keyCode);
  39895. if (index === -1) {
  39896. _this._keys.push(evt.keyCode);
  39897. }
  39898. if (evt.preventDefault) {
  39899. if (!noPreventDefault) {
  39900. evt.preventDefault();
  39901. }
  39902. }
  39903. }
  39904. }
  39905. else {
  39906. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39907. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39908. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39909. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39910. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39911. var index = _this._keys.indexOf(evt.keyCode);
  39912. if (index >= 0) {
  39913. _this._keys.splice(index, 1);
  39914. }
  39915. if (evt.preventDefault) {
  39916. if (!noPreventDefault) {
  39917. evt.preventDefault();
  39918. }
  39919. }
  39920. }
  39921. }
  39922. });
  39923. };
  39924. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39925. if (this._scene) {
  39926. if (this._onKeyboardObserver) {
  39927. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39928. }
  39929. if (this._onCanvasBlurObserver) {
  39930. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39931. }
  39932. this._onKeyboardObserver = null;
  39933. this._onCanvasBlurObserver = null;
  39934. }
  39935. this._keys = [];
  39936. };
  39937. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39938. if (this._onKeyboardObserver) {
  39939. var camera = this.camera;
  39940. for (var index = 0; index < this._keys.length; index++) {
  39941. var keyCode = this._keys[index];
  39942. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39943. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39944. camera.inertialPanningX -= 1 / this.panningSensibility;
  39945. }
  39946. else {
  39947. camera.inertialAlphaOffset -= 0.01;
  39948. }
  39949. }
  39950. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39951. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39952. camera.inertialPanningY += 1 / this.panningSensibility;
  39953. }
  39954. else if (this._altPressed && this.useAltToZoom) {
  39955. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39956. }
  39957. else {
  39958. camera.inertialBetaOffset -= 0.01;
  39959. }
  39960. }
  39961. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39962. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39963. camera.inertialPanningX += 1 / this.panningSensibility;
  39964. }
  39965. else {
  39966. camera.inertialAlphaOffset += 0.01;
  39967. }
  39968. }
  39969. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39970. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39971. camera.inertialPanningY -= 1 / this.panningSensibility;
  39972. }
  39973. else if (this._altPressed && this.useAltToZoom) {
  39974. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39975. }
  39976. else {
  39977. camera.inertialBetaOffset += 0.01;
  39978. }
  39979. }
  39980. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39981. camera.restoreState();
  39982. }
  39983. }
  39984. }
  39985. };
  39986. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39987. return "ArcRotateCameraKeyboardMoveInput";
  39988. };
  39989. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39990. return "keyboard";
  39991. };
  39992. __decorate([
  39993. BABYLON.serialize()
  39994. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39995. __decorate([
  39996. BABYLON.serialize()
  39997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39998. __decorate([
  39999. BABYLON.serialize()
  40000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40001. __decorate([
  40002. BABYLON.serialize()
  40003. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40004. __decorate([
  40005. BABYLON.serialize()
  40006. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  40007. __decorate([
  40008. BABYLON.serialize()
  40009. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  40010. __decorate([
  40011. BABYLON.serialize()
  40012. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  40013. __decorate([
  40014. BABYLON.serialize()
  40015. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  40016. return ArcRotateCameraKeyboardMoveInput;
  40017. }());
  40018. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  40019. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  40020. })(BABYLON || (BABYLON = {}));
  40021. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  40022. var BABYLON;
  40023. (function (BABYLON) {
  40024. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  40025. function ArcRotateCameraMouseWheelInput() {
  40026. this.wheelPrecision = 3.0;
  40027. /**
  40028. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  40029. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  40030. */
  40031. this.wheelDeltaPercentage = 0;
  40032. }
  40033. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  40034. var _this = this;
  40035. this._wheel = function (p, s) {
  40036. //sanity check - this should be a PointerWheel event.
  40037. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  40038. return;
  40039. var event = p.event;
  40040. var delta = 0;
  40041. if (event.wheelDelta) {
  40042. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  40043. }
  40044. else if (event.detail) {
  40045. delta = -event.detail / _this.wheelPrecision;
  40046. }
  40047. if (delta)
  40048. _this.camera.inertialRadiusOffset += delta;
  40049. if (event.preventDefault) {
  40050. if (!noPreventDefault) {
  40051. event.preventDefault();
  40052. }
  40053. }
  40054. };
  40055. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  40056. };
  40057. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  40058. if (this._observer && element) {
  40059. this.camera.getScene().onPointerObservable.remove(this._observer);
  40060. this._observer = null;
  40061. this._wheel = null;
  40062. }
  40063. };
  40064. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  40065. return "ArcRotateCameraMouseWheelInput";
  40066. };
  40067. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  40068. return "mousewheel";
  40069. };
  40070. __decorate([
  40071. BABYLON.serialize()
  40072. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  40073. __decorate([
  40074. BABYLON.serialize()
  40075. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  40076. return ArcRotateCameraMouseWheelInput;
  40077. }());
  40078. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  40079. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  40080. })(BABYLON || (BABYLON = {}));
  40081. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  40082. var BABYLON;
  40083. (function (BABYLON) {
  40084. var ArcRotateCameraPointersInput = /** @class */ (function () {
  40085. function ArcRotateCameraPointersInput() {
  40086. this.buttons = [0, 1, 2];
  40087. this.angularSensibilityX = 1000.0;
  40088. this.angularSensibilityY = 1000.0;
  40089. this.pinchPrecision = 12.0;
  40090. /**
  40091. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  40092. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  40093. */
  40094. this.pinchDeltaPercentage = 0;
  40095. this.panningSensibility = 1000.0;
  40096. this.multiTouchPanning = true;
  40097. this.multiTouchPanAndZoom = true;
  40098. this._isPanClick = false;
  40099. this.pinchInwards = true;
  40100. }
  40101. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  40102. var _this = this;
  40103. var engine = this.camera.getEngine();
  40104. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  40105. var pointA = null;
  40106. var pointB = null;
  40107. var previousPinchSquaredDistance = 0;
  40108. var initialDistance = 0;
  40109. var twoFingerActivityCount = 0;
  40110. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  40111. this._pointerInput = function (p, s) {
  40112. var evt = p.event;
  40113. var isTouch = p.event.pointerType === "touch";
  40114. if (engine.isInVRExclusivePointerMode) {
  40115. return;
  40116. }
  40117. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40118. return;
  40119. }
  40120. var srcElement = (evt.srcElement || evt.target);
  40121. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40122. try {
  40123. srcElement.setPointerCapture(evt.pointerId);
  40124. }
  40125. catch (e) {
  40126. //Nothing to do with the error. Execution will continue.
  40127. }
  40128. // Manage panning with pan button click
  40129. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40130. // manage pointers
  40131. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40132. if (pointA === null) {
  40133. pointA = cacheSoloPointer;
  40134. }
  40135. else if (pointB === null) {
  40136. pointB = cacheSoloPointer;
  40137. }
  40138. if (!noPreventDefault) {
  40139. evt.preventDefault();
  40140. element.focus();
  40141. }
  40142. }
  40143. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40144. _this.camera.restoreState();
  40145. }
  40146. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40147. try {
  40148. srcElement.releasePointerCapture(evt.pointerId);
  40149. }
  40150. catch (e) {
  40151. //Nothing to do with the error.
  40152. }
  40153. cacheSoloPointer = null;
  40154. previousPinchSquaredDistance = 0;
  40155. previousMultiTouchPanPosition.isPaning = false;
  40156. previousMultiTouchPanPosition.isPinching = false;
  40157. twoFingerActivityCount = 0;
  40158. initialDistance = 0;
  40159. if (!isTouch) {
  40160. pointB = null; // Mouse and pen are mono pointer
  40161. }
  40162. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40163. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40164. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40165. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40166. if (engine.badOS) {
  40167. pointA = pointB = null;
  40168. }
  40169. else {
  40170. //only remove the impacted pointer in case of multitouch allowing on most
  40171. //platforms switching from rotate to zoom and pan seamlessly.
  40172. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40173. pointA = pointB;
  40174. pointB = null;
  40175. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40176. }
  40177. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40178. pointB = null;
  40179. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40180. }
  40181. else {
  40182. pointA = pointB = null;
  40183. }
  40184. }
  40185. if (!noPreventDefault) {
  40186. evt.preventDefault();
  40187. }
  40188. }
  40189. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40190. if (!noPreventDefault) {
  40191. evt.preventDefault();
  40192. }
  40193. // One button down
  40194. if (pointA && pointB === null && cacheSoloPointer) {
  40195. if (_this.panningSensibility !== 0 &&
  40196. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40197. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40198. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40199. }
  40200. else {
  40201. var offsetX = evt.clientX - cacheSoloPointer.x;
  40202. var offsetY = evt.clientY - cacheSoloPointer.y;
  40203. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40204. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40205. }
  40206. cacheSoloPointer.x = evt.clientX;
  40207. cacheSoloPointer.y = evt.clientY;
  40208. }
  40209. else if (pointA && pointB) {
  40210. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40211. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40212. ed.x = evt.clientX;
  40213. ed.y = evt.clientY;
  40214. var direction = _this.pinchInwards ? 1 : -1;
  40215. var distX = pointA.x - pointB.x;
  40216. var distY = pointA.y - pointB.y;
  40217. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40218. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40219. if (previousPinchSquaredDistance === 0) {
  40220. initialDistance = pinchDistance;
  40221. previousPinchSquaredDistance = pinchSquaredDistance;
  40222. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40223. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40224. return;
  40225. }
  40226. if (_this.multiTouchPanAndZoom) {
  40227. if (_this.pinchDeltaPercentage) {
  40228. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40229. }
  40230. else {
  40231. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40232. (_this.pinchPrecision *
  40233. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40234. direction);
  40235. }
  40236. if (_this.panningSensibility !== 0) {
  40237. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40238. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40239. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40240. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40241. previousMultiTouchPanPosition.x = pointersCenterX;
  40242. previousMultiTouchPanPosition.y = pointersCenterY;
  40243. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40244. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40245. }
  40246. }
  40247. else {
  40248. twoFingerActivityCount++;
  40249. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40250. if (_this.pinchDeltaPercentage) {
  40251. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40252. }
  40253. else {
  40254. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40255. (_this.pinchPrecision *
  40256. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40257. direction);
  40258. }
  40259. previousMultiTouchPanPosition.isPaning = false;
  40260. previousMultiTouchPanPosition.isPinching = true;
  40261. }
  40262. else {
  40263. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40264. if (!previousMultiTouchPanPosition.isPaning) {
  40265. previousMultiTouchPanPosition.isPaning = true;
  40266. previousMultiTouchPanPosition.isPinching = false;
  40267. previousMultiTouchPanPosition.x = ed.x;
  40268. previousMultiTouchPanPosition.y = ed.y;
  40269. return;
  40270. }
  40271. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40272. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40273. }
  40274. }
  40275. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40276. previousMultiTouchPanPosition.x = ed.x;
  40277. previousMultiTouchPanPosition.y = ed.y;
  40278. }
  40279. }
  40280. previousPinchSquaredDistance = pinchSquaredDistance;
  40281. }
  40282. }
  40283. };
  40284. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40285. this._onContextMenu = function (evt) {
  40286. evt.preventDefault();
  40287. };
  40288. if (!this.camera._useCtrlForPanning) {
  40289. element.addEventListener("contextmenu", this._onContextMenu, false);
  40290. }
  40291. this._onLostFocus = function () {
  40292. //this._keys = [];
  40293. pointA = pointB = null;
  40294. previousPinchSquaredDistance = 0;
  40295. previousMultiTouchPanPosition.isPaning = false;
  40296. previousMultiTouchPanPosition.isPinching = false;
  40297. twoFingerActivityCount = 0;
  40298. cacheSoloPointer = null;
  40299. initialDistance = 0;
  40300. };
  40301. this._onMouseMove = function (evt) {
  40302. if (!engine.isPointerLock) {
  40303. return;
  40304. }
  40305. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40306. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40307. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40308. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40309. if (!noPreventDefault) {
  40310. evt.preventDefault();
  40311. }
  40312. };
  40313. this._onGestureStart = function (e) {
  40314. if (window.MSGesture === undefined) {
  40315. return;
  40316. }
  40317. if (!_this._MSGestureHandler) {
  40318. _this._MSGestureHandler = new MSGesture();
  40319. _this._MSGestureHandler.target = element;
  40320. }
  40321. _this._MSGestureHandler.addPointer(e.pointerId);
  40322. };
  40323. this._onGesture = function (e) {
  40324. _this.camera.radius *= e.scale;
  40325. if (e.preventDefault) {
  40326. if (!noPreventDefault) {
  40327. e.stopPropagation();
  40328. e.preventDefault();
  40329. }
  40330. }
  40331. };
  40332. element.addEventListener("mousemove", this._onMouseMove, false);
  40333. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40334. element.addEventListener("MSGestureChange", this._onGesture, false);
  40335. BABYLON.Tools.RegisterTopRootEvents([
  40336. { name: "blur", handler: this._onLostFocus }
  40337. ]);
  40338. };
  40339. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40340. if (this._onLostFocus) {
  40341. BABYLON.Tools.UnregisterTopRootEvents([
  40342. { name: "blur", handler: this._onLostFocus }
  40343. ]);
  40344. }
  40345. if (element && this._observer) {
  40346. this.camera.getScene().onPointerObservable.remove(this._observer);
  40347. this._observer = null;
  40348. if (this._onContextMenu) {
  40349. element.removeEventListener("contextmenu", this._onContextMenu);
  40350. }
  40351. if (this._onMouseMove) {
  40352. element.removeEventListener("mousemove", this._onMouseMove);
  40353. }
  40354. if (this._onGestureStart) {
  40355. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40356. }
  40357. if (this._onGesture) {
  40358. element.removeEventListener("MSGestureChange", this._onGesture);
  40359. }
  40360. this._isPanClick = false;
  40361. this.pinchInwards = true;
  40362. this._onMouseMove = null;
  40363. this._onGestureStart = null;
  40364. this._onGesture = null;
  40365. this._MSGestureHandler = null;
  40366. this._onLostFocus = null;
  40367. this._onContextMenu = null;
  40368. }
  40369. };
  40370. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40371. return "ArcRotateCameraPointersInput";
  40372. };
  40373. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40374. return "pointers";
  40375. };
  40376. __decorate([
  40377. BABYLON.serialize()
  40378. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40379. __decorate([
  40380. BABYLON.serialize()
  40381. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40382. __decorate([
  40383. BABYLON.serialize()
  40384. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40385. __decorate([
  40386. BABYLON.serialize()
  40387. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40388. __decorate([
  40389. BABYLON.serialize()
  40390. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40391. __decorate([
  40392. BABYLON.serialize()
  40393. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40394. __decorate([
  40395. BABYLON.serialize()
  40396. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40397. __decorate([
  40398. BABYLON.serialize()
  40399. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40400. return ArcRotateCameraPointersInput;
  40401. }());
  40402. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40403. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40404. })(BABYLON || (BABYLON = {}));
  40405. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40406. var BABYLON;
  40407. (function (BABYLON) {
  40408. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40409. __extends(ArcRotateCameraInputsManager, _super);
  40410. function ArcRotateCameraInputsManager(camera) {
  40411. return _super.call(this, camera) || this;
  40412. }
  40413. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40414. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40415. return this;
  40416. };
  40417. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40418. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40419. return this;
  40420. };
  40421. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40422. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40423. return this;
  40424. };
  40425. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40426. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40427. return this;
  40428. };
  40429. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40430. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40431. return this;
  40432. };
  40433. return ArcRotateCameraInputsManager;
  40434. }(BABYLON.CameraInputsManager));
  40435. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40436. })(BABYLON || (BABYLON = {}));
  40437. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40438. var BABYLON;
  40439. (function (BABYLON) {
  40440. var ArcRotateCamera = /** @class */ (function (_super) {
  40441. __extends(ArcRotateCamera, _super);
  40442. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40443. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40444. _this.inertialAlphaOffset = 0;
  40445. _this.inertialBetaOffset = 0;
  40446. _this.inertialRadiusOffset = 0;
  40447. _this.lowerAlphaLimit = null;
  40448. _this.upperAlphaLimit = null;
  40449. _this.lowerBetaLimit = 0.01;
  40450. _this.upperBetaLimit = Math.PI;
  40451. _this.lowerRadiusLimit = null;
  40452. _this.upperRadiusLimit = null;
  40453. _this.inertialPanningX = 0;
  40454. _this.inertialPanningY = 0;
  40455. _this.pinchToPanMaxDistance = 20;
  40456. _this.panningDistanceLimit = null;
  40457. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40458. _this.panningInertia = 0.9;
  40459. //-- end properties for backward compatibility for inputs
  40460. _this.zoomOnFactor = 1;
  40461. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40462. _this.allowUpsideDown = true;
  40463. _this._viewMatrix = new BABYLON.Matrix();
  40464. // Panning
  40465. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40466. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40467. _this.checkCollisions = false;
  40468. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40469. _this._previousPosition = BABYLON.Vector3.Zero();
  40470. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40471. _this._newPosition = BABYLON.Vector3.Zero();
  40472. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40473. if (collidedMesh === void 0) { collidedMesh = null; }
  40474. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40475. newPosition.multiplyInPlace(_this._collider._radius);
  40476. }
  40477. if (!collidedMesh) {
  40478. _this._previousPosition.copyFrom(_this.position);
  40479. }
  40480. else {
  40481. _this.setPosition(newPosition);
  40482. if (_this.onCollide) {
  40483. _this.onCollide(collidedMesh);
  40484. }
  40485. }
  40486. // Recompute because of constraints
  40487. var cosa = Math.cos(_this.alpha);
  40488. var sina = Math.sin(_this.alpha);
  40489. var cosb = Math.cos(_this.beta);
  40490. var sinb = Math.sin(_this.beta);
  40491. if (sinb === 0) {
  40492. sinb = 0.0001;
  40493. }
  40494. var target = _this._getTargetPosition();
  40495. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40496. _this.position.copyFrom(_this._newPosition);
  40497. var up = _this.upVector;
  40498. if (_this.allowUpsideDown && _this.beta < 0) {
  40499. up = up.clone();
  40500. up = up.negate();
  40501. }
  40502. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40503. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40504. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40505. _this._collisionTriggered = false;
  40506. };
  40507. _this._target = BABYLON.Vector3.Zero();
  40508. if (target) {
  40509. _this.setTarget(target);
  40510. }
  40511. _this.alpha = alpha;
  40512. _this.beta = beta;
  40513. _this.radius = radius;
  40514. _this.getViewMatrix();
  40515. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40516. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40517. return _this;
  40518. }
  40519. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40520. get: function () {
  40521. return this._target;
  40522. },
  40523. set: function (value) {
  40524. this.setTarget(value);
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40530. //-- begin properties for backward compatibility for inputs
  40531. get: function () {
  40532. var pointers = this.inputs.attached["pointers"];
  40533. if (pointers)
  40534. return pointers.angularSensibilityX;
  40535. return 0;
  40536. },
  40537. set: function (value) {
  40538. var pointers = this.inputs.attached["pointers"];
  40539. if (pointers) {
  40540. pointers.angularSensibilityX = value;
  40541. }
  40542. },
  40543. enumerable: true,
  40544. configurable: true
  40545. });
  40546. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40547. get: function () {
  40548. var pointers = this.inputs.attached["pointers"];
  40549. if (pointers)
  40550. return pointers.angularSensibilityY;
  40551. return 0;
  40552. },
  40553. set: function (value) {
  40554. var pointers = this.inputs.attached["pointers"];
  40555. if (pointers) {
  40556. pointers.angularSensibilityY = value;
  40557. }
  40558. },
  40559. enumerable: true,
  40560. configurable: true
  40561. });
  40562. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40563. get: function () {
  40564. var pointers = this.inputs.attached["pointers"];
  40565. if (pointers)
  40566. return pointers.pinchPrecision;
  40567. return 0;
  40568. },
  40569. set: function (value) {
  40570. var pointers = this.inputs.attached["pointers"];
  40571. if (pointers) {
  40572. pointers.pinchPrecision = value;
  40573. }
  40574. },
  40575. enumerable: true,
  40576. configurable: true
  40577. });
  40578. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40579. get: function () {
  40580. var pointers = this.inputs.attached["pointers"];
  40581. if (pointers)
  40582. return pointers.pinchDeltaPercentage;
  40583. return 0;
  40584. },
  40585. set: function (value) {
  40586. var pointers = this.inputs.attached["pointers"];
  40587. if (pointers) {
  40588. pointers.pinchDeltaPercentage = value;
  40589. }
  40590. },
  40591. enumerable: true,
  40592. configurable: true
  40593. });
  40594. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40595. get: function () {
  40596. var pointers = this.inputs.attached["pointers"];
  40597. if (pointers)
  40598. return pointers.panningSensibility;
  40599. return 0;
  40600. },
  40601. set: function (value) {
  40602. var pointers = this.inputs.attached["pointers"];
  40603. if (pointers) {
  40604. pointers.panningSensibility = value;
  40605. }
  40606. },
  40607. enumerable: true,
  40608. configurable: true
  40609. });
  40610. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40611. get: function () {
  40612. var keyboard = this.inputs.attached["keyboard"];
  40613. if (keyboard)
  40614. return keyboard.keysUp;
  40615. return [];
  40616. },
  40617. set: function (value) {
  40618. var keyboard = this.inputs.attached["keyboard"];
  40619. if (keyboard)
  40620. keyboard.keysUp = value;
  40621. },
  40622. enumerable: true,
  40623. configurable: true
  40624. });
  40625. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40626. get: function () {
  40627. var keyboard = this.inputs.attached["keyboard"];
  40628. if (keyboard)
  40629. return keyboard.keysDown;
  40630. return [];
  40631. },
  40632. set: function (value) {
  40633. var keyboard = this.inputs.attached["keyboard"];
  40634. if (keyboard)
  40635. keyboard.keysDown = value;
  40636. },
  40637. enumerable: true,
  40638. configurable: true
  40639. });
  40640. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40641. get: function () {
  40642. var keyboard = this.inputs.attached["keyboard"];
  40643. if (keyboard)
  40644. return keyboard.keysLeft;
  40645. return [];
  40646. },
  40647. set: function (value) {
  40648. var keyboard = this.inputs.attached["keyboard"];
  40649. if (keyboard)
  40650. keyboard.keysLeft = value;
  40651. },
  40652. enumerable: true,
  40653. configurable: true
  40654. });
  40655. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40656. get: function () {
  40657. var keyboard = this.inputs.attached["keyboard"];
  40658. if (keyboard)
  40659. return keyboard.keysRight;
  40660. return [];
  40661. },
  40662. set: function (value) {
  40663. var keyboard = this.inputs.attached["keyboard"];
  40664. if (keyboard)
  40665. keyboard.keysRight = value;
  40666. },
  40667. enumerable: true,
  40668. configurable: true
  40669. });
  40670. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40671. get: function () {
  40672. var mousewheel = this.inputs.attached["mousewheel"];
  40673. if (mousewheel)
  40674. return mousewheel.wheelPrecision;
  40675. return 0;
  40676. },
  40677. set: function (value) {
  40678. var mousewheel = this.inputs.attached["mousewheel"];
  40679. if (mousewheel)
  40680. mousewheel.wheelPrecision = value;
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40686. get: function () {
  40687. var mousewheel = this.inputs.attached["mousewheel"];
  40688. if (mousewheel)
  40689. return mousewheel.wheelDeltaPercentage;
  40690. return 0;
  40691. },
  40692. set: function (value) {
  40693. var mousewheel = this.inputs.attached["mousewheel"];
  40694. if (mousewheel)
  40695. mousewheel.wheelDeltaPercentage = value;
  40696. },
  40697. enumerable: true,
  40698. configurable: true
  40699. });
  40700. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40701. get: function () {
  40702. return this._bouncingBehavior;
  40703. },
  40704. enumerable: true,
  40705. configurable: true
  40706. });
  40707. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40708. get: function () {
  40709. return this._bouncingBehavior != null;
  40710. },
  40711. set: function (value) {
  40712. if (value === this.useBouncingBehavior) {
  40713. return;
  40714. }
  40715. if (value) {
  40716. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40717. this.addBehavior(this._bouncingBehavior);
  40718. }
  40719. else if (this._bouncingBehavior) {
  40720. this.removeBehavior(this._bouncingBehavior);
  40721. this._bouncingBehavior = null;
  40722. }
  40723. },
  40724. enumerable: true,
  40725. configurable: true
  40726. });
  40727. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40728. get: function () {
  40729. return this._framingBehavior;
  40730. },
  40731. enumerable: true,
  40732. configurable: true
  40733. });
  40734. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40735. get: function () {
  40736. return this._framingBehavior != null;
  40737. },
  40738. set: function (value) {
  40739. if (value === this.useFramingBehavior) {
  40740. return;
  40741. }
  40742. if (value) {
  40743. this._framingBehavior = new BABYLON.FramingBehavior();
  40744. this.addBehavior(this._framingBehavior);
  40745. }
  40746. else if (this._framingBehavior) {
  40747. this.removeBehavior(this._framingBehavior);
  40748. this._framingBehavior = null;
  40749. }
  40750. },
  40751. enumerable: true,
  40752. configurable: true
  40753. });
  40754. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40755. get: function () {
  40756. return this._autoRotationBehavior;
  40757. },
  40758. enumerable: true,
  40759. configurable: true
  40760. });
  40761. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40762. get: function () {
  40763. return this._autoRotationBehavior != null;
  40764. },
  40765. set: function (value) {
  40766. if (value === this.useAutoRotationBehavior) {
  40767. return;
  40768. }
  40769. if (value) {
  40770. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40771. this.addBehavior(this._autoRotationBehavior);
  40772. }
  40773. else if (this._autoRotationBehavior) {
  40774. this.removeBehavior(this._autoRotationBehavior);
  40775. this._autoRotationBehavior = null;
  40776. }
  40777. },
  40778. enumerable: true,
  40779. configurable: true
  40780. });
  40781. // Cache
  40782. ArcRotateCamera.prototype._initCache = function () {
  40783. _super.prototype._initCache.call(this);
  40784. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40785. this._cache.alpha = undefined;
  40786. this._cache.beta = undefined;
  40787. this._cache.radius = undefined;
  40788. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40789. };
  40790. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40791. if (!ignoreParentClass) {
  40792. _super.prototype._updateCache.call(this);
  40793. }
  40794. this._cache._target.copyFrom(this._getTargetPosition());
  40795. this._cache.alpha = this.alpha;
  40796. this._cache.beta = this.beta;
  40797. this._cache.radius = this.radius;
  40798. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40799. };
  40800. ArcRotateCamera.prototype._getTargetPosition = function () {
  40801. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40802. var pos = this._targetHost.getAbsolutePosition();
  40803. if (this._targetBoundingCenter) {
  40804. pos.addToRef(this._targetBoundingCenter, this._target);
  40805. }
  40806. else {
  40807. this._target.copyFrom(pos);
  40808. }
  40809. }
  40810. var lockedTargetPosition = this._getLockedTargetPosition();
  40811. if (lockedTargetPosition) {
  40812. return lockedTargetPosition;
  40813. }
  40814. return this._target;
  40815. };
  40816. ArcRotateCamera.prototype.storeState = function () {
  40817. this._storedAlpha = this.alpha;
  40818. this._storedBeta = this.beta;
  40819. this._storedRadius = this.radius;
  40820. this._storedTarget = this._getTargetPosition().clone();
  40821. return _super.prototype.storeState.call(this);
  40822. };
  40823. /**
  40824. * Restored camera state. You must call storeState() first
  40825. */
  40826. ArcRotateCamera.prototype._restoreStateValues = function () {
  40827. if (!_super.prototype._restoreStateValues.call(this)) {
  40828. return false;
  40829. }
  40830. this.alpha = this._storedAlpha;
  40831. this.beta = this._storedBeta;
  40832. this.radius = this._storedRadius;
  40833. this.setTarget(this._storedTarget.clone());
  40834. this.inertialAlphaOffset = 0;
  40835. this.inertialBetaOffset = 0;
  40836. this.inertialRadiusOffset = 0;
  40837. this.inertialPanningX = 0;
  40838. this.inertialPanningY = 0;
  40839. return true;
  40840. };
  40841. // Synchronized
  40842. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40843. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40844. return false;
  40845. return this._cache._target.equals(this._getTargetPosition())
  40846. && this._cache.alpha === this.alpha
  40847. && this._cache.beta === this.beta
  40848. && this._cache.radius === this.radius
  40849. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40850. };
  40851. // Methods
  40852. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40853. var _this = this;
  40854. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40855. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40856. this._useCtrlForPanning = useCtrlForPanning;
  40857. this._panningMouseButton = panningMouseButton;
  40858. this.inputs.attachElement(element, noPreventDefault);
  40859. this._reset = function () {
  40860. _this.inertialAlphaOffset = 0;
  40861. _this.inertialBetaOffset = 0;
  40862. _this.inertialRadiusOffset = 0;
  40863. _this.inertialPanningX = 0;
  40864. _this.inertialPanningY = 0;
  40865. };
  40866. };
  40867. ArcRotateCamera.prototype.detachControl = function (element) {
  40868. this.inputs.detachElement(element);
  40869. if (this._reset) {
  40870. this._reset();
  40871. }
  40872. };
  40873. ArcRotateCamera.prototype._checkInputs = function () {
  40874. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40875. if (this._collisionTriggered) {
  40876. return;
  40877. }
  40878. this.inputs.checkInputs();
  40879. // Inertia
  40880. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40881. if (this.getScene().useRightHandedSystem) {
  40882. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40883. }
  40884. else {
  40885. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40886. }
  40887. this.beta += this.inertialBetaOffset;
  40888. this.radius -= this.inertialRadiusOffset;
  40889. this.inertialAlphaOffset *= this.inertia;
  40890. this.inertialBetaOffset *= this.inertia;
  40891. this.inertialRadiusOffset *= this.inertia;
  40892. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40893. this.inertialAlphaOffset = 0;
  40894. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40895. this.inertialBetaOffset = 0;
  40896. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40897. this.inertialRadiusOffset = 0;
  40898. }
  40899. // Panning inertia
  40900. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40901. if (!this._localDirection) {
  40902. this._localDirection = BABYLON.Vector3.Zero();
  40903. this._transformedDirection = BABYLON.Vector3.Zero();
  40904. }
  40905. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40906. this._localDirection.multiplyInPlace(this.panningAxis);
  40907. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40908. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40909. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40910. if (!this.panningAxis.y) {
  40911. this._transformedDirection.y = 0;
  40912. }
  40913. if (!this._targetHost) {
  40914. if (this.panningDistanceLimit) {
  40915. this._transformedDirection.addInPlace(this._target);
  40916. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40917. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40918. this._target.copyFrom(this._transformedDirection);
  40919. }
  40920. }
  40921. else {
  40922. this._target.addInPlace(this._transformedDirection);
  40923. }
  40924. }
  40925. this.inertialPanningX *= this.panningInertia;
  40926. this.inertialPanningY *= this.panningInertia;
  40927. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40928. this.inertialPanningX = 0;
  40929. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40930. this.inertialPanningY = 0;
  40931. }
  40932. // Limits
  40933. this._checkLimits();
  40934. _super.prototype._checkInputs.call(this);
  40935. };
  40936. ArcRotateCamera.prototype._checkLimits = function () {
  40937. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40938. if (this.allowUpsideDown && this.beta > Math.PI) {
  40939. this.beta = this.beta - (2 * Math.PI);
  40940. }
  40941. }
  40942. else {
  40943. if (this.beta < this.lowerBetaLimit) {
  40944. this.beta = this.lowerBetaLimit;
  40945. }
  40946. }
  40947. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40948. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40949. this.beta = this.beta + (2 * Math.PI);
  40950. }
  40951. }
  40952. else {
  40953. if (this.beta > this.upperBetaLimit) {
  40954. this.beta = this.upperBetaLimit;
  40955. }
  40956. }
  40957. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40958. this.alpha = this.lowerAlphaLimit;
  40959. }
  40960. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40961. this.alpha = this.upperAlphaLimit;
  40962. }
  40963. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40964. this.radius = this.lowerRadiusLimit;
  40965. }
  40966. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40967. this.radius = this.upperRadiusLimit;
  40968. }
  40969. };
  40970. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40971. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40972. this.radius = radiusv3.length();
  40973. if (this.radius === 0) {
  40974. this.radius = 0.0001; // Just to avoid division by zero
  40975. }
  40976. // Alpha
  40977. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40978. if (radiusv3.z < 0) {
  40979. this.alpha = 2 * Math.PI - this.alpha;
  40980. }
  40981. // Beta
  40982. this.beta = Math.acos(radiusv3.y / this.radius);
  40983. this._checkLimits();
  40984. };
  40985. ArcRotateCamera.prototype.setPosition = function (position) {
  40986. if (this.position.equals(position)) {
  40987. return;
  40988. }
  40989. this.position.copyFrom(position);
  40990. this.rebuildAnglesAndRadius();
  40991. };
  40992. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40993. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40994. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40995. if (target.getBoundingInfo) {
  40996. if (toBoundingCenter) {
  40997. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40998. }
  40999. else {
  41000. this._targetBoundingCenter = null;
  41001. }
  41002. this._targetHost = target;
  41003. this._target = this._getTargetPosition();
  41004. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  41005. }
  41006. else {
  41007. var newTarget = target;
  41008. var currentTarget = this._getTargetPosition();
  41009. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  41010. return;
  41011. }
  41012. this._targetHost = null;
  41013. this._target = newTarget;
  41014. this._targetBoundingCenter = null;
  41015. this.onMeshTargetChangedObservable.notifyObservers(null);
  41016. }
  41017. this.rebuildAnglesAndRadius();
  41018. };
  41019. ArcRotateCamera.prototype._getViewMatrix = function () {
  41020. // Compute
  41021. var cosa = Math.cos(this.alpha);
  41022. var sina = Math.sin(this.alpha);
  41023. var cosb = Math.cos(this.beta);
  41024. var sinb = Math.sin(this.beta);
  41025. if (sinb === 0) {
  41026. sinb = 0.0001;
  41027. }
  41028. var target = this._getTargetPosition();
  41029. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  41030. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  41031. if (!this._collider) {
  41032. this._collider = new BABYLON.Collider();
  41033. }
  41034. this._collider._radius = this.collisionRadius;
  41035. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  41036. this._collisionTriggered = true;
  41037. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41038. }
  41039. else {
  41040. this.position.copyFrom(this._newPosition);
  41041. var up = this.upVector;
  41042. if (this.allowUpsideDown && sinb < 0) {
  41043. up = up.clone();
  41044. up = up.negate();
  41045. }
  41046. if (this.getScene().useRightHandedSystem) {
  41047. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  41048. }
  41049. else {
  41050. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  41051. }
  41052. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  41053. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  41054. }
  41055. this._currentTarget = target;
  41056. return this._viewMatrix;
  41057. };
  41058. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  41059. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41060. meshes = meshes || this.getScene().meshes;
  41061. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  41062. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  41063. this.radius = distance * this.zoomOnFactor;
  41064. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  41065. };
  41066. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  41067. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41068. var meshesOrMinMaxVector;
  41069. var distance;
  41070. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  41071. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  41072. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  41073. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  41074. }
  41075. else {
  41076. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  41077. meshesOrMinMaxVector = minMaxVectorAndDistance;
  41078. distance = minMaxVectorAndDistance.distance;
  41079. }
  41080. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  41081. if (!doNotUpdateMaxZ) {
  41082. this.maxZ = distance * 2;
  41083. }
  41084. };
  41085. /**
  41086. * @override
  41087. * Override Camera.createRigCamera
  41088. */
  41089. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41090. var alphaShift = 0;
  41091. switch (this.cameraRigMode) {
  41092. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41093. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41094. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41095. case BABYLON.Camera.RIG_MODE_VR:
  41096. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  41097. break;
  41098. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41099. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  41100. break;
  41101. }
  41102. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  41103. rigCam._cameraRigParams = {};
  41104. return rigCam;
  41105. };
  41106. /**
  41107. * @override
  41108. * Override Camera._updateRigCameras
  41109. */
  41110. ArcRotateCamera.prototype._updateRigCameras = function () {
  41111. var camLeft = this._rigCameras[0];
  41112. var camRight = this._rigCameras[1];
  41113. camLeft.beta = camRight.beta = this.beta;
  41114. camLeft.radius = camRight.radius = this.radius;
  41115. switch (this.cameraRigMode) {
  41116. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41117. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41118. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41119. case BABYLON.Camera.RIG_MODE_VR:
  41120. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41121. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41122. break;
  41123. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41124. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41125. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41126. break;
  41127. }
  41128. _super.prototype._updateRigCameras.call(this);
  41129. };
  41130. ArcRotateCamera.prototype.dispose = function () {
  41131. this.inputs.clear();
  41132. _super.prototype.dispose.call(this);
  41133. };
  41134. ArcRotateCamera.prototype.getClassName = function () {
  41135. return "ArcRotateCamera";
  41136. };
  41137. __decorate([
  41138. BABYLON.serialize()
  41139. ], ArcRotateCamera.prototype, "alpha", void 0);
  41140. __decorate([
  41141. BABYLON.serialize()
  41142. ], ArcRotateCamera.prototype, "beta", void 0);
  41143. __decorate([
  41144. BABYLON.serialize()
  41145. ], ArcRotateCamera.prototype, "radius", void 0);
  41146. __decorate([
  41147. BABYLON.serializeAsVector3("target")
  41148. ], ArcRotateCamera.prototype, "_target", void 0);
  41149. __decorate([
  41150. BABYLON.serialize()
  41151. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41152. __decorate([
  41153. BABYLON.serialize()
  41154. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41155. __decorate([
  41156. BABYLON.serialize()
  41157. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41158. __decorate([
  41159. BABYLON.serialize()
  41160. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41161. __decorate([
  41162. BABYLON.serialize()
  41163. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41164. __decorate([
  41165. BABYLON.serialize()
  41166. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41167. __decorate([
  41168. BABYLON.serialize()
  41169. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41170. __decorate([
  41171. BABYLON.serialize()
  41172. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41173. __decorate([
  41174. BABYLON.serialize()
  41175. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41176. __decorate([
  41177. BABYLON.serialize()
  41178. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41179. __decorate([
  41180. BABYLON.serialize()
  41181. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41182. __decorate([
  41183. BABYLON.serialize()
  41184. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41185. __decorate([
  41186. BABYLON.serialize()
  41187. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41188. __decorate([
  41189. BABYLON.serializeAsVector3()
  41190. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41191. __decorate([
  41192. BABYLON.serialize()
  41193. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41194. __decorate([
  41195. BABYLON.serialize()
  41196. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41197. __decorate([
  41198. BABYLON.serialize()
  41199. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41200. return ArcRotateCamera;
  41201. }(BABYLON.TargetCamera));
  41202. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41203. })(BABYLON || (BABYLON = {}));
  41204. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41205. var BABYLON;
  41206. (function (BABYLON) {
  41207. var HemisphericLight = /** @class */ (function (_super) {
  41208. __extends(HemisphericLight, _super);
  41209. /**
  41210. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41211. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41212. * The HemisphericLight can't cast shadows.
  41213. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41214. */
  41215. function HemisphericLight(name, direction, scene) {
  41216. var _this = _super.call(this, name, scene) || this;
  41217. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41218. _this.direction = direction || BABYLON.Vector3.Up();
  41219. return _this;
  41220. }
  41221. HemisphericLight.prototype._buildUniformLayout = function () {
  41222. this._uniformBuffer.addUniform("vLightData", 4);
  41223. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41224. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41225. this._uniformBuffer.addUniform("vLightGround", 3);
  41226. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41227. this._uniformBuffer.addUniform("depthValues", 2);
  41228. this._uniformBuffer.create();
  41229. };
  41230. /**
  41231. * Returns the string "HemisphericLight".
  41232. */
  41233. HemisphericLight.prototype.getClassName = function () {
  41234. return "HemisphericLight";
  41235. };
  41236. /**
  41237. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41238. * Returns the updated direction.
  41239. */
  41240. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41241. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41242. return this.direction;
  41243. };
  41244. HemisphericLight.prototype.getShadowGenerator = function () {
  41245. return null;
  41246. };
  41247. /**
  41248. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41249. * Returns the HemisphericLight.
  41250. */
  41251. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41252. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41253. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41254. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41255. return this;
  41256. };
  41257. HemisphericLight.prototype._getWorldMatrix = function () {
  41258. if (!this._worldMatrix) {
  41259. this._worldMatrix = BABYLON.Matrix.Identity();
  41260. }
  41261. return this._worldMatrix;
  41262. };
  41263. /**
  41264. * Returns the integer 3.
  41265. */
  41266. HemisphericLight.prototype.getTypeID = function () {
  41267. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41268. };
  41269. __decorate([
  41270. BABYLON.serializeAsColor3()
  41271. ], HemisphericLight.prototype, "groundColor", void 0);
  41272. __decorate([
  41273. BABYLON.serializeAsVector3()
  41274. ], HemisphericLight.prototype, "direction", void 0);
  41275. return HemisphericLight;
  41276. }(BABYLON.Light));
  41277. BABYLON.HemisphericLight = HemisphericLight;
  41278. })(BABYLON || (BABYLON = {}));
  41279. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41280. var BABYLON;
  41281. (function (BABYLON) {
  41282. var ShadowLight = /** @class */ (function (_super) {
  41283. __extends(ShadowLight, _super);
  41284. function ShadowLight() {
  41285. var _this = _super !== null && _super.apply(this, arguments) || this;
  41286. _this._needProjectionMatrixCompute = true;
  41287. return _this;
  41288. }
  41289. Object.defineProperty(ShadowLight.prototype, "direction", {
  41290. get: function () {
  41291. return this._direction;
  41292. },
  41293. set: function (value) {
  41294. this._direction = value;
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41300. get: function () {
  41301. return this._shadowMinZ;
  41302. },
  41303. set: function (value) {
  41304. this._shadowMinZ = value;
  41305. this.forceProjectionMatrixCompute();
  41306. },
  41307. enumerable: true,
  41308. configurable: true
  41309. });
  41310. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41311. get: function () {
  41312. return this._shadowMaxZ;
  41313. },
  41314. set: function (value) {
  41315. this._shadowMaxZ = value;
  41316. this.forceProjectionMatrixCompute();
  41317. },
  41318. enumerable: true,
  41319. configurable: true
  41320. });
  41321. /**
  41322. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41323. */
  41324. ShadowLight.prototype.computeTransformedInformation = function () {
  41325. if (this.parent && this.parent.getWorldMatrix) {
  41326. if (!this.transformedPosition) {
  41327. this.transformedPosition = BABYLON.Vector3.Zero();
  41328. }
  41329. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41330. // In case the direction is present.
  41331. if (this.direction) {
  41332. if (!this.transformedDirection) {
  41333. this.transformedDirection = BABYLON.Vector3.Zero();
  41334. }
  41335. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41336. }
  41337. return true;
  41338. }
  41339. return false;
  41340. };
  41341. /**
  41342. * Return the depth scale used for the shadow map.
  41343. */
  41344. ShadowLight.prototype.getDepthScale = function () {
  41345. return 50.0;
  41346. };
  41347. /**
  41348. * Returns the light direction (Vector3) for any passed face index.
  41349. */
  41350. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41351. return this.transformedDirection ? this.transformedDirection : this.direction;
  41352. };
  41353. /**
  41354. * Returns the ShadowLight absolute position in the World.
  41355. */
  41356. ShadowLight.prototype.getAbsolutePosition = function () {
  41357. return this.transformedPosition ? this.transformedPosition : this.position;
  41358. };
  41359. /**
  41360. * Sets the ShadowLight direction toward the passed target (Vector3).
  41361. * Returns the updated ShadowLight direction (Vector3).
  41362. */
  41363. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41364. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41365. return this.direction;
  41366. };
  41367. /**
  41368. * Returns the light rotation (Vector3).
  41369. */
  41370. ShadowLight.prototype.getRotation = function () {
  41371. this.direction.normalize();
  41372. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41373. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41374. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41375. };
  41376. /**
  41377. * Boolean : false by default.
  41378. */
  41379. ShadowLight.prototype.needCube = function () {
  41380. return false;
  41381. };
  41382. /**
  41383. * Specifies wether or not the projection matrix should be recomputed this frame.
  41384. */
  41385. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41386. return this._needProjectionMatrixCompute;
  41387. };
  41388. /**
  41389. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41390. */
  41391. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41392. this._needProjectionMatrixCompute = true;
  41393. };
  41394. /**
  41395. * Get the world matrix of the sahdow lights.
  41396. */
  41397. ShadowLight.prototype._getWorldMatrix = function () {
  41398. if (!this._worldMatrix) {
  41399. this._worldMatrix = BABYLON.Matrix.Identity();
  41400. }
  41401. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41402. return this._worldMatrix;
  41403. };
  41404. /**
  41405. * Gets the minZ used for shadow according to both the scene and the light.
  41406. * @param activeCamera
  41407. */
  41408. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41409. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41410. };
  41411. /**
  41412. * Gets the maxZ used for shadow according to both the scene and the light.
  41413. * @param activeCamera
  41414. */
  41415. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41416. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41417. };
  41418. /**
  41419. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41420. * Returns the light.
  41421. */
  41422. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41423. if (this.customProjectionMatrixBuilder) {
  41424. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41425. }
  41426. else {
  41427. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41428. }
  41429. return this;
  41430. };
  41431. __decorate([
  41432. BABYLON.serializeAsVector3()
  41433. ], ShadowLight.prototype, "position", void 0);
  41434. __decorate([
  41435. BABYLON.serializeAsVector3()
  41436. ], ShadowLight.prototype, "direction", null);
  41437. __decorate([
  41438. BABYLON.serialize()
  41439. ], ShadowLight.prototype, "shadowMinZ", null);
  41440. __decorate([
  41441. BABYLON.serialize()
  41442. ], ShadowLight.prototype, "shadowMaxZ", null);
  41443. return ShadowLight;
  41444. }(BABYLON.Light));
  41445. BABYLON.ShadowLight = ShadowLight;
  41446. })(BABYLON || (BABYLON = {}));
  41447. //# sourceMappingURL=babylon.shadowLight.js.map
  41448. var BABYLON;
  41449. (function (BABYLON) {
  41450. var PointLight = /** @class */ (function (_super) {
  41451. __extends(PointLight, _super);
  41452. /**
  41453. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41454. * A PointLight emits the light in every direction.
  41455. * It can cast shadows.
  41456. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41457. * ```javascript
  41458. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41459. * ```
  41460. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41461. */
  41462. function PointLight(name, position, scene) {
  41463. var _this = _super.call(this, name, scene) || this;
  41464. _this._shadowAngle = Math.PI / 2;
  41465. _this.position = position;
  41466. return _this;
  41467. }
  41468. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41469. /**
  41470. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41471. * This specifies what angle the shadow will use to be created.
  41472. *
  41473. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41474. */
  41475. get: function () {
  41476. return this._shadowAngle;
  41477. },
  41478. /**
  41479. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41480. * This specifies what angle the shadow will use to be created.
  41481. *
  41482. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41483. */
  41484. set: function (value) {
  41485. this._shadowAngle = value;
  41486. this.forceProjectionMatrixCompute();
  41487. },
  41488. enumerable: true,
  41489. configurable: true
  41490. });
  41491. Object.defineProperty(PointLight.prototype, "direction", {
  41492. get: function () {
  41493. return this._direction;
  41494. },
  41495. /**
  41496. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41497. */
  41498. set: function (value) {
  41499. var previousNeedCube = this.needCube();
  41500. this._direction = value;
  41501. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41502. this._shadowGenerator.recreateShadowMap();
  41503. }
  41504. },
  41505. enumerable: true,
  41506. configurable: true
  41507. });
  41508. /**
  41509. * Returns the string "PointLight"
  41510. */
  41511. PointLight.prototype.getClassName = function () {
  41512. return "PointLight";
  41513. };
  41514. /**
  41515. * Returns the integer 0.
  41516. */
  41517. PointLight.prototype.getTypeID = function () {
  41518. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41519. };
  41520. /**
  41521. * Specifies wether or not the shadowmap should be a cube texture.
  41522. */
  41523. PointLight.prototype.needCube = function () {
  41524. return !this.direction;
  41525. };
  41526. /**
  41527. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41528. */
  41529. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41530. if (this.direction) {
  41531. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41532. }
  41533. else {
  41534. switch (faceIndex) {
  41535. case 0:
  41536. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41537. case 1:
  41538. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41539. case 2:
  41540. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41541. case 3:
  41542. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41543. case 4:
  41544. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41545. case 5:
  41546. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41547. }
  41548. }
  41549. return BABYLON.Vector3.Zero();
  41550. };
  41551. /**
  41552. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41553. * - fov = PI / 2
  41554. * - aspect ratio : 1.0
  41555. * - z-near and far equal to the active camera minZ and maxZ.
  41556. * Returns the PointLight.
  41557. */
  41558. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41559. var activeCamera = this.getScene().activeCamera;
  41560. if (!activeCamera) {
  41561. return;
  41562. }
  41563. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41564. };
  41565. PointLight.prototype._buildUniformLayout = function () {
  41566. this._uniformBuffer.addUniform("vLightData", 4);
  41567. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41568. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41569. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41570. this._uniformBuffer.addUniform("depthValues", 2);
  41571. this._uniformBuffer.create();
  41572. };
  41573. /**
  41574. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41575. * Returns the PointLight.
  41576. */
  41577. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41578. if (this.computeTransformedInformation()) {
  41579. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41580. return this;
  41581. }
  41582. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41583. return this;
  41584. };
  41585. __decorate([
  41586. BABYLON.serialize()
  41587. ], PointLight.prototype, "shadowAngle", null);
  41588. return PointLight;
  41589. }(BABYLON.ShadowLight));
  41590. BABYLON.PointLight = PointLight;
  41591. })(BABYLON || (BABYLON = {}));
  41592. //# sourceMappingURL=babylon.pointLight.js.map
  41593. var BABYLON;
  41594. (function (BABYLON) {
  41595. var DirectionalLight = /** @class */ (function (_super) {
  41596. __extends(DirectionalLight, _super);
  41597. /**
  41598. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41599. * The directional light is emitted from everywhere in the given direction.
  41600. * It can cast shawdows.
  41601. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41602. */
  41603. function DirectionalLight(name, direction, scene) {
  41604. var _this = _super.call(this, name, scene) || this;
  41605. _this._shadowFrustumSize = 0;
  41606. _this._shadowOrthoScale = 0.5;
  41607. _this.autoUpdateExtends = true;
  41608. // Cache
  41609. _this._orthoLeft = Number.MAX_VALUE;
  41610. _this._orthoRight = Number.MIN_VALUE;
  41611. _this._orthoTop = Number.MIN_VALUE;
  41612. _this._orthoBottom = Number.MAX_VALUE;
  41613. _this.position = direction.scale(-1.0);
  41614. _this.direction = direction;
  41615. return _this;
  41616. }
  41617. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41618. /**
  41619. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41620. */
  41621. get: function () {
  41622. return this._shadowFrustumSize;
  41623. },
  41624. /**
  41625. * Specifies a fix frustum size for the shadow generation.
  41626. */
  41627. set: function (value) {
  41628. this._shadowFrustumSize = value;
  41629. this.forceProjectionMatrixCompute();
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41635. get: function () {
  41636. return this._shadowOrthoScale;
  41637. },
  41638. set: function (value) {
  41639. this._shadowOrthoScale = value;
  41640. this.forceProjectionMatrixCompute();
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. /**
  41646. * Returns the string "DirectionalLight".
  41647. */
  41648. DirectionalLight.prototype.getClassName = function () {
  41649. return "DirectionalLight";
  41650. };
  41651. /**
  41652. * Returns the integer 1.
  41653. */
  41654. DirectionalLight.prototype.getTypeID = function () {
  41655. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41656. };
  41657. /**
  41658. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41659. * Returns the DirectionalLight Shadow projection matrix.
  41660. */
  41661. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41662. if (this.shadowFrustumSize > 0) {
  41663. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41664. }
  41665. else {
  41666. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41667. }
  41668. };
  41669. /**
  41670. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41671. * Returns the DirectionalLight Shadow projection matrix.
  41672. */
  41673. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41674. var activeCamera = this.getScene().activeCamera;
  41675. if (!activeCamera) {
  41676. return;
  41677. }
  41678. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41679. };
  41680. /**
  41681. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41682. * Returns the DirectionalLight Shadow projection matrix.
  41683. */
  41684. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41685. var activeCamera = this.getScene().activeCamera;
  41686. if (!activeCamera) {
  41687. return;
  41688. }
  41689. // Check extends
  41690. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41691. var tempVector3 = BABYLON.Vector3.Zero();
  41692. this._orthoLeft = Number.MAX_VALUE;
  41693. this._orthoRight = Number.MIN_VALUE;
  41694. this._orthoTop = Number.MIN_VALUE;
  41695. this._orthoBottom = Number.MAX_VALUE;
  41696. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41697. var mesh = renderList[meshIndex];
  41698. if (!mesh) {
  41699. continue;
  41700. }
  41701. var boundingInfo = mesh.getBoundingInfo();
  41702. var boundingBox = boundingInfo.boundingBox;
  41703. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41704. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41705. if (tempVector3.x < this._orthoLeft)
  41706. this._orthoLeft = tempVector3.x;
  41707. if (tempVector3.y < this._orthoBottom)
  41708. this._orthoBottom = tempVector3.y;
  41709. if (tempVector3.x > this._orthoRight)
  41710. this._orthoRight = tempVector3.x;
  41711. if (tempVector3.y > this._orthoTop)
  41712. this._orthoTop = tempVector3.y;
  41713. }
  41714. }
  41715. }
  41716. var xOffset = this._orthoRight - this._orthoLeft;
  41717. var yOffset = this._orthoTop - this._orthoBottom;
  41718. 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);
  41719. };
  41720. DirectionalLight.prototype._buildUniformLayout = function () {
  41721. this._uniformBuffer.addUniform("vLightData", 4);
  41722. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41723. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41724. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41725. this._uniformBuffer.addUniform("depthValues", 2);
  41726. this._uniformBuffer.create();
  41727. };
  41728. /**
  41729. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41730. * Returns the DirectionalLight.
  41731. */
  41732. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41733. if (this.computeTransformedInformation()) {
  41734. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41735. return this;
  41736. }
  41737. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41738. return this;
  41739. };
  41740. /**
  41741. * Gets the minZ used for shadow according to both the scene and the light.
  41742. *
  41743. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41744. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41745. * @param activeCamera
  41746. */
  41747. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41748. return 1;
  41749. };
  41750. /**
  41751. * Gets the maxZ used for shadow according to both the scene and the light.
  41752. *
  41753. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41754. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41755. * @param activeCamera
  41756. */
  41757. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41758. return 1;
  41759. };
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41766. __decorate([
  41767. BABYLON.serialize()
  41768. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41769. return DirectionalLight;
  41770. }(BABYLON.ShadowLight));
  41771. BABYLON.DirectionalLight = DirectionalLight;
  41772. })(BABYLON || (BABYLON = {}));
  41773. //# sourceMappingURL=babylon.directionalLight.js.map
  41774. var BABYLON;
  41775. (function (BABYLON) {
  41776. var SpotLight = /** @class */ (function (_super) {
  41777. __extends(SpotLight, _super);
  41778. /**
  41779. * Creates a SpotLight object in the scene with the passed parameters :
  41780. * - `position` (Vector3) is the initial SpotLight position,
  41781. * - `direction` (Vector3) is the initial SpotLight direction,
  41782. * - `angle` (float, in radians) is the spot light cone angle,
  41783. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41784. * A spot light is a simply light oriented cone.
  41785. * It can cast shadows.
  41786. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41787. */
  41788. function SpotLight(name, position, direction, angle, exponent, scene) {
  41789. var _this = _super.call(this, name, scene) || this;
  41790. _this.position = position;
  41791. _this.direction = direction;
  41792. _this.angle = angle;
  41793. _this.exponent = exponent;
  41794. return _this;
  41795. }
  41796. Object.defineProperty(SpotLight.prototype, "angle", {
  41797. get: function () {
  41798. return this._angle;
  41799. },
  41800. set: function (value) {
  41801. this._angle = value;
  41802. this.forceProjectionMatrixCompute();
  41803. },
  41804. enumerable: true,
  41805. configurable: true
  41806. });
  41807. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41808. get: function () {
  41809. return this._shadowAngleScale;
  41810. },
  41811. /**
  41812. * Allows scaling the angle of the light for shadow generation only.
  41813. */
  41814. set: function (value) {
  41815. this._shadowAngleScale = value;
  41816. this.forceProjectionMatrixCompute();
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. /**
  41822. * Returns the string "SpotLight".
  41823. */
  41824. SpotLight.prototype.getClassName = function () {
  41825. return "SpotLight";
  41826. };
  41827. /**
  41828. * Returns the integer 2.
  41829. */
  41830. SpotLight.prototype.getTypeID = function () {
  41831. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41832. };
  41833. /**
  41834. * 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.
  41835. * Returns the SpotLight.
  41836. */
  41837. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41838. var activeCamera = this.getScene().activeCamera;
  41839. if (!activeCamera) {
  41840. return;
  41841. }
  41842. this._shadowAngleScale = this._shadowAngleScale || 1;
  41843. var angle = this._shadowAngleScale * this._angle;
  41844. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41845. };
  41846. SpotLight.prototype._buildUniformLayout = function () {
  41847. this._uniformBuffer.addUniform("vLightData", 4);
  41848. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41849. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41850. this._uniformBuffer.addUniform("vLightDirection", 3);
  41851. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41852. this._uniformBuffer.addUniform("depthValues", 2);
  41853. this._uniformBuffer.create();
  41854. };
  41855. /**
  41856. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41857. * Return the SpotLight.
  41858. */
  41859. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41860. var normalizeDirection;
  41861. if (this.computeTransformedInformation()) {
  41862. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41863. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41864. }
  41865. else {
  41866. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41867. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41868. }
  41869. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41870. return this;
  41871. };
  41872. __decorate([
  41873. BABYLON.serialize()
  41874. ], SpotLight.prototype, "angle", null);
  41875. __decorate([
  41876. BABYLON.serialize()
  41877. /**
  41878. * Allows scaling the angle of the light for shadow generation only.
  41879. */
  41880. ], SpotLight.prototype, "shadowAngleScale", null);
  41881. __decorate([
  41882. BABYLON.serialize()
  41883. ], SpotLight.prototype, "exponent", void 0);
  41884. return SpotLight;
  41885. }(BABYLON.ShadowLight));
  41886. BABYLON.SpotLight = SpotLight;
  41887. })(BABYLON || (BABYLON = {}));
  41888. //# sourceMappingURL=babylon.spotLight.js.map
  41889. var BABYLON;
  41890. (function (BABYLON) {
  41891. var AnimationRange = /** @class */ (function () {
  41892. function AnimationRange(name, from, to) {
  41893. this.name = name;
  41894. this.from = from;
  41895. this.to = to;
  41896. }
  41897. AnimationRange.prototype.clone = function () {
  41898. return new AnimationRange(this.name, this.from, this.to);
  41899. };
  41900. return AnimationRange;
  41901. }());
  41902. BABYLON.AnimationRange = AnimationRange;
  41903. /**
  41904. * Composed of a frame, and an action function
  41905. */
  41906. var AnimationEvent = /** @class */ (function () {
  41907. function AnimationEvent(frame, action, onlyOnce) {
  41908. this.frame = frame;
  41909. this.action = action;
  41910. this.onlyOnce = onlyOnce;
  41911. this.isDone = false;
  41912. }
  41913. return AnimationEvent;
  41914. }());
  41915. BABYLON.AnimationEvent = AnimationEvent;
  41916. var PathCursor = /** @class */ (function () {
  41917. function PathCursor(path) {
  41918. this.path = path;
  41919. this._onchange = new Array();
  41920. this.value = 0;
  41921. this.animations = new Array();
  41922. }
  41923. PathCursor.prototype.getPoint = function () {
  41924. var point = this.path.getPointAtLengthPosition(this.value);
  41925. return new BABYLON.Vector3(point.x, 0, point.y);
  41926. };
  41927. PathCursor.prototype.moveAhead = function (step) {
  41928. if (step === void 0) { step = 0.002; }
  41929. this.move(step);
  41930. return this;
  41931. };
  41932. PathCursor.prototype.moveBack = function (step) {
  41933. if (step === void 0) { step = 0.002; }
  41934. this.move(-step);
  41935. return this;
  41936. };
  41937. PathCursor.prototype.move = function (step) {
  41938. if (Math.abs(step) > 1) {
  41939. throw "step size should be less than 1.";
  41940. }
  41941. this.value += step;
  41942. this.ensureLimits();
  41943. this.raiseOnChange();
  41944. return this;
  41945. };
  41946. PathCursor.prototype.ensureLimits = function () {
  41947. while (this.value > 1) {
  41948. this.value -= 1;
  41949. }
  41950. while (this.value < 0) {
  41951. this.value += 1;
  41952. }
  41953. return this;
  41954. };
  41955. // used by animation engine
  41956. PathCursor.prototype.raiseOnChange = function () {
  41957. var _this = this;
  41958. this._onchange.forEach(function (f) { return f(_this); });
  41959. return this;
  41960. };
  41961. PathCursor.prototype.onchange = function (f) {
  41962. this._onchange.push(f);
  41963. return this;
  41964. };
  41965. return PathCursor;
  41966. }());
  41967. BABYLON.PathCursor = PathCursor;
  41968. var AnimationKeyInterpolation;
  41969. (function (AnimationKeyInterpolation) {
  41970. /**
  41971. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41972. */
  41973. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41974. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41975. var Animation = /** @class */ (function () {
  41976. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41977. this.name = name;
  41978. this.targetProperty = targetProperty;
  41979. this.framePerSecond = framePerSecond;
  41980. this.dataType = dataType;
  41981. this.loopMode = loopMode;
  41982. this.enableBlending = enableBlending;
  41983. this._runtimeAnimations = new Array();
  41984. // The set of event that will be linked to this animation
  41985. this._events = new Array();
  41986. this.blendingSpeed = 0.01;
  41987. this._ranges = {};
  41988. this.targetPropertyPath = targetProperty.split(".");
  41989. this.dataType = dataType;
  41990. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41991. }
  41992. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41993. var dataType = undefined;
  41994. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41995. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41996. }
  41997. else if (from instanceof BABYLON.Quaternion) {
  41998. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41999. }
  42000. else if (from instanceof BABYLON.Vector3) {
  42001. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  42002. }
  42003. else if (from instanceof BABYLON.Vector2) {
  42004. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  42005. }
  42006. else if (from instanceof BABYLON.Color3) {
  42007. dataType = Animation.ANIMATIONTYPE_COLOR3;
  42008. }
  42009. else if (from instanceof BABYLON.Size) {
  42010. dataType = Animation.ANIMATIONTYPE_SIZE;
  42011. }
  42012. if (dataType == undefined) {
  42013. return null;
  42014. }
  42015. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  42016. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  42017. animation.setKeys(keys);
  42018. if (easingFunction !== undefined) {
  42019. animation.setEasingFunction(easingFunction);
  42020. }
  42021. return animation;
  42022. };
  42023. /**
  42024. * Sets up an animation.
  42025. * @param property the property to animate
  42026. * @param animationType the animation type to apply
  42027. * @param easingFunction the easing function used in the animation
  42028. * @returns The created animation
  42029. */
  42030. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  42031. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  42032. animation.setEasingFunction(easingFunction);
  42033. return animation;
  42034. };
  42035. /**
  42036. * Create and start an animation on a node
  42037. * @param {string} name defines the name of the global animation that will be run on all nodes
  42038. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42039. * @param {string} targetProperty defines property to animate
  42040. * @param {number} framePerSecond defines the number of frame per second yo use
  42041. * @param {number} totalFrame defines the number of frames in total
  42042. * @param {any} from defines the initial value
  42043. * @param {any} to defines the final value
  42044. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42045. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42046. * @param onAnimationEnd defines the callback to call when animation end
  42047. * @returns the animatable created for this animation
  42048. */
  42049. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42050. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42051. if (!animation) {
  42052. return null;
  42053. }
  42054. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42055. };
  42056. /**
  42057. * Create and start an animation on a node and its descendants
  42058. * @param {string} name defines the name of the global animation that will be run on all nodes
  42059. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42060. * @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.
  42061. * @param {string} targetProperty defines property to animate
  42062. * @param {number} framePerSecond defines the number of frame per second yo use
  42063. * @param {number} totalFrame defines the number of frames in total
  42064. * @param {any} from defines the initial value
  42065. * @param {any} to defines the final value
  42066. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42067. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42068. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  42069. * @returns the list of animatables created for all nodes
  42070. * @example https://www.babylonjs-playground.com/#MH0VLI
  42071. */
  42072. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42073. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42074. if (!animation) {
  42075. return null;
  42076. }
  42077. var scene = node.getScene();
  42078. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42079. };
  42080. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42081. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42082. if (!animation) {
  42083. return null;
  42084. }
  42085. node.animations.push(animation);
  42086. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42087. };
  42088. /**
  42089. * Transition property of the Camera to the target Value.
  42090. * @param property The property to transition
  42091. * @param targetValue The target Value of the property
  42092. * @param host The object where the property to animate belongs
  42093. * @param scene Scene used to run the animation
  42094. * @param frameRate Framerate (in frame/s) to use
  42095. * @param transition The transition type we want to use
  42096. * @param duration The duration of the animation, in milliseconds
  42097. * @param onAnimationEnd Call back trigger at the end of the animation.
  42098. */
  42099. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  42100. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  42101. if (duration <= 0) {
  42102. host[property] = targetValue;
  42103. if (onAnimationEnd) {
  42104. onAnimationEnd();
  42105. }
  42106. return null;
  42107. }
  42108. var endFrame = frameRate * (duration / 1000);
  42109. transition.setKeys([{
  42110. frame: 0,
  42111. value: host[property].clone ? host[property].clone() : host[property]
  42112. },
  42113. {
  42114. frame: endFrame,
  42115. value: targetValue
  42116. }]);
  42117. if (!host.animations) {
  42118. host.animations = [];
  42119. }
  42120. host.animations.push(transition);
  42121. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42122. animation.onAnimationEnd = onAnimationEnd;
  42123. return animation;
  42124. };
  42125. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42126. /**
  42127. * Return the array of runtime animations currently using this animation
  42128. */
  42129. get: function () {
  42130. return this._runtimeAnimations;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42136. get: function () {
  42137. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42138. var runtimeAnimation = _a[_i];
  42139. if (!runtimeAnimation.isStopped) {
  42140. return true;
  42141. }
  42142. }
  42143. return false;
  42144. },
  42145. enumerable: true,
  42146. configurable: true
  42147. });
  42148. // Methods
  42149. /**
  42150. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42151. */
  42152. Animation.prototype.toString = function (fullDetails) {
  42153. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42154. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42155. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42156. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42157. if (fullDetails) {
  42158. ret += ", Ranges: {";
  42159. var first = true;
  42160. for (var name in this._ranges) {
  42161. if (first) {
  42162. ret += ", ";
  42163. first = false;
  42164. }
  42165. ret += name;
  42166. }
  42167. ret += "}";
  42168. }
  42169. return ret;
  42170. };
  42171. /**
  42172. * Add an event to this animation.
  42173. */
  42174. Animation.prototype.addEvent = function (event) {
  42175. this._events.push(event);
  42176. };
  42177. /**
  42178. * Remove all events found at the given frame
  42179. * @param frame
  42180. */
  42181. Animation.prototype.removeEvents = function (frame) {
  42182. for (var index = 0; index < this._events.length; index++) {
  42183. if (this._events[index].frame === frame) {
  42184. this._events.splice(index, 1);
  42185. index--;
  42186. }
  42187. }
  42188. };
  42189. Animation.prototype.getEvents = function () {
  42190. return this._events;
  42191. };
  42192. Animation.prototype.createRange = function (name, from, to) {
  42193. // check name not already in use; could happen for bones after serialized
  42194. if (!this._ranges[name]) {
  42195. this._ranges[name] = new AnimationRange(name, from, to);
  42196. }
  42197. };
  42198. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42199. if (deleteFrames === void 0) { deleteFrames = true; }
  42200. var range = this._ranges[name];
  42201. if (!range) {
  42202. return;
  42203. }
  42204. if (deleteFrames) {
  42205. var from = range.from;
  42206. var to = range.to;
  42207. // this loop MUST go high to low for multiple splices to work
  42208. for (var key = this._keys.length - 1; key >= 0; key--) {
  42209. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42210. this._keys.splice(key, 1);
  42211. }
  42212. }
  42213. }
  42214. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42215. };
  42216. Animation.prototype.getRange = function (name) {
  42217. return this._ranges[name];
  42218. };
  42219. Animation.prototype.getKeys = function () {
  42220. return this._keys;
  42221. };
  42222. Animation.prototype.getHighestFrame = function () {
  42223. var ret = 0;
  42224. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42225. if (ret < this._keys[key].frame) {
  42226. ret = this._keys[key].frame;
  42227. }
  42228. }
  42229. return ret;
  42230. };
  42231. Animation.prototype.getEasingFunction = function () {
  42232. return this._easingFunction;
  42233. };
  42234. Animation.prototype.setEasingFunction = function (easingFunction) {
  42235. this._easingFunction = easingFunction;
  42236. };
  42237. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42238. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42239. };
  42240. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42241. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42242. };
  42243. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42244. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42245. };
  42246. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42247. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42248. };
  42249. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42250. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42251. };
  42252. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42253. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42254. };
  42255. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42256. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42257. };
  42258. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42259. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42260. };
  42261. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42262. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42263. };
  42264. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42265. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42266. };
  42267. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42268. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42269. };
  42270. Animation.prototype.clone = function () {
  42271. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42272. clone.enableBlending = this.enableBlending;
  42273. clone.blendingSpeed = this.blendingSpeed;
  42274. if (this._keys) {
  42275. clone.setKeys(this._keys);
  42276. }
  42277. if (this._ranges) {
  42278. clone._ranges = {};
  42279. for (var name in this._ranges) {
  42280. var range = this._ranges[name];
  42281. if (!range) {
  42282. continue;
  42283. }
  42284. clone._ranges[name] = range.clone();
  42285. }
  42286. }
  42287. return clone;
  42288. };
  42289. Animation.prototype.setKeys = function (values) {
  42290. this._keys = values.slice(0);
  42291. };
  42292. Animation.prototype.serialize = function () {
  42293. var serializationObject = {};
  42294. serializationObject.name = this.name;
  42295. serializationObject.property = this.targetProperty;
  42296. serializationObject.framePerSecond = this.framePerSecond;
  42297. serializationObject.dataType = this.dataType;
  42298. serializationObject.loopBehavior = this.loopMode;
  42299. serializationObject.enableBlending = this.enableBlending;
  42300. serializationObject.blendingSpeed = this.blendingSpeed;
  42301. var dataType = this.dataType;
  42302. serializationObject.keys = [];
  42303. var keys = this.getKeys();
  42304. for (var index = 0; index < keys.length; index++) {
  42305. var animationKey = keys[index];
  42306. var key = {};
  42307. key.frame = animationKey.frame;
  42308. switch (dataType) {
  42309. case Animation.ANIMATIONTYPE_FLOAT:
  42310. key.values = [animationKey.value];
  42311. break;
  42312. case Animation.ANIMATIONTYPE_QUATERNION:
  42313. case Animation.ANIMATIONTYPE_MATRIX:
  42314. case Animation.ANIMATIONTYPE_VECTOR3:
  42315. case Animation.ANIMATIONTYPE_COLOR3:
  42316. key.values = animationKey.value.asArray();
  42317. break;
  42318. }
  42319. serializationObject.keys.push(key);
  42320. }
  42321. serializationObject.ranges = [];
  42322. for (var name in this._ranges) {
  42323. var source = this._ranges[name];
  42324. if (!source) {
  42325. continue;
  42326. }
  42327. var range = {};
  42328. range.name = name;
  42329. range.from = source.from;
  42330. range.to = source.to;
  42331. serializationObject.ranges.push(range);
  42332. }
  42333. return serializationObject;
  42334. };
  42335. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42336. get: function () {
  42337. return Animation._ANIMATIONTYPE_FLOAT;
  42338. },
  42339. enumerable: true,
  42340. configurable: true
  42341. });
  42342. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42343. get: function () {
  42344. return Animation._ANIMATIONTYPE_VECTOR3;
  42345. },
  42346. enumerable: true,
  42347. configurable: true
  42348. });
  42349. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42350. get: function () {
  42351. return Animation._ANIMATIONTYPE_VECTOR2;
  42352. },
  42353. enumerable: true,
  42354. configurable: true
  42355. });
  42356. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42357. get: function () {
  42358. return Animation._ANIMATIONTYPE_SIZE;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42364. get: function () {
  42365. return Animation._ANIMATIONTYPE_QUATERNION;
  42366. },
  42367. enumerable: true,
  42368. configurable: true
  42369. });
  42370. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42371. get: function () {
  42372. return Animation._ANIMATIONTYPE_MATRIX;
  42373. },
  42374. enumerable: true,
  42375. configurable: true
  42376. });
  42377. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42378. get: function () {
  42379. return Animation._ANIMATIONTYPE_COLOR3;
  42380. },
  42381. enumerable: true,
  42382. configurable: true
  42383. });
  42384. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42385. get: function () {
  42386. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42387. },
  42388. enumerable: true,
  42389. configurable: true
  42390. });
  42391. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42392. get: function () {
  42393. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42394. },
  42395. enumerable: true,
  42396. configurable: true
  42397. });
  42398. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42399. get: function () {
  42400. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. Animation.Parse = function (parsedAnimation) {
  42406. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42407. var dataType = parsedAnimation.dataType;
  42408. var keys = [];
  42409. var data;
  42410. var index;
  42411. if (parsedAnimation.enableBlending) {
  42412. animation.enableBlending = parsedAnimation.enableBlending;
  42413. }
  42414. if (parsedAnimation.blendingSpeed) {
  42415. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42416. }
  42417. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42418. var key = parsedAnimation.keys[index];
  42419. var inTangent;
  42420. var outTangent;
  42421. switch (dataType) {
  42422. case Animation.ANIMATIONTYPE_FLOAT:
  42423. data = key.values[0];
  42424. if (key.values.length >= 1) {
  42425. inTangent = key.values[1];
  42426. }
  42427. if (key.values.length >= 2) {
  42428. outTangent = key.values[2];
  42429. }
  42430. break;
  42431. case Animation.ANIMATIONTYPE_QUATERNION:
  42432. data = BABYLON.Quaternion.FromArray(key.values);
  42433. if (key.values.length >= 8) {
  42434. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42435. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42436. inTangent = _inTangent;
  42437. }
  42438. }
  42439. if (key.values.length >= 12) {
  42440. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42441. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42442. outTangent = _outTangent;
  42443. }
  42444. }
  42445. break;
  42446. case Animation.ANIMATIONTYPE_MATRIX:
  42447. data = BABYLON.Matrix.FromArray(key.values);
  42448. break;
  42449. case Animation.ANIMATIONTYPE_COLOR3:
  42450. data = BABYLON.Color3.FromArray(key.values);
  42451. break;
  42452. case Animation.ANIMATIONTYPE_VECTOR3:
  42453. default:
  42454. data = BABYLON.Vector3.FromArray(key.values);
  42455. break;
  42456. }
  42457. var keyData = {};
  42458. keyData.frame = key.frame;
  42459. keyData.value = data;
  42460. if (inTangent != undefined) {
  42461. keyData.inTangent = inTangent;
  42462. }
  42463. if (outTangent != undefined) {
  42464. keyData.outTangent = outTangent;
  42465. }
  42466. keys.push(keyData);
  42467. }
  42468. animation.setKeys(keys);
  42469. if (parsedAnimation.ranges) {
  42470. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42471. data = parsedAnimation.ranges[index];
  42472. animation.createRange(data.name, data.from, data.to);
  42473. }
  42474. }
  42475. return animation;
  42476. };
  42477. Animation.AppendSerializedAnimations = function (source, destination) {
  42478. if (source.animations) {
  42479. destination.animations = [];
  42480. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42481. var animation = source.animations[animationIndex];
  42482. destination.animations.push(animation.serialize());
  42483. }
  42484. }
  42485. };
  42486. Animation.AllowMatricesInterpolation = false;
  42487. // Statics
  42488. Animation._ANIMATIONTYPE_FLOAT = 0;
  42489. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42490. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42491. Animation._ANIMATIONTYPE_MATRIX = 3;
  42492. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42493. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42494. Animation._ANIMATIONTYPE_SIZE = 6;
  42495. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42496. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42497. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42498. return Animation;
  42499. }());
  42500. BABYLON.Animation = Animation;
  42501. })(BABYLON || (BABYLON = {}));
  42502. //# sourceMappingURL=babylon.animation.js.map
  42503. var BABYLON;
  42504. (function (BABYLON) {
  42505. /**
  42506. * This class defines the direct association between an animation and a target
  42507. */
  42508. var TargetedAnimation = /** @class */ (function () {
  42509. function TargetedAnimation() {
  42510. }
  42511. return TargetedAnimation;
  42512. }());
  42513. BABYLON.TargetedAnimation = TargetedAnimation;
  42514. /**
  42515. * Use this class to create coordinated animations on multiple targets
  42516. */
  42517. var AnimationGroup = /** @class */ (function () {
  42518. function AnimationGroup(name, scene) {
  42519. if (scene === void 0) { scene = null; }
  42520. this.name = name;
  42521. this._targetedAnimations = new Array();
  42522. this._animatables = new Array();
  42523. this._from = Number.MAX_VALUE;
  42524. this._to = -Number.MAX_VALUE;
  42525. this._speedRatio = 1;
  42526. this.onAnimationEndObservable = new BABYLON.Observable();
  42527. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42528. this._scene.animationGroups.push(this);
  42529. }
  42530. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42531. /**
  42532. * Define if the animations are started
  42533. */
  42534. get: function () {
  42535. return this._isStarted;
  42536. },
  42537. enumerable: true,
  42538. configurable: true
  42539. });
  42540. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42541. /**
  42542. * Gets or sets the speed ratio to use for all animations
  42543. */
  42544. get: function () {
  42545. return this._speedRatio;
  42546. },
  42547. /**
  42548. * Gets or sets the speed ratio to use for all animations
  42549. */
  42550. set: function (value) {
  42551. if (this._speedRatio === value) {
  42552. return;
  42553. }
  42554. this._speedRatio = value;
  42555. for (var index = 0; index < this._animatables.length; index++) {
  42556. var animatable = this._animatables[index];
  42557. animatable.speedRatio = this._speedRatio;
  42558. }
  42559. },
  42560. enumerable: true,
  42561. configurable: true
  42562. });
  42563. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  42564. /**
  42565. * Gets the targeted animations for this animation group
  42566. */
  42567. get: function () {
  42568. return this._targetedAnimations;
  42569. },
  42570. enumerable: true,
  42571. configurable: true
  42572. });
  42573. /**
  42574. * Add an animation (with its target) in the group
  42575. * @param animation defines the animation we want to add
  42576. * @param target defines the target of the animation
  42577. * @returns the {BABYLON.TargetedAnimation} object
  42578. */
  42579. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42580. var targetedAnimation = {
  42581. animation: animation,
  42582. target: target
  42583. };
  42584. var keys = animation.getKeys();
  42585. if (this._from > keys[0].frame) {
  42586. this._from = keys[0].frame;
  42587. }
  42588. if (this._to < keys[keys.length - 1].frame) {
  42589. this._to = keys[keys.length - 1].frame;
  42590. }
  42591. this._targetedAnimations.push(targetedAnimation);
  42592. return targetedAnimation;
  42593. };
  42594. /**
  42595. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42596. * It can add constant keys at begin or end
  42597. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  42598. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  42599. */
  42600. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42601. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  42602. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  42603. beginFrame = Math.max(beginFrame, this._from);
  42604. endFrame = Math.min(endFrame, this._to);
  42605. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42606. var targetedAnimation = this._targetedAnimations[index];
  42607. var keys = targetedAnimation.animation.getKeys();
  42608. var startKey = keys[0];
  42609. var endKey = keys[keys.length - 1];
  42610. if (startKey.frame > beginFrame) {
  42611. var newKey = {
  42612. frame: beginFrame,
  42613. value: startKey.value,
  42614. inTangent: startKey.inTangent,
  42615. outTangent: startKey.outTangent,
  42616. interpolation: startKey.interpolation
  42617. };
  42618. keys.splice(0, 0, newKey);
  42619. }
  42620. if (endKey.frame < endFrame) {
  42621. var newKey = {
  42622. frame: endFrame,
  42623. value: endKey.value,
  42624. inTangent: endKey.outTangent,
  42625. outTangent: endKey.outTangent,
  42626. interpolation: endKey.interpolation
  42627. };
  42628. keys.push(newKey);
  42629. }
  42630. }
  42631. return this;
  42632. };
  42633. /**
  42634. * Start all animations on given targets
  42635. * @param loop defines if animations must loop
  42636. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42637. */
  42638. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42639. var _this = this;
  42640. if (loop === void 0) { loop = false; }
  42641. if (speedRatio === void 0) { speedRatio = 1; }
  42642. if (this._isStarted || this._targetedAnimations.length === 0) {
  42643. return this;
  42644. }
  42645. var _loop_1 = function () {
  42646. var targetedAnimation = this_1._targetedAnimations[index];
  42647. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42648. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42649. }));
  42650. };
  42651. var this_1 = this;
  42652. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42653. _loop_1();
  42654. }
  42655. this._speedRatio = speedRatio;
  42656. this._isStarted = true;
  42657. return this;
  42658. };
  42659. /**
  42660. * Pause all animations
  42661. */
  42662. AnimationGroup.prototype.pause = function () {
  42663. if (!this._isStarted) {
  42664. return this;
  42665. }
  42666. for (var index = 0; index < this._animatables.length; index++) {
  42667. var animatable = this._animatables[index];
  42668. animatable.pause();
  42669. }
  42670. return this;
  42671. };
  42672. /**
  42673. * Play all animations to initial state
  42674. * This function will start() the animations if they were not started or will restart() them if they were paused
  42675. * @param loop defines if animations must loop
  42676. */
  42677. AnimationGroup.prototype.play = function (loop) {
  42678. if (this.isStarted) {
  42679. if (loop !== undefined) {
  42680. for (var index = 0; index < this._animatables.length; index++) {
  42681. var animatable = this._animatables[index];
  42682. animatable.loopAnimation = loop;
  42683. }
  42684. }
  42685. this.restart();
  42686. }
  42687. else {
  42688. this.start(loop, this._speedRatio);
  42689. }
  42690. return this;
  42691. };
  42692. /**
  42693. * Reset all animations to initial state
  42694. */
  42695. AnimationGroup.prototype.reset = function () {
  42696. if (!this._isStarted) {
  42697. return this;
  42698. }
  42699. for (var index = 0; index < this._animatables.length; index++) {
  42700. var animatable = this._animatables[index];
  42701. animatable.reset();
  42702. }
  42703. return this;
  42704. };
  42705. /**
  42706. * Restart animations from key 0
  42707. */
  42708. AnimationGroup.prototype.restart = function () {
  42709. if (!this._isStarted) {
  42710. return this;
  42711. }
  42712. for (var index = 0; index < this._animatables.length; index++) {
  42713. var animatable = this._animatables[index];
  42714. animatable.restart();
  42715. }
  42716. return this;
  42717. };
  42718. /**
  42719. * Stop all animations
  42720. */
  42721. AnimationGroup.prototype.stop = function () {
  42722. if (!this._isStarted) {
  42723. return this;
  42724. }
  42725. for (var index = 0; index < this._animatables.length; index++) {
  42726. var animatable = this._animatables[index];
  42727. animatable.stop();
  42728. }
  42729. this._isStarted = false;
  42730. return this;
  42731. };
  42732. /**
  42733. * Dispose all associated resources
  42734. */
  42735. AnimationGroup.prototype.dispose = function () {
  42736. this._targetedAnimations = [];
  42737. this._animatables = [];
  42738. var index = this._scene.animationGroups.indexOf(this);
  42739. if (index > -1) {
  42740. this._scene.animationGroups.splice(index, 1);
  42741. }
  42742. };
  42743. return AnimationGroup;
  42744. }());
  42745. BABYLON.AnimationGroup = AnimationGroup;
  42746. })(BABYLON || (BABYLON = {}));
  42747. //# sourceMappingURL=babylon.animationGroup.js.map
  42748. var BABYLON;
  42749. (function (BABYLON) {
  42750. var RuntimeAnimation = /** @class */ (function () {
  42751. function RuntimeAnimation(target, animation) {
  42752. this._offsetsCache = {};
  42753. this._highLimitsCache = {};
  42754. this._stopped = false;
  42755. this._blendingFactor = 0;
  42756. this._ratioOffset = 0;
  42757. this._animation = animation;
  42758. this._target = target;
  42759. animation._runtimeAnimations.push(this);
  42760. }
  42761. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42762. get: function () {
  42763. return this._animation;
  42764. },
  42765. enumerable: true,
  42766. configurable: true
  42767. });
  42768. RuntimeAnimation.prototype.reset = function () {
  42769. this._offsetsCache = {};
  42770. this._highLimitsCache = {};
  42771. this.currentFrame = 0;
  42772. this._blendingFactor = 0;
  42773. this._originalBlendValue = null;
  42774. };
  42775. RuntimeAnimation.prototype.isStopped = function () {
  42776. return this._stopped;
  42777. };
  42778. RuntimeAnimation.prototype.dispose = function () {
  42779. var index = this._animation.runtimeAnimations.indexOf(this);
  42780. if (index > -1) {
  42781. this._animation.runtimeAnimations.splice(index, 1);
  42782. }
  42783. };
  42784. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42785. if (typeof value === "function") {
  42786. return value();
  42787. }
  42788. return value;
  42789. };
  42790. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42791. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42792. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42793. }
  42794. this.currentFrame = currentFrame;
  42795. var keys = this._animation.getKeys();
  42796. // Try to get a hash to find the right key
  42797. 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));
  42798. if (keys[startKeyIndex].frame >= currentFrame) {
  42799. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42800. startKeyIndex--;
  42801. }
  42802. }
  42803. for (var key = startKeyIndex; key < keys.length; key++) {
  42804. var endKey = keys[key + 1];
  42805. if (endKey.frame >= currentFrame) {
  42806. var startKey = keys[key];
  42807. var startValue = this._getKeyValue(startKey.value);
  42808. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42809. return startValue;
  42810. }
  42811. var endValue = this._getKeyValue(endKey.value);
  42812. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42813. var frameDelta = endKey.frame - startKey.frame;
  42814. // gradient : percent of currentFrame between the frame inf and the frame sup
  42815. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42816. // check for easingFunction and correction of gradient
  42817. var easingFunction = this._animation.getEasingFunction();
  42818. if (easingFunction != null) {
  42819. gradient = easingFunction.ease(gradient);
  42820. }
  42821. switch (this._animation.dataType) {
  42822. // Float
  42823. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42824. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42825. switch (loopMode) {
  42826. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42827. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42828. return floatValue;
  42829. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42830. return offsetValue * repeatCount + floatValue;
  42831. }
  42832. break;
  42833. // Quaternion
  42834. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42835. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42836. switch (loopMode) {
  42837. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42838. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42839. return quatValue;
  42840. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42841. return quatValue.add(offsetValue.scale(repeatCount));
  42842. }
  42843. return quatValue;
  42844. // Vector3
  42845. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42846. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42847. switch (loopMode) {
  42848. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42849. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42850. return vec3Value;
  42851. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42852. return vec3Value.add(offsetValue.scale(repeatCount));
  42853. }
  42854. // Vector2
  42855. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42856. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42857. switch (loopMode) {
  42858. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42859. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42860. return vec2Value;
  42861. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42862. return vec2Value.add(offsetValue.scale(repeatCount));
  42863. }
  42864. // Size
  42865. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42866. switch (loopMode) {
  42867. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42868. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42869. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42870. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42871. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42872. }
  42873. // Color3
  42874. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42875. switch (loopMode) {
  42876. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42877. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42878. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42879. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42880. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42881. }
  42882. // Matrix
  42883. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42884. switch (loopMode) {
  42885. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42886. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42887. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42888. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42889. }
  42890. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42891. return startValue;
  42892. }
  42893. default:
  42894. break;
  42895. }
  42896. break;
  42897. }
  42898. }
  42899. return this._getKeyValue(keys[keys.length - 1].value);
  42900. };
  42901. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42902. if (blend === void 0) { blend = false; }
  42903. // Set value
  42904. var path;
  42905. var destination;
  42906. var targetPropertyPath = this._animation.targetPropertyPath;
  42907. if (targetPropertyPath.length > 1) {
  42908. var property = this._target[targetPropertyPath[0]];
  42909. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42910. property = property[targetPropertyPath[index]];
  42911. }
  42912. path = targetPropertyPath[targetPropertyPath.length - 1];
  42913. destination = property;
  42914. }
  42915. else {
  42916. path = targetPropertyPath[0];
  42917. destination = this._target;
  42918. }
  42919. // Blending
  42920. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42921. if (!this._originalBlendValue) {
  42922. if (destination[path].clone) {
  42923. this._originalBlendValue = destination[path].clone();
  42924. }
  42925. else {
  42926. this._originalBlendValue = destination[path];
  42927. }
  42928. }
  42929. if (this._originalBlendValue.prototype) {
  42930. if (this._originalBlendValue.prototype.Lerp) {
  42931. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42932. }
  42933. else {
  42934. destination[path] = currentValue;
  42935. }
  42936. }
  42937. else if (this._originalBlendValue.m) {
  42938. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42939. }
  42940. else {
  42941. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42942. }
  42943. this._blendingFactor += this._animation.blendingSpeed;
  42944. }
  42945. else {
  42946. destination[path] = currentValue;
  42947. }
  42948. if (this._target.markAsDirty) {
  42949. this._target.markAsDirty(this._animation.targetProperty);
  42950. }
  42951. };
  42952. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42953. var keys = this._animation.getKeys();
  42954. if (frame < keys[0].frame) {
  42955. frame = keys[0].frame;
  42956. }
  42957. else if (frame > keys[keys.length - 1].frame) {
  42958. frame = keys[keys.length - 1].frame;
  42959. }
  42960. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42961. this.setValue(currentValue);
  42962. };
  42963. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42964. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42965. this._ratioOffset = this._previousRatio - newRatio;
  42966. };
  42967. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42968. if (blend === void 0) { blend = false; }
  42969. var targetPropertyPath = this._animation.targetPropertyPath;
  42970. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42971. this._stopped = true;
  42972. return false;
  42973. }
  42974. var returnValue = true;
  42975. var keys = this._animation.getKeys();
  42976. // Adding a start key at frame 0 if missing
  42977. if (keys[0].frame !== 0) {
  42978. var newKey = { frame: 0, value: keys[0].value };
  42979. keys.splice(0, 0, newKey);
  42980. }
  42981. // Check limits
  42982. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42983. from = keys[0].frame;
  42984. }
  42985. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42986. to = keys[keys.length - 1].frame;
  42987. }
  42988. //to and from cannot be the same key
  42989. if (from === to) {
  42990. if (from > keys[0].frame) {
  42991. from--;
  42992. }
  42993. else if (to < keys[keys.length - 1].frame) {
  42994. to++;
  42995. }
  42996. }
  42997. // Compute ratio
  42998. var range = to - from;
  42999. var offsetValue;
  43000. // ratio represents the frame delta between from and to
  43001. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  43002. var highLimitValue = 0;
  43003. this._previousDelay = delay;
  43004. this._previousRatio = ratio;
  43005. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  43006. returnValue = false;
  43007. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  43008. }
  43009. else {
  43010. // Get max value if required
  43011. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  43012. var keyOffset = to.toString() + from.toString();
  43013. if (!this._offsetsCache[keyOffset]) {
  43014. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43015. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43016. switch (this._animation.dataType) {
  43017. // Float
  43018. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43019. this._offsetsCache[keyOffset] = toValue - fromValue;
  43020. break;
  43021. // Quaternion
  43022. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43023. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43024. break;
  43025. // Vector3
  43026. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43027. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43028. // Vector2
  43029. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43030. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43031. // Size
  43032. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43033. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43034. // Color3
  43035. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43036. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43037. default:
  43038. break;
  43039. }
  43040. this._highLimitsCache[keyOffset] = toValue;
  43041. }
  43042. highLimitValue = this._highLimitsCache[keyOffset];
  43043. offsetValue = this._offsetsCache[keyOffset];
  43044. }
  43045. }
  43046. if (offsetValue === undefined) {
  43047. switch (this._animation.dataType) {
  43048. // Float
  43049. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43050. offsetValue = 0;
  43051. break;
  43052. // Quaternion
  43053. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43054. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  43055. break;
  43056. // Vector3
  43057. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43058. offsetValue = BABYLON.Vector3.Zero();
  43059. break;
  43060. // Vector2
  43061. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43062. offsetValue = BABYLON.Vector2.Zero();
  43063. break;
  43064. // Size
  43065. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43066. offsetValue = BABYLON.Size.Zero();
  43067. break;
  43068. // Color3
  43069. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43070. offsetValue = BABYLON.Color3.Black();
  43071. }
  43072. }
  43073. // Compute value
  43074. var repeatCount = (ratio / range) >> 0;
  43075. var currentFrame = returnValue ? from + ratio % range : to;
  43076. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  43077. // Set value
  43078. this.setValue(currentValue);
  43079. // Check events
  43080. var events = this._animation.getEvents();
  43081. for (var index = 0; index < events.length; index++) {
  43082. // Make sure current frame has passed event frame and that event frame is within the current range
  43083. // Also, handle both forward and reverse animations
  43084. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  43085. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  43086. var event = events[index];
  43087. if (!event.isDone) {
  43088. // If event should be done only once, remove it.
  43089. if (event.onlyOnce) {
  43090. events.splice(index, 1);
  43091. index--;
  43092. }
  43093. event.isDone = true;
  43094. event.action();
  43095. } // Don't do anything if the event has already be done.
  43096. }
  43097. else if (events[index].isDone && !events[index].onlyOnce) {
  43098. // reset event, the animation is looping
  43099. events[index].isDone = false;
  43100. }
  43101. }
  43102. if (!returnValue) {
  43103. this._stopped = true;
  43104. }
  43105. return returnValue;
  43106. };
  43107. return RuntimeAnimation;
  43108. }());
  43109. BABYLON.RuntimeAnimation = RuntimeAnimation;
  43110. })(BABYLON || (BABYLON = {}));
  43111. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  43112. var BABYLON;
  43113. (function (BABYLON) {
  43114. var Animatable = /** @class */ (function () {
  43115. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  43116. if (fromFrame === void 0) { fromFrame = 0; }
  43117. if (toFrame === void 0) { toFrame = 100; }
  43118. if (loopAnimation === void 0) { loopAnimation = false; }
  43119. if (speedRatio === void 0) { speedRatio = 1.0; }
  43120. this.target = target;
  43121. this.fromFrame = fromFrame;
  43122. this.toFrame = toFrame;
  43123. this.loopAnimation = loopAnimation;
  43124. this.onAnimationEnd = onAnimationEnd;
  43125. this._localDelayOffset = null;
  43126. this._pausedDelay = null;
  43127. this._runtimeAnimations = new Array();
  43128. this._paused = false;
  43129. this._speedRatio = 1;
  43130. this.animationStarted = false;
  43131. if (animations) {
  43132. this.appendAnimations(target, animations);
  43133. }
  43134. this._speedRatio = speedRatio;
  43135. this._scene = scene;
  43136. scene._activeAnimatables.push(this);
  43137. }
  43138. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43139. get: function () {
  43140. return this._speedRatio;
  43141. },
  43142. set: function (value) {
  43143. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43144. var animation = this._runtimeAnimations[index];
  43145. animation._prepareForSpeedRatioChange(value);
  43146. }
  43147. this._speedRatio = value;
  43148. },
  43149. enumerable: true,
  43150. configurable: true
  43151. });
  43152. // Methods
  43153. Animatable.prototype.getAnimations = function () {
  43154. return this._runtimeAnimations;
  43155. };
  43156. Animatable.prototype.appendAnimations = function (target, animations) {
  43157. for (var index = 0; index < animations.length; index++) {
  43158. var animation = animations[index];
  43159. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43160. }
  43161. };
  43162. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43163. var runtimeAnimations = this._runtimeAnimations;
  43164. for (var index = 0; index < runtimeAnimations.length; index++) {
  43165. if (runtimeAnimations[index].animation.targetProperty === property) {
  43166. return runtimeAnimations[index].animation;
  43167. }
  43168. }
  43169. return null;
  43170. };
  43171. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43172. var runtimeAnimations = this._runtimeAnimations;
  43173. for (var index = 0; index < runtimeAnimations.length; index++) {
  43174. if (runtimeAnimations[index].animation.targetProperty === property) {
  43175. return runtimeAnimations[index];
  43176. }
  43177. }
  43178. return null;
  43179. };
  43180. Animatable.prototype.reset = function () {
  43181. var runtimeAnimations = this._runtimeAnimations;
  43182. for (var index = 0; index < runtimeAnimations.length; index++) {
  43183. runtimeAnimations[index].reset();
  43184. }
  43185. // Reset to original value
  43186. for (index = 0; index < runtimeAnimations.length; index++) {
  43187. var animation = runtimeAnimations[index];
  43188. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43189. }
  43190. this._localDelayOffset = null;
  43191. this._pausedDelay = null;
  43192. };
  43193. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43194. var runtimeAnimations = this._runtimeAnimations;
  43195. for (var index = 0; index < runtimeAnimations.length; index++) {
  43196. runtimeAnimations[index].animation.enableBlending = true;
  43197. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43198. }
  43199. };
  43200. Animatable.prototype.disableBlending = function () {
  43201. var runtimeAnimations = this._runtimeAnimations;
  43202. for (var index = 0; index < runtimeAnimations.length; index++) {
  43203. runtimeAnimations[index].animation.enableBlending = false;
  43204. }
  43205. };
  43206. Animatable.prototype.goToFrame = function (frame) {
  43207. var runtimeAnimations = this._runtimeAnimations;
  43208. if (runtimeAnimations[0]) {
  43209. var fps = runtimeAnimations[0].animation.framePerSecond;
  43210. var currentFrame = runtimeAnimations[0].currentFrame;
  43211. var adjustTime = frame - currentFrame;
  43212. var delay = adjustTime * 1000 / fps;
  43213. if (this._localDelayOffset === null) {
  43214. this._localDelayOffset = 0;
  43215. }
  43216. this._localDelayOffset -= delay;
  43217. }
  43218. for (var index = 0; index < runtimeAnimations.length; index++) {
  43219. runtimeAnimations[index].goToFrame(frame);
  43220. }
  43221. };
  43222. Animatable.prototype.pause = function () {
  43223. if (this._paused) {
  43224. return;
  43225. }
  43226. this._paused = true;
  43227. };
  43228. Animatable.prototype.restart = function () {
  43229. this._paused = false;
  43230. };
  43231. Animatable.prototype.stop = function (animationName) {
  43232. if (animationName) {
  43233. var idx = this._scene._activeAnimatables.indexOf(this);
  43234. if (idx > -1) {
  43235. var runtimeAnimations = this._runtimeAnimations;
  43236. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43237. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43238. continue;
  43239. }
  43240. runtimeAnimations[index].dispose();
  43241. runtimeAnimations.splice(index, 1);
  43242. }
  43243. if (runtimeAnimations.length == 0) {
  43244. this._scene._activeAnimatables.splice(idx, 1);
  43245. if (this.onAnimationEnd) {
  43246. this.onAnimationEnd();
  43247. }
  43248. }
  43249. }
  43250. }
  43251. else {
  43252. var index = this._scene._activeAnimatables.indexOf(this);
  43253. if (index > -1) {
  43254. this._scene._activeAnimatables.splice(index, 1);
  43255. var runtimeAnimations = this._runtimeAnimations;
  43256. for (var index = 0; index < runtimeAnimations.length; index++) {
  43257. runtimeAnimations[index].dispose();
  43258. }
  43259. if (this.onAnimationEnd) {
  43260. this.onAnimationEnd();
  43261. }
  43262. }
  43263. }
  43264. };
  43265. Animatable.prototype._animate = function (delay) {
  43266. if (this._paused) {
  43267. this.animationStarted = false;
  43268. if (this._pausedDelay === null) {
  43269. this._pausedDelay = delay;
  43270. }
  43271. return true;
  43272. }
  43273. if (this._localDelayOffset === null) {
  43274. this._localDelayOffset = delay;
  43275. }
  43276. else if (this._pausedDelay !== null) {
  43277. this._localDelayOffset += delay - this._pausedDelay;
  43278. this._pausedDelay = null;
  43279. }
  43280. // Animating
  43281. var running = false;
  43282. var runtimeAnimations = this._runtimeAnimations;
  43283. var index;
  43284. for (index = 0; index < runtimeAnimations.length; index++) {
  43285. var animation = runtimeAnimations[index];
  43286. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43287. running = running || isRunning;
  43288. }
  43289. this.animationStarted = running;
  43290. if (!running) {
  43291. // Remove from active animatables
  43292. index = this._scene._activeAnimatables.indexOf(this);
  43293. this._scene._activeAnimatables.splice(index, 1);
  43294. // Dispose all runtime animations
  43295. for (index = 0; index < runtimeAnimations.length; index++) {
  43296. runtimeAnimations[index].dispose();
  43297. }
  43298. }
  43299. if (!running && this.onAnimationEnd) {
  43300. this.onAnimationEnd();
  43301. this.onAnimationEnd = null;
  43302. }
  43303. return running;
  43304. };
  43305. return Animatable;
  43306. }());
  43307. BABYLON.Animatable = Animatable;
  43308. })(BABYLON || (BABYLON = {}));
  43309. //# sourceMappingURL=babylon.animatable.js.map
  43310. var BABYLON;
  43311. (function (BABYLON) {
  43312. var EasingFunction = /** @class */ (function () {
  43313. function EasingFunction() {
  43314. // Properties
  43315. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43316. }
  43317. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43318. get: function () {
  43319. return EasingFunction._EASINGMODE_EASEIN;
  43320. },
  43321. enumerable: true,
  43322. configurable: true
  43323. });
  43324. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43325. get: function () {
  43326. return EasingFunction._EASINGMODE_EASEOUT;
  43327. },
  43328. enumerable: true,
  43329. configurable: true
  43330. });
  43331. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43332. get: function () {
  43333. return EasingFunction._EASINGMODE_EASEINOUT;
  43334. },
  43335. enumerable: true,
  43336. configurable: true
  43337. });
  43338. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43339. var n = Math.min(Math.max(easingMode, 0), 2);
  43340. this._easingMode = n;
  43341. };
  43342. EasingFunction.prototype.getEasingMode = function () {
  43343. return this._easingMode;
  43344. };
  43345. EasingFunction.prototype.easeInCore = function (gradient) {
  43346. throw new Error('You must implement this method');
  43347. };
  43348. EasingFunction.prototype.ease = function (gradient) {
  43349. switch (this._easingMode) {
  43350. case EasingFunction.EASINGMODE_EASEIN:
  43351. return this.easeInCore(gradient);
  43352. case EasingFunction.EASINGMODE_EASEOUT:
  43353. return (1 - this.easeInCore(1 - gradient));
  43354. }
  43355. if (gradient >= 0.5) {
  43356. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43357. }
  43358. return (this.easeInCore(gradient * 2) * 0.5);
  43359. };
  43360. //Statics
  43361. EasingFunction._EASINGMODE_EASEIN = 0;
  43362. EasingFunction._EASINGMODE_EASEOUT = 1;
  43363. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43364. return EasingFunction;
  43365. }());
  43366. BABYLON.EasingFunction = EasingFunction;
  43367. var CircleEase = /** @class */ (function (_super) {
  43368. __extends(CircleEase, _super);
  43369. function CircleEase() {
  43370. return _super !== null && _super.apply(this, arguments) || this;
  43371. }
  43372. CircleEase.prototype.easeInCore = function (gradient) {
  43373. gradient = Math.max(0, Math.min(1, gradient));
  43374. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43375. };
  43376. return CircleEase;
  43377. }(EasingFunction));
  43378. BABYLON.CircleEase = CircleEase;
  43379. var BackEase = /** @class */ (function (_super) {
  43380. __extends(BackEase, _super);
  43381. function BackEase(amplitude) {
  43382. if (amplitude === void 0) { amplitude = 1; }
  43383. var _this = _super.call(this) || this;
  43384. _this.amplitude = amplitude;
  43385. return _this;
  43386. }
  43387. BackEase.prototype.easeInCore = function (gradient) {
  43388. var num = Math.max(0, this.amplitude);
  43389. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43390. };
  43391. return BackEase;
  43392. }(EasingFunction));
  43393. BABYLON.BackEase = BackEase;
  43394. var BounceEase = /** @class */ (function (_super) {
  43395. __extends(BounceEase, _super);
  43396. function BounceEase(bounces, bounciness) {
  43397. if (bounces === void 0) { bounces = 3; }
  43398. if (bounciness === void 0) { bounciness = 2; }
  43399. var _this = _super.call(this) || this;
  43400. _this.bounces = bounces;
  43401. _this.bounciness = bounciness;
  43402. return _this;
  43403. }
  43404. BounceEase.prototype.easeInCore = function (gradient) {
  43405. var y = Math.max(0.0, this.bounces);
  43406. var bounciness = this.bounciness;
  43407. if (bounciness <= 1.0) {
  43408. bounciness = 1.001;
  43409. }
  43410. var num9 = Math.pow(bounciness, y);
  43411. var num5 = 1.0 - bounciness;
  43412. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43413. var num15 = gradient * num4;
  43414. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43415. var num3 = Math.floor(num65);
  43416. var num13 = num3 + 1.0;
  43417. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43418. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43419. var num7 = (num8 + num12) * 0.5;
  43420. var num6 = gradient - num7;
  43421. var num2 = num7 - num8;
  43422. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43423. };
  43424. return BounceEase;
  43425. }(EasingFunction));
  43426. BABYLON.BounceEase = BounceEase;
  43427. var CubicEase = /** @class */ (function (_super) {
  43428. __extends(CubicEase, _super);
  43429. function CubicEase() {
  43430. return _super !== null && _super.apply(this, arguments) || this;
  43431. }
  43432. CubicEase.prototype.easeInCore = function (gradient) {
  43433. return (gradient * gradient * gradient);
  43434. };
  43435. return CubicEase;
  43436. }(EasingFunction));
  43437. BABYLON.CubicEase = CubicEase;
  43438. var ElasticEase = /** @class */ (function (_super) {
  43439. __extends(ElasticEase, _super);
  43440. function ElasticEase(oscillations, springiness) {
  43441. if (oscillations === void 0) { oscillations = 3; }
  43442. if (springiness === void 0) { springiness = 3; }
  43443. var _this = _super.call(this) || this;
  43444. _this.oscillations = oscillations;
  43445. _this.springiness = springiness;
  43446. return _this;
  43447. }
  43448. ElasticEase.prototype.easeInCore = function (gradient) {
  43449. var num2;
  43450. var num3 = Math.max(0.0, this.oscillations);
  43451. var num = Math.max(0.0, this.springiness);
  43452. if (num == 0) {
  43453. num2 = gradient;
  43454. }
  43455. else {
  43456. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43457. }
  43458. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43459. };
  43460. return ElasticEase;
  43461. }(EasingFunction));
  43462. BABYLON.ElasticEase = ElasticEase;
  43463. var ExponentialEase = /** @class */ (function (_super) {
  43464. __extends(ExponentialEase, _super);
  43465. function ExponentialEase(exponent) {
  43466. if (exponent === void 0) { exponent = 2; }
  43467. var _this = _super.call(this) || this;
  43468. _this.exponent = exponent;
  43469. return _this;
  43470. }
  43471. ExponentialEase.prototype.easeInCore = function (gradient) {
  43472. if (this.exponent <= 0) {
  43473. return gradient;
  43474. }
  43475. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43476. };
  43477. return ExponentialEase;
  43478. }(EasingFunction));
  43479. BABYLON.ExponentialEase = ExponentialEase;
  43480. var PowerEase = /** @class */ (function (_super) {
  43481. __extends(PowerEase, _super);
  43482. function PowerEase(power) {
  43483. if (power === void 0) { power = 2; }
  43484. var _this = _super.call(this) || this;
  43485. _this.power = power;
  43486. return _this;
  43487. }
  43488. PowerEase.prototype.easeInCore = function (gradient) {
  43489. var y = Math.max(0.0, this.power);
  43490. return Math.pow(gradient, y);
  43491. };
  43492. return PowerEase;
  43493. }(EasingFunction));
  43494. BABYLON.PowerEase = PowerEase;
  43495. var QuadraticEase = /** @class */ (function (_super) {
  43496. __extends(QuadraticEase, _super);
  43497. function QuadraticEase() {
  43498. return _super !== null && _super.apply(this, arguments) || this;
  43499. }
  43500. QuadraticEase.prototype.easeInCore = function (gradient) {
  43501. return (gradient * gradient);
  43502. };
  43503. return QuadraticEase;
  43504. }(EasingFunction));
  43505. BABYLON.QuadraticEase = QuadraticEase;
  43506. var QuarticEase = /** @class */ (function (_super) {
  43507. __extends(QuarticEase, _super);
  43508. function QuarticEase() {
  43509. return _super !== null && _super.apply(this, arguments) || this;
  43510. }
  43511. QuarticEase.prototype.easeInCore = function (gradient) {
  43512. return (gradient * gradient * gradient * gradient);
  43513. };
  43514. return QuarticEase;
  43515. }(EasingFunction));
  43516. BABYLON.QuarticEase = QuarticEase;
  43517. var QuinticEase = /** @class */ (function (_super) {
  43518. __extends(QuinticEase, _super);
  43519. function QuinticEase() {
  43520. return _super !== null && _super.apply(this, arguments) || this;
  43521. }
  43522. QuinticEase.prototype.easeInCore = function (gradient) {
  43523. return (gradient * gradient * gradient * gradient * gradient);
  43524. };
  43525. return QuinticEase;
  43526. }(EasingFunction));
  43527. BABYLON.QuinticEase = QuinticEase;
  43528. var SineEase = /** @class */ (function (_super) {
  43529. __extends(SineEase, _super);
  43530. function SineEase() {
  43531. return _super !== null && _super.apply(this, arguments) || this;
  43532. }
  43533. SineEase.prototype.easeInCore = function (gradient) {
  43534. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43535. };
  43536. return SineEase;
  43537. }(EasingFunction));
  43538. BABYLON.SineEase = SineEase;
  43539. var BezierCurveEase = /** @class */ (function (_super) {
  43540. __extends(BezierCurveEase, _super);
  43541. function BezierCurveEase(x1, y1, x2, y2) {
  43542. if (x1 === void 0) { x1 = 0; }
  43543. if (y1 === void 0) { y1 = 0; }
  43544. if (x2 === void 0) { x2 = 1; }
  43545. if (y2 === void 0) { y2 = 1; }
  43546. var _this = _super.call(this) || this;
  43547. _this.x1 = x1;
  43548. _this.y1 = y1;
  43549. _this.x2 = x2;
  43550. _this.y2 = y2;
  43551. return _this;
  43552. }
  43553. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43554. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43555. };
  43556. return BezierCurveEase;
  43557. }(EasingFunction));
  43558. BABYLON.BezierCurveEase = BezierCurveEase;
  43559. })(BABYLON || (BABYLON = {}));
  43560. //# sourceMappingURL=babylon.easing.js.map
  43561. var BABYLON;
  43562. (function (BABYLON) {
  43563. var Condition = /** @class */ (function () {
  43564. function Condition(actionManager) {
  43565. this._actionManager = actionManager;
  43566. }
  43567. Condition.prototype.isValid = function () {
  43568. return true;
  43569. };
  43570. Condition.prototype._getProperty = function (propertyPath) {
  43571. return this._actionManager._getProperty(propertyPath);
  43572. };
  43573. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43574. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43575. };
  43576. Condition.prototype.serialize = function () {
  43577. };
  43578. Condition.prototype._serialize = function (serializedCondition) {
  43579. return {
  43580. type: 2,
  43581. children: [],
  43582. name: serializedCondition.name,
  43583. properties: serializedCondition.properties
  43584. };
  43585. };
  43586. return Condition;
  43587. }());
  43588. BABYLON.Condition = Condition;
  43589. var ValueCondition = /** @class */ (function (_super) {
  43590. __extends(ValueCondition, _super);
  43591. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43592. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43593. var _this = _super.call(this, actionManager) || this;
  43594. _this.propertyPath = propertyPath;
  43595. _this.value = value;
  43596. _this.operator = operator;
  43597. _this._target = target;
  43598. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43599. _this._property = _this._getProperty(_this.propertyPath);
  43600. return _this;
  43601. }
  43602. Object.defineProperty(ValueCondition, "IsEqual", {
  43603. get: function () {
  43604. return ValueCondition._IsEqual;
  43605. },
  43606. enumerable: true,
  43607. configurable: true
  43608. });
  43609. Object.defineProperty(ValueCondition, "IsDifferent", {
  43610. get: function () {
  43611. return ValueCondition._IsDifferent;
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. Object.defineProperty(ValueCondition, "IsGreater", {
  43617. get: function () {
  43618. return ValueCondition._IsGreater;
  43619. },
  43620. enumerable: true,
  43621. configurable: true
  43622. });
  43623. Object.defineProperty(ValueCondition, "IsLesser", {
  43624. get: function () {
  43625. return ValueCondition._IsLesser;
  43626. },
  43627. enumerable: true,
  43628. configurable: true
  43629. });
  43630. // Methods
  43631. ValueCondition.prototype.isValid = function () {
  43632. switch (this.operator) {
  43633. case ValueCondition.IsGreater:
  43634. return this._effectiveTarget[this._property] > this.value;
  43635. case ValueCondition.IsLesser:
  43636. return this._effectiveTarget[this._property] < this.value;
  43637. case ValueCondition.IsEqual:
  43638. case ValueCondition.IsDifferent:
  43639. var check;
  43640. if (this.value.equals) {
  43641. check = this.value.equals(this._effectiveTarget[this._property]);
  43642. }
  43643. else {
  43644. check = this.value === this._effectiveTarget[this._property];
  43645. }
  43646. return this.operator === ValueCondition.IsEqual ? check : !check;
  43647. }
  43648. return false;
  43649. };
  43650. ValueCondition.prototype.serialize = function () {
  43651. return this._serialize({
  43652. name: "ValueCondition",
  43653. properties: [
  43654. BABYLON.Action._GetTargetProperty(this._target),
  43655. { name: "propertyPath", value: this.propertyPath },
  43656. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43657. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43658. ]
  43659. });
  43660. };
  43661. ValueCondition.GetOperatorName = function (operator) {
  43662. switch (operator) {
  43663. case ValueCondition._IsEqual: return "IsEqual";
  43664. case ValueCondition._IsDifferent: return "IsDifferent";
  43665. case ValueCondition._IsGreater: return "IsGreater";
  43666. case ValueCondition._IsLesser: return "IsLesser";
  43667. default: return "";
  43668. }
  43669. };
  43670. // Statics
  43671. ValueCondition._IsEqual = 0;
  43672. ValueCondition._IsDifferent = 1;
  43673. ValueCondition._IsGreater = 2;
  43674. ValueCondition._IsLesser = 3;
  43675. return ValueCondition;
  43676. }(Condition));
  43677. BABYLON.ValueCondition = ValueCondition;
  43678. var PredicateCondition = /** @class */ (function (_super) {
  43679. __extends(PredicateCondition, _super);
  43680. function PredicateCondition(actionManager, predicate) {
  43681. var _this = _super.call(this, actionManager) || this;
  43682. _this.predicate = predicate;
  43683. return _this;
  43684. }
  43685. PredicateCondition.prototype.isValid = function () {
  43686. return this.predicate();
  43687. };
  43688. return PredicateCondition;
  43689. }(Condition));
  43690. BABYLON.PredicateCondition = PredicateCondition;
  43691. var StateCondition = /** @class */ (function (_super) {
  43692. __extends(StateCondition, _super);
  43693. function StateCondition(actionManager, target, value) {
  43694. var _this = _super.call(this, actionManager) || this;
  43695. _this.value = value;
  43696. _this._target = target;
  43697. return _this;
  43698. }
  43699. // Methods
  43700. StateCondition.prototype.isValid = function () {
  43701. return this._target.state === this.value;
  43702. };
  43703. StateCondition.prototype.serialize = function () {
  43704. return this._serialize({
  43705. name: "StateCondition",
  43706. properties: [
  43707. BABYLON.Action._GetTargetProperty(this._target),
  43708. { name: "value", value: this.value }
  43709. ]
  43710. });
  43711. };
  43712. return StateCondition;
  43713. }(Condition));
  43714. BABYLON.StateCondition = StateCondition;
  43715. })(BABYLON || (BABYLON = {}));
  43716. //# sourceMappingURL=babylon.condition.js.map
  43717. var BABYLON;
  43718. (function (BABYLON) {
  43719. var Action = /** @class */ (function () {
  43720. function Action(triggerOptions, condition) {
  43721. this.triggerOptions = triggerOptions;
  43722. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43723. if (triggerOptions.parameter) {
  43724. this.trigger = triggerOptions.trigger;
  43725. this._triggerParameter = triggerOptions.parameter;
  43726. }
  43727. else {
  43728. this.trigger = triggerOptions;
  43729. }
  43730. this._nextActiveAction = this;
  43731. this._condition = condition;
  43732. }
  43733. // Methods
  43734. Action.prototype._prepare = function () {
  43735. };
  43736. Action.prototype.getTriggerParameter = function () {
  43737. return this._triggerParameter;
  43738. };
  43739. Action.prototype._executeCurrent = function (evt) {
  43740. if (this._nextActiveAction._condition) {
  43741. var condition = this._nextActiveAction._condition;
  43742. var currentRenderId = this._actionManager.getScene().getRenderId();
  43743. // We cache the current evaluation for the current frame
  43744. if (condition._evaluationId === currentRenderId) {
  43745. if (!condition._currentResult) {
  43746. return;
  43747. }
  43748. }
  43749. else {
  43750. condition._evaluationId = currentRenderId;
  43751. if (!condition.isValid()) {
  43752. condition._currentResult = false;
  43753. return;
  43754. }
  43755. condition._currentResult = true;
  43756. }
  43757. }
  43758. this.onBeforeExecuteObservable.notifyObservers(this);
  43759. this._nextActiveAction.execute(evt);
  43760. this.skipToNextActiveAction();
  43761. };
  43762. Action.prototype.execute = function (evt) {
  43763. };
  43764. Action.prototype.skipToNextActiveAction = function () {
  43765. if (this._nextActiveAction._child) {
  43766. if (!this._nextActiveAction._child._actionManager) {
  43767. this._nextActiveAction._child._actionManager = this._actionManager;
  43768. }
  43769. this._nextActiveAction = this._nextActiveAction._child;
  43770. }
  43771. else {
  43772. this._nextActiveAction = this;
  43773. }
  43774. };
  43775. Action.prototype.then = function (action) {
  43776. this._child = action;
  43777. action._actionManager = this._actionManager;
  43778. action._prepare();
  43779. return action;
  43780. };
  43781. Action.prototype._getProperty = function (propertyPath) {
  43782. return this._actionManager._getProperty(propertyPath);
  43783. };
  43784. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43785. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43786. };
  43787. Action.prototype.serialize = function (parent) {
  43788. };
  43789. // Called by BABYLON.Action objects in serialize(...). Internal use
  43790. Action.prototype._serialize = function (serializedAction, parent) {
  43791. var serializationObject = {
  43792. type: 1,
  43793. children: [],
  43794. name: serializedAction.name,
  43795. properties: serializedAction.properties || []
  43796. };
  43797. // Serialize child
  43798. if (this._child) {
  43799. this._child.serialize(serializationObject);
  43800. }
  43801. // Check if "this" has a condition
  43802. if (this._condition) {
  43803. var serializedCondition = this._condition.serialize();
  43804. serializedCondition.children.push(serializationObject);
  43805. if (parent) {
  43806. parent.children.push(serializedCondition);
  43807. }
  43808. return serializedCondition;
  43809. }
  43810. if (parent) {
  43811. parent.children.push(serializationObject);
  43812. }
  43813. return serializationObject;
  43814. };
  43815. Action._SerializeValueAsString = function (value) {
  43816. if (typeof value === "number") {
  43817. return value.toString();
  43818. }
  43819. if (typeof value === "boolean") {
  43820. return value ? "true" : "false";
  43821. }
  43822. if (value instanceof BABYLON.Vector2) {
  43823. return value.x + ", " + value.y;
  43824. }
  43825. if (value instanceof BABYLON.Vector3) {
  43826. return value.x + ", " + value.y + ", " + value.z;
  43827. }
  43828. if (value instanceof BABYLON.Color3) {
  43829. return value.r + ", " + value.g + ", " + value.b;
  43830. }
  43831. if (value instanceof BABYLON.Color4) {
  43832. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43833. }
  43834. return value; // string
  43835. };
  43836. Action._GetTargetProperty = function (target) {
  43837. return {
  43838. name: "target",
  43839. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43840. : target instanceof BABYLON.Light ? "LightProperties"
  43841. : target instanceof BABYLON.Camera ? "CameraProperties"
  43842. : "SceneProperties",
  43843. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43844. };
  43845. };
  43846. return Action;
  43847. }());
  43848. BABYLON.Action = Action;
  43849. })(BABYLON || (BABYLON = {}));
  43850. //# sourceMappingURL=babylon.action.js.map
  43851. var BABYLON;
  43852. (function (BABYLON) {
  43853. /**
  43854. * ActionEvent is the event beint sent when an action is triggered.
  43855. */
  43856. var ActionEvent = /** @class */ (function () {
  43857. /**
  43858. * @param source The mesh or sprite that triggered the action.
  43859. * @param pointerX The X mouse cursor position at the time of the event
  43860. * @param pointerY The Y mouse cursor position at the time of the event
  43861. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43862. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43863. */
  43864. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43865. this.source = source;
  43866. this.pointerX = pointerX;
  43867. this.pointerY = pointerY;
  43868. this.meshUnderPointer = meshUnderPointer;
  43869. this.sourceEvent = sourceEvent;
  43870. this.additionalData = additionalData;
  43871. }
  43872. /**
  43873. * Helper function to auto-create an ActionEvent from a source mesh.
  43874. * @param source The source mesh that triggered the event
  43875. * @param evt {Event} The original (browser) event
  43876. */
  43877. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43878. var scene = source.getScene();
  43879. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43880. };
  43881. /**
  43882. * Helper function to auto-create an ActionEvent from a source mesh.
  43883. * @param source The source sprite that triggered the event
  43884. * @param scene Scene associated with the sprite
  43885. * @param evt {Event} The original (browser) event
  43886. */
  43887. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43888. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43889. };
  43890. /**
  43891. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43892. * @param scene the scene where the event occurred
  43893. * @param evt {Event} The original (browser) event
  43894. */
  43895. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43896. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43897. };
  43898. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43899. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43900. };
  43901. return ActionEvent;
  43902. }());
  43903. BABYLON.ActionEvent = ActionEvent;
  43904. /**
  43905. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43906. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43907. */
  43908. var ActionManager = /** @class */ (function () {
  43909. function ActionManager(scene) {
  43910. // Members
  43911. this.actions = new Array();
  43912. this.hoverCursor = '';
  43913. this._scene = scene;
  43914. scene._actionManagers.push(this);
  43915. }
  43916. Object.defineProperty(ActionManager, "NothingTrigger", {
  43917. get: function () {
  43918. return ActionManager._NothingTrigger;
  43919. },
  43920. enumerable: true,
  43921. configurable: true
  43922. });
  43923. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43924. get: function () {
  43925. return ActionManager._OnPickTrigger;
  43926. },
  43927. enumerable: true,
  43928. configurable: true
  43929. });
  43930. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43931. get: function () {
  43932. return ActionManager._OnLeftPickTrigger;
  43933. },
  43934. enumerable: true,
  43935. configurable: true
  43936. });
  43937. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43938. get: function () {
  43939. return ActionManager._OnRightPickTrigger;
  43940. },
  43941. enumerable: true,
  43942. configurable: true
  43943. });
  43944. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43945. get: function () {
  43946. return ActionManager._OnCenterPickTrigger;
  43947. },
  43948. enumerable: true,
  43949. configurable: true
  43950. });
  43951. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43952. get: function () {
  43953. return ActionManager._OnPickDownTrigger;
  43954. },
  43955. enumerable: true,
  43956. configurable: true
  43957. });
  43958. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43959. get: function () {
  43960. return ActionManager._OnDoublePickTrigger;
  43961. },
  43962. enumerable: true,
  43963. configurable: true
  43964. });
  43965. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43966. get: function () {
  43967. return ActionManager._OnPickUpTrigger;
  43968. },
  43969. enumerable: true,
  43970. configurable: true
  43971. });
  43972. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43973. /// This trigger will only be raised if you also declared a OnPickDown
  43974. get: function () {
  43975. return ActionManager._OnPickOutTrigger;
  43976. },
  43977. enumerable: true,
  43978. configurable: true
  43979. });
  43980. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43981. get: function () {
  43982. return ActionManager._OnLongPressTrigger;
  43983. },
  43984. enumerable: true,
  43985. configurable: true
  43986. });
  43987. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43988. get: function () {
  43989. return ActionManager._OnPointerOverTrigger;
  43990. },
  43991. enumerable: true,
  43992. configurable: true
  43993. });
  43994. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43995. get: function () {
  43996. return ActionManager._OnPointerOutTrigger;
  43997. },
  43998. enumerable: true,
  43999. configurable: true
  44000. });
  44001. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44002. get: function () {
  44003. return ActionManager._OnEveryFrameTrigger;
  44004. },
  44005. enumerable: true,
  44006. configurable: true
  44007. });
  44008. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44009. get: function () {
  44010. return ActionManager._OnIntersectionEnterTrigger;
  44011. },
  44012. enumerable: true,
  44013. configurable: true
  44014. });
  44015. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44016. get: function () {
  44017. return ActionManager._OnIntersectionExitTrigger;
  44018. },
  44019. enumerable: true,
  44020. configurable: true
  44021. });
  44022. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44023. get: function () {
  44024. return ActionManager._OnKeyDownTrigger;
  44025. },
  44026. enumerable: true,
  44027. configurable: true
  44028. });
  44029. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  44030. get: function () {
  44031. return ActionManager._OnKeyUpTrigger;
  44032. },
  44033. enumerable: true,
  44034. configurable: true
  44035. });
  44036. // Methods
  44037. ActionManager.prototype.dispose = function () {
  44038. var index = this._scene._actionManagers.indexOf(this);
  44039. for (var i = 0; i < this.actions.length; i++) {
  44040. var action = this.actions[i];
  44041. ActionManager.Triggers[action.trigger]--;
  44042. if (ActionManager.Triggers[action.trigger] === 0) {
  44043. delete ActionManager.Triggers[action.trigger];
  44044. }
  44045. }
  44046. if (index > -1) {
  44047. this._scene._actionManagers.splice(index, 1);
  44048. }
  44049. };
  44050. ActionManager.prototype.getScene = function () {
  44051. return this._scene;
  44052. };
  44053. /**
  44054. * Does this action manager handles actions of any of the given triggers
  44055. * @param {number[]} triggers - the triggers to be tested
  44056. * @return {boolean} whether one (or more) of the triggers is handeled
  44057. */
  44058. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  44059. for (var index = 0; index < this.actions.length; index++) {
  44060. var action = this.actions[index];
  44061. if (triggers.indexOf(action.trigger) > -1) {
  44062. return true;
  44063. }
  44064. }
  44065. return false;
  44066. };
  44067. /**
  44068. * Does this action manager handles actions of a given trigger
  44069. * @param {number} trigger - the trigger to be tested
  44070. * @return {boolean} whether the trigger is handeled
  44071. */
  44072. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  44073. for (var index = 0; index < this.actions.length; index++) {
  44074. var action = this.actions[index];
  44075. if (action.trigger === trigger) {
  44076. return true;
  44077. }
  44078. }
  44079. return false;
  44080. };
  44081. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  44082. /**
  44083. * Does this action manager has pointer triggers
  44084. * @return {boolean} whether or not it has pointer triggers
  44085. */
  44086. get: function () {
  44087. for (var index = 0; index < this.actions.length; index++) {
  44088. var action = this.actions[index];
  44089. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  44090. return true;
  44091. }
  44092. }
  44093. return false;
  44094. },
  44095. enumerable: true,
  44096. configurable: true
  44097. });
  44098. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  44099. /**
  44100. * Does this action manager has pick triggers
  44101. * @return {boolean} whether or not it has pick triggers
  44102. */
  44103. get: function () {
  44104. for (var index = 0; index < this.actions.length; index++) {
  44105. var action = this.actions[index];
  44106. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44107. return true;
  44108. }
  44109. }
  44110. return false;
  44111. },
  44112. enumerable: true,
  44113. configurable: true
  44114. });
  44115. Object.defineProperty(ActionManager, "HasTriggers", {
  44116. /**
  44117. * Does exist one action manager with at least one trigger
  44118. * @return {boolean} whether or not it exists one action manager with one trigger
  44119. **/
  44120. get: function () {
  44121. for (var t in ActionManager.Triggers) {
  44122. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44123. return true;
  44124. }
  44125. }
  44126. return false;
  44127. },
  44128. enumerable: true,
  44129. configurable: true
  44130. });
  44131. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44132. /**
  44133. * Does exist one action manager with at least one pick trigger
  44134. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44135. **/
  44136. get: function () {
  44137. for (var t in ActionManager.Triggers) {
  44138. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44139. var t_int = parseInt(t);
  44140. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44141. return true;
  44142. }
  44143. }
  44144. }
  44145. return false;
  44146. },
  44147. enumerable: true,
  44148. configurable: true
  44149. });
  44150. /**
  44151. * Does exist one action manager that handles actions of a given trigger
  44152. * @param {number} trigger - the trigger to be tested
  44153. * @return {boolean} whether the trigger is handeled by at least one action manager
  44154. **/
  44155. ActionManager.HasSpecificTrigger = function (trigger) {
  44156. for (var t in ActionManager.Triggers) {
  44157. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44158. var t_int = parseInt(t);
  44159. if (t_int === trigger) {
  44160. return true;
  44161. }
  44162. }
  44163. }
  44164. return false;
  44165. };
  44166. /**
  44167. * Registers an action to this action manager
  44168. * @param {BABYLON.Action} action - the action to be registered
  44169. * @return {BABYLON.Action} the action amended (prepared) after registration
  44170. */
  44171. ActionManager.prototype.registerAction = function (action) {
  44172. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44173. if (this.getScene().actionManager !== this) {
  44174. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44175. return null;
  44176. }
  44177. }
  44178. this.actions.push(action);
  44179. if (ActionManager.Triggers[action.trigger]) {
  44180. ActionManager.Triggers[action.trigger]++;
  44181. }
  44182. else {
  44183. ActionManager.Triggers[action.trigger] = 1;
  44184. }
  44185. action._actionManager = this;
  44186. action._prepare();
  44187. return action;
  44188. };
  44189. /**
  44190. * Process a specific trigger
  44191. * @param {number} trigger - the trigger to process
  44192. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44193. */
  44194. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44195. for (var index = 0; index < this.actions.length; index++) {
  44196. var action = this.actions[index];
  44197. if (action.trigger === trigger) {
  44198. if (evt) {
  44199. if (trigger === ActionManager.OnKeyUpTrigger
  44200. || trigger === ActionManager.OnKeyDownTrigger) {
  44201. var parameter = action.getTriggerParameter();
  44202. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44203. if (!parameter.toLowerCase) {
  44204. continue;
  44205. }
  44206. var lowerCase = parameter.toLowerCase();
  44207. if (lowerCase !== evt.sourceEvent.key) {
  44208. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44209. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44210. if (actualkey !== lowerCase) {
  44211. continue;
  44212. }
  44213. }
  44214. }
  44215. }
  44216. }
  44217. action._executeCurrent(evt);
  44218. }
  44219. }
  44220. };
  44221. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44222. var properties = propertyPath.split(".");
  44223. for (var index = 0; index < properties.length - 1; index++) {
  44224. target = target[properties[index]];
  44225. }
  44226. return target;
  44227. };
  44228. ActionManager.prototype._getProperty = function (propertyPath) {
  44229. var properties = propertyPath.split(".");
  44230. return properties[properties.length - 1];
  44231. };
  44232. ActionManager.prototype.serialize = function (name) {
  44233. var root = {
  44234. children: new Array(),
  44235. name: name,
  44236. type: 3,
  44237. properties: new Array() // Empty for root but required
  44238. };
  44239. for (var i = 0; i < this.actions.length; i++) {
  44240. var triggerObject = {
  44241. type: 0,
  44242. children: new Array(),
  44243. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44244. properties: new Array()
  44245. };
  44246. var triggerOptions = this.actions[i].triggerOptions;
  44247. if (triggerOptions && typeof triggerOptions !== "number") {
  44248. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44249. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44250. }
  44251. else {
  44252. var parameter = {};
  44253. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44254. if (triggerOptions.parameter.mesh) {
  44255. parameter._meshId = triggerOptions.parameter.mesh.id;
  44256. }
  44257. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44258. }
  44259. }
  44260. // Serialize child action, recursively
  44261. this.actions[i].serialize(triggerObject);
  44262. // Add serialized trigger
  44263. root.children.push(triggerObject);
  44264. }
  44265. return root;
  44266. };
  44267. ActionManager.Parse = function (parsedActions, object, scene) {
  44268. var actionManager = new ActionManager(scene);
  44269. if (object === null)
  44270. scene.actionManager = actionManager;
  44271. else
  44272. object.actionManager = actionManager;
  44273. // instanciate a new object
  44274. var instanciate = function (name, params) {
  44275. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44276. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44277. newInstance.constructor.apply(newInstance, params);
  44278. return newInstance;
  44279. };
  44280. var parseParameter = function (name, value, target, propertyPath) {
  44281. if (propertyPath === null) {
  44282. // String, boolean or float
  44283. var floatValue = parseFloat(value);
  44284. if (value === "true" || value === "false")
  44285. return value === "true";
  44286. else
  44287. return isNaN(floatValue) ? value : floatValue;
  44288. }
  44289. var effectiveTarget = propertyPath.split(".");
  44290. var values = value.split(",");
  44291. // Get effective Target
  44292. for (var i = 0; i < effectiveTarget.length; i++) {
  44293. target = target[effectiveTarget[i]];
  44294. }
  44295. // Return appropriate value with its type
  44296. if (typeof (target) === "boolean")
  44297. return values[0] === "true";
  44298. if (typeof (target) === "string")
  44299. return values[0];
  44300. // Parameters with multiple values such as Vector3 etc.
  44301. var split = new Array();
  44302. for (var i = 0; i < values.length; i++)
  44303. split.push(parseFloat(values[i]));
  44304. if (target instanceof BABYLON.Vector3)
  44305. return BABYLON.Vector3.FromArray(split);
  44306. if (target instanceof BABYLON.Vector4)
  44307. return BABYLON.Vector4.FromArray(split);
  44308. if (target instanceof BABYLON.Color3)
  44309. return BABYLON.Color3.FromArray(split);
  44310. if (target instanceof BABYLON.Color4)
  44311. return BABYLON.Color4.FromArray(split);
  44312. return parseFloat(values[0]);
  44313. };
  44314. // traverse graph per trigger
  44315. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44316. if (combineArray === void 0) { combineArray = null; }
  44317. if (parsedAction.detached)
  44318. return;
  44319. var parameters = new Array();
  44320. var target = null;
  44321. var propertyPath = null;
  44322. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44323. // Parameters
  44324. if (parsedAction.type === 2)
  44325. parameters.push(actionManager);
  44326. else
  44327. parameters.push(trigger);
  44328. if (combine) {
  44329. var actions = new Array();
  44330. for (var j = 0; j < parsedAction.combine.length; j++) {
  44331. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44332. }
  44333. parameters.push(actions);
  44334. }
  44335. else {
  44336. for (var i = 0; i < parsedAction.properties.length; i++) {
  44337. var value = parsedAction.properties[i].value;
  44338. var name = parsedAction.properties[i].name;
  44339. var targetType = parsedAction.properties[i].targetType;
  44340. if (name === "target")
  44341. if (targetType !== null && targetType === "SceneProperties")
  44342. value = target = scene;
  44343. else
  44344. value = target = scene.getNodeByName(value);
  44345. else if (name === "parent")
  44346. value = scene.getNodeByName(value);
  44347. else if (name === "sound")
  44348. value = scene.getSoundByName(value);
  44349. else if (name !== "propertyPath") {
  44350. if (parsedAction.type === 2 && name === "operator")
  44351. value = BABYLON.ValueCondition[value];
  44352. else
  44353. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44354. }
  44355. else {
  44356. propertyPath = value;
  44357. }
  44358. parameters.push(value);
  44359. }
  44360. }
  44361. if (combineArray === null) {
  44362. parameters.push(condition);
  44363. }
  44364. else {
  44365. parameters.push(null);
  44366. }
  44367. // If interpolate value action
  44368. if (parsedAction.name === "InterpolateValueAction") {
  44369. var param = parameters[parameters.length - 2];
  44370. parameters[parameters.length - 1] = param;
  44371. parameters[parameters.length - 2] = condition;
  44372. }
  44373. // Action or condition(s) and not CombineAction
  44374. var newAction = instanciate(parsedAction.name, parameters);
  44375. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44376. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44377. if (action)
  44378. action.then(nothing);
  44379. else
  44380. actionManager.registerAction(nothing);
  44381. action = nothing;
  44382. }
  44383. if (combineArray === null) {
  44384. if (newAction instanceof BABYLON.Condition) {
  44385. condition = newAction;
  44386. newAction = action;
  44387. }
  44388. else {
  44389. condition = null;
  44390. if (action)
  44391. action.then(newAction);
  44392. else
  44393. actionManager.registerAction(newAction);
  44394. }
  44395. }
  44396. else {
  44397. combineArray.push(newAction);
  44398. }
  44399. for (var i = 0; i < parsedAction.children.length; i++)
  44400. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44401. };
  44402. // triggers
  44403. for (var i = 0; i < parsedActions.children.length; i++) {
  44404. var triggerParams;
  44405. var trigger = parsedActions.children[i];
  44406. if (trigger.properties.length > 0) {
  44407. var param = trigger.properties[0].value;
  44408. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44409. if (value._meshId) {
  44410. value.mesh = scene.getMeshByID(value._meshId);
  44411. }
  44412. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44413. }
  44414. else
  44415. triggerParams = ActionManager[trigger.name];
  44416. for (var j = 0; j < trigger.children.length; j++) {
  44417. if (!trigger.detached)
  44418. traverse(trigger.children[j], triggerParams, null, null);
  44419. }
  44420. }
  44421. };
  44422. ActionManager.GetTriggerName = function (trigger) {
  44423. switch (trigger) {
  44424. case 0: return "NothingTrigger";
  44425. case 1: return "OnPickTrigger";
  44426. case 2: return "OnLeftPickTrigger";
  44427. case 3: return "OnRightPickTrigger";
  44428. case 4: return "OnCenterPickTrigger";
  44429. case 5: return "OnPickDownTrigger";
  44430. case 6: return "OnPickUpTrigger";
  44431. case 7: return "OnLongPressTrigger";
  44432. case 8: return "OnPointerOverTrigger";
  44433. case 9: return "OnPointerOutTrigger";
  44434. case 10: return "OnEveryFrameTrigger";
  44435. case 11: return "OnIntersectionEnterTrigger";
  44436. case 12: return "OnIntersectionExitTrigger";
  44437. case 13: return "OnKeyDownTrigger";
  44438. case 14: return "OnKeyUpTrigger";
  44439. case 15: return "OnPickOutTrigger";
  44440. default: return "";
  44441. }
  44442. };
  44443. // Statics
  44444. ActionManager._NothingTrigger = 0;
  44445. ActionManager._OnPickTrigger = 1;
  44446. ActionManager._OnLeftPickTrigger = 2;
  44447. ActionManager._OnRightPickTrigger = 3;
  44448. ActionManager._OnCenterPickTrigger = 4;
  44449. ActionManager._OnPickDownTrigger = 5;
  44450. ActionManager._OnDoublePickTrigger = 6;
  44451. ActionManager._OnPickUpTrigger = 7;
  44452. ActionManager._OnLongPressTrigger = 8;
  44453. ActionManager._OnPointerOverTrigger = 9;
  44454. ActionManager._OnPointerOutTrigger = 10;
  44455. ActionManager._OnEveryFrameTrigger = 11;
  44456. ActionManager._OnIntersectionEnterTrigger = 12;
  44457. ActionManager._OnIntersectionExitTrigger = 13;
  44458. ActionManager._OnKeyDownTrigger = 14;
  44459. ActionManager._OnKeyUpTrigger = 15;
  44460. ActionManager._OnPickOutTrigger = 16;
  44461. ActionManager.Triggers = {};
  44462. return ActionManager;
  44463. }());
  44464. BABYLON.ActionManager = ActionManager;
  44465. })(BABYLON || (BABYLON = {}));
  44466. //# sourceMappingURL=babylon.actionManager.js.map
  44467. var BABYLON;
  44468. (function (BABYLON) {
  44469. var InterpolateValueAction = /** @class */ (function (_super) {
  44470. __extends(InterpolateValueAction, _super);
  44471. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44472. if (duration === void 0) { duration = 1000; }
  44473. var _this = _super.call(this, triggerOptions, condition) || this;
  44474. _this.propertyPath = propertyPath;
  44475. _this.value = value;
  44476. _this.duration = duration;
  44477. _this.stopOtherAnimations = stopOtherAnimations;
  44478. _this.onInterpolationDone = onInterpolationDone;
  44479. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44480. _this._target = _this._effectiveTarget = target;
  44481. return _this;
  44482. }
  44483. InterpolateValueAction.prototype._prepare = function () {
  44484. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44485. this._property = this._getProperty(this.propertyPath);
  44486. };
  44487. InterpolateValueAction.prototype.execute = function () {
  44488. var _this = this;
  44489. var scene = this._actionManager.getScene();
  44490. var keys = [
  44491. {
  44492. frame: 0,
  44493. value: this._effectiveTarget[this._property]
  44494. }, {
  44495. frame: 100,
  44496. value: this.value
  44497. }
  44498. ];
  44499. var dataType;
  44500. if (typeof this.value === "number") {
  44501. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44502. }
  44503. else if (this.value instanceof BABYLON.Color3) {
  44504. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44505. }
  44506. else if (this.value instanceof BABYLON.Vector3) {
  44507. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44508. }
  44509. else if (this.value instanceof BABYLON.Matrix) {
  44510. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44511. }
  44512. else if (this.value instanceof BABYLON.Quaternion) {
  44513. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44514. }
  44515. else {
  44516. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44517. return;
  44518. }
  44519. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44520. animation.setKeys(keys);
  44521. if (this.stopOtherAnimations) {
  44522. scene.stopAnimation(this._effectiveTarget);
  44523. }
  44524. var wrapper = function () {
  44525. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44526. if (_this.onInterpolationDone) {
  44527. _this.onInterpolationDone();
  44528. }
  44529. };
  44530. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44531. };
  44532. InterpolateValueAction.prototype.serialize = function (parent) {
  44533. return _super.prototype._serialize.call(this, {
  44534. name: "InterpolateValueAction",
  44535. properties: [
  44536. BABYLON.Action._GetTargetProperty(this._target),
  44537. { name: "propertyPath", value: this.propertyPath },
  44538. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44539. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44540. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44541. ]
  44542. }, parent);
  44543. };
  44544. return InterpolateValueAction;
  44545. }(BABYLON.Action));
  44546. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44547. })(BABYLON || (BABYLON = {}));
  44548. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44549. var BABYLON;
  44550. (function (BABYLON) {
  44551. var SwitchBooleanAction = /** @class */ (function (_super) {
  44552. __extends(SwitchBooleanAction, _super);
  44553. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44554. var _this = _super.call(this, triggerOptions, condition) || this;
  44555. _this.propertyPath = propertyPath;
  44556. _this._target = _this._effectiveTarget = target;
  44557. return _this;
  44558. }
  44559. SwitchBooleanAction.prototype._prepare = function () {
  44560. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44561. this._property = this._getProperty(this.propertyPath);
  44562. };
  44563. SwitchBooleanAction.prototype.execute = function () {
  44564. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44565. };
  44566. SwitchBooleanAction.prototype.serialize = function (parent) {
  44567. return _super.prototype._serialize.call(this, {
  44568. name: "SwitchBooleanAction",
  44569. properties: [
  44570. BABYLON.Action._GetTargetProperty(this._target),
  44571. { name: "propertyPath", value: this.propertyPath }
  44572. ]
  44573. }, parent);
  44574. };
  44575. return SwitchBooleanAction;
  44576. }(BABYLON.Action));
  44577. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44578. var SetStateAction = /** @class */ (function (_super) {
  44579. __extends(SetStateAction, _super);
  44580. function SetStateAction(triggerOptions, target, value, condition) {
  44581. var _this = _super.call(this, triggerOptions, condition) || this;
  44582. _this.value = value;
  44583. _this._target = target;
  44584. return _this;
  44585. }
  44586. SetStateAction.prototype.execute = function () {
  44587. this._target.state = this.value;
  44588. };
  44589. SetStateAction.prototype.serialize = function (parent) {
  44590. return _super.prototype._serialize.call(this, {
  44591. name: "SetStateAction",
  44592. properties: [
  44593. BABYLON.Action._GetTargetProperty(this._target),
  44594. { name: "value", value: this.value }
  44595. ]
  44596. }, parent);
  44597. };
  44598. return SetStateAction;
  44599. }(BABYLON.Action));
  44600. BABYLON.SetStateAction = SetStateAction;
  44601. var SetValueAction = /** @class */ (function (_super) {
  44602. __extends(SetValueAction, _super);
  44603. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44604. var _this = _super.call(this, triggerOptions, condition) || this;
  44605. _this.propertyPath = propertyPath;
  44606. _this.value = value;
  44607. _this._target = _this._effectiveTarget = target;
  44608. return _this;
  44609. }
  44610. SetValueAction.prototype._prepare = function () {
  44611. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44612. this._property = this._getProperty(this.propertyPath);
  44613. };
  44614. SetValueAction.prototype.execute = function () {
  44615. this._effectiveTarget[this._property] = this.value;
  44616. if (this._target.markAsDirty) {
  44617. this._target.markAsDirty(this._property);
  44618. }
  44619. };
  44620. SetValueAction.prototype.serialize = function (parent) {
  44621. return _super.prototype._serialize.call(this, {
  44622. name: "SetValueAction",
  44623. properties: [
  44624. BABYLON.Action._GetTargetProperty(this._target),
  44625. { name: "propertyPath", value: this.propertyPath },
  44626. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44627. ]
  44628. }, parent);
  44629. };
  44630. return SetValueAction;
  44631. }(BABYLON.Action));
  44632. BABYLON.SetValueAction = SetValueAction;
  44633. var IncrementValueAction = /** @class */ (function (_super) {
  44634. __extends(IncrementValueAction, _super);
  44635. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44636. var _this = _super.call(this, triggerOptions, condition) || this;
  44637. _this.propertyPath = propertyPath;
  44638. _this.value = value;
  44639. _this._target = _this._effectiveTarget = target;
  44640. return _this;
  44641. }
  44642. IncrementValueAction.prototype._prepare = function () {
  44643. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44644. this._property = this._getProperty(this.propertyPath);
  44645. if (typeof this._effectiveTarget[this._property] !== "number") {
  44646. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44647. }
  44648. };
  44649. IncrementValueAction.prototype.execute = function () {
  44650. this._effectiveTarget[this._property] += this.value;
  44651. if (this._target.markAsDirty) {
  44652. this._target.markAsDirty(this._property);
  44653. }
  44654. };
  44655. IncrementValueAction.prototype.serialize = function (parent) {
  44656. return _super.prototype._serialize.call(this, {
  44657. name: "IncrementValueAction",
  44658. properties: [
  44659. BABYLON.Action._GetTargetProperty(this._target),
  44660. { name: "propertyPath", value: this.propertyPath },
  44661. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44662. ]
  44663. }, parent);
  44664. };
  44665. return IncrementValueAction;
  44666. }(BABYLON.Action));
  44667. BABYLON.IncrementValueAction = IncrementValueAction;
  44668. var PlayAnimationAction = /** @class */ (function (_super) {
  44669. __extends(PlayAnimationAction, _super);
  44670. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44671. var _this = _super.call(this, triggerOptions, condition) || this;
  44672. _this.from = from;
  44673. _this.to = to;
  44674. _this.loop = loop;
  44675. _this._target = target;
  44676. return _this;
  44677. }
  44678. PlayAnimationAction.prototype._prepare = function () {
  44679. };
  44680. PlayAnimationAction.prototype.execute = function () {
  44681. var scene = this._actionManager.getScene();
  44682. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44683. };
  44684. PlayAnimationAction.prototype.serialize = function (parent) {
  44685. return _super.prototype._serialize.call(this, {
  44686. name: "PlayAnimationAction",
  44687. properties: [
  44688. BABYLON.Action._GetTargetProperty(this._target),
  44689. { name: "from", value: String(this.from) },
  44690. { name: "to", value: String(this.to) },
  44691. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44692. ]
  44693. }, parent);
  44694. };
  44695. return PlayAnimationAction;
  44696. }(BABYLON.Action));
  44697. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44698. var StopAnimationAction = /** @class */ (function (_super) {
  44699. __extends(StopAnimationAction, _super);
  44700. function StopAnimationAction(triggerOptions, target, condition) {
  44701. var _this = _super.call(this, triggerOptions, condition) || this;
  44702. _this._target = target;
  44703. return _this;
  44704. }
  44705. StopAnimationAction.prototype._prepare = function () {
  44706. };
  44707. StopAnimationAction.prototype.execute = function () {
  44708. var scene = this._actionManager.getScene();
  44709. scene.stopAnimation(this._target);
  44710. };
  44711. StopAnimationAction.prototype.serialize = function (parent) {
  44712. return _super.prototype._serialize.call(this, {
  44713. name: "StopAnimationAction",
  44714. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44715. }, parent);
  44716. };
  44717. return StopAnimationAction;
  44718. }(BABYLON.Action));
  44719. BABYLON.StopAnimationAction = StopAnimationAction;
  44720. var DoNothingAction = /** @class */ (function (_super) {
  44721. __extends(DoNothingAction, _super);
  44722. function DoNothingAction(triggerOptions, condition) {
  44723. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44724. return _super.call(this, triggerOptions, condition) || this;
  44725. }
  44726. DoNothingAction.prototype.execute = function () {
  44727. };
  44728. DoNothingAction.prototype.serialize = function (parent) {
  44729. return _super.prototype._serialize.call(this, {
  44730. name: "DoNothingAction",
  44731. properties: []
  44732. }, parent);
  44733. };
  44734. return DoNothingAction;
  44735. }(BABYLON.Action));
  44736. BABYLON.DoNothingAction = DoNothingAction;
  44737. var CombineAction = /** @class */ (function (_super) {
  44738. __extends(CombineAction, _super);
  44739. function CombineAction(triggerOptions, children, condition) {
  44740. var _this = _super.call(this, triggerOptions, condition) || this;
  44741. _this.children = children;
  44742. return _this;
  44743. }
  44744. CombineAction.prototype._prepare = function () {
  44745. for (var index = 0; index < this.children.length; index++) {
  44746. this.children[index]._actionManager = this._actionManager;
  44747. this.children[index]._prepare();
  44748. }
  44749. };
  44750. CombineAction.prototype.execute = function (evt) {
  44751. for (var index = 0; index < this.children.length; index++) {
  44752. this.children[index].execute(evt);
  44753. }
  44754. };
  44755. CombineAction.prototype.serialize = function (parent) {
  44756. var serializationObject = _super.prototype._serialize.call(this, {
  44757. name: "CombineAction",
  44758. properties: [],
  44759. combine: []
  44760. }, parent);
  44761. for (var i = 0; i < this.children.length; i++) {
  44762. serializationObject.combine.push(this.children[i].serialize(null));
  44763. }
  44764. return serializationObject;
  44765. };
  44766. return CombineAction;
  44767. }(BABYLON.Action));
  44768. BABYLON.CombineAction = CombineAction;
  44769. var ExecuteCodeAction = /** @class */ (function (_super) {
  44770. __extends(ExecuteCodeAction, _super);
  44771. function ExecuteCodeAction(triggerOptions, func, condition) {
  44772. var _this = _super.call(this, triggerOptions, condition) || this;
  44773. _this.func = func;
  44774. return _this;
  44775. }
  44776. ExecuteCodeAction.prototype.execute = function (evt) {
  44777. this.func(evt);
  44778. };
  44779. return ExecuteCodeAction;
  44780. }(BABYLON.Action));
  44781. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44782. var SetParentAction = /** @class */ (function (_super) {
  44783. __extends(SetParentAction, _super);
  44784. function SetParentAction(triggerOptions, target, parent, condition) {
  44785. var _this = _super.call(this, triggerOptions, condition) || this;
  44786. _this._target = target;
  44787. _this._parent = parent;
  44788. return _this;
  44789. }
  44790. SetParentAction.prototype._prepare = function () {
  44791. };
  44792. SetParentAction.prototype.execute = function () {
  44793. if (this._target.parent === this._parent) {
  44794. return;
  44795. }
  44796. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44797. invertParentWorldMatrix.invert();
  44798. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44799. this._target.parent = this._parent;
  44800. };
  44801. SetParentAction.prototype.serialize = function (parent) {
  44802. return _super.prototype._serialize.call(this, {
  44803. name: "SetParentAction",
  44804. properties: [
  44805. BABYLON.Action._GetTargetProperty(this._target),
  44806. BABYLON.Action._GetTargetProperty(this._parent),
  44807. ]
  44808. }, parent);
  44809. };
  44810. return SetParentAction;
  44811. }(BABYLON.Action));
  44812. BABYLON.SetParentAction = SetParentAction;
  44813. var PlaySoundAction = /** @class */ (function (_super) {
  44814. __extends(PlaySoundAction, _super);
  44815. function PlaySoundAction(triggerOptions, sound, condition) {
  44816. var _this = _super.call(this, triggerOptions, condition) || this;
  44817. _this._sound = sound;
  44818. return _this;
  44819. }
  44820. PlaySoundAction.prototype._prepare = function () {
  44821. };
  44822. PlaySoundAction.prototype.execute = function () {
  44823. if (this._sound !== undefined)
  44824. this._sound.play();
  44825. };
  44826. PlaySoundAction.prototype.serialize = function (parent) {
  44827. return _super.prototype._serialize.call(this, {
  44828. name: "PlaySoundAction",
  44829. properties: [{ name: "sound", value: this._sound.name }]
  44830. }, parent);
  44831. };
  44832. return PlaySoundAction;
  44833. }(BABYLON.Action));
  44834. BABYLON.PlaySoundAction = PlaySoundAction;
  44835. var StopSoundAction = /** @class */ (function (_super) {
  44836. __extends(StopSoundAction, _super);
  44837. function StopSoundAction(triggerOptions, sound, condition) {
  44838. var _this = _super.call(this, triggerOptions, condition) || this;
  44839. _this._sound = sound;
  44840. return _this;
  44841. }
  44842. StopSoundAction.prototype._prepare = function () {
  44843. };
  44844. StopSoundAction.prototype.execute = function () {
  44845. if (this._sound !== undefined)
  44846. this._sound.stop();
  44847. };
  44848. StopSoundAction.prototype.serialize = function (parent) {
  44849. return _super.prototype._serialize.call(this, {
  44850. name: "StopSoundAction",
  44851. properties: [{ name: "sound", value: this._sound.name }]
  44852. }, parent);
  44853. };
  44854. return StopSoundAction;
  44855. }(BABYLON.Action));
  44856. BABYLON.StopSoundAction = StopSoundAction;
  44857. })(BABYLON || (BABYLON = {}));
  44858. //# sourceMappingURL=babylon.directActions.js.map
  44859. var BABYLON;
  44860. (function (BABYLON) {
  44861. var SpriteManager = /** @class */ (function () {
  44862. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44863. if (epsilon === void 0) { epsilon = 0.01; }
  44864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44865. this.name = name;
  44866. this.sprites = new Array();
  44867. this.renderingGroupId = 0;
  44868. this.layerMask = 0x0FFFFFFF;
  44869. this.fogEnabled = true;
  44870. this.isPickable = false;
  44871. /**
  44872. * An event triggered when the manager is disposed.
  44873. * @type {BABYLON.Observable}
  44874. */
  44875. this.onDisposeObservable = new BABYLON.Observable();
  44876. this._vertexBuffers = {};
  44877. this._capacity = capacity;
  44878. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44879. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44880. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44881. if (cellSize.width && cellSize.height) {
  44882. this.cellWidth = cellSize.width;
  44883. this.cellHeight = cellSize.height;
  44884. }
  44885. else if (cellSize !== undefined) {
  44886. this.cellWidth = cellSize;
  44887. this.cellHeight = cellSize;
  44888. }
  44889. else {
  44890. return;
  44891. }
  44892. this._epsilon = epsilon;
  44893. this._scene = scene;
  44894. this._scene.spriteManagers.push(this);
  44895. var indices = [];
  44896. var index = 0;
  44897. for (var count = 0; count < capacity; count++) {
  44898. indices.push(index);
  44899. indices.push(index + 1);
  44900. indices.push(index + 2);
  44901. indices.push(index);
  44902. indices.push(index + 2);
  44903. indices.push(index + 3);
  44904. index += 4;
  44905. }
  44906. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44907. // VBO
  44908. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44909. this._vertexData = new Float32Array(capacity * 16 * 4);
  44910. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44911. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44912. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44913. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44914. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44915. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44916. this._vertexBuffers["options"] = options;
  44917. this._vertexBuffers["cellInfo"] = cellInfo;
  44918. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44919. // Effects
  44920. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44921. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44922. }
  44923. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44924. set: function (callback) {
  44925. if (this._onDisposeObserver) {
  44926. this.onDisposeObservable.remove(this._onDisposeObserver);
  44927. }
  44928. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44929. },
  44930. enumerable: true,
  44931. configurable: true
  44932. });
  44933. Object.defineProperty(SpriteManager.prototype, "texture", {
  44934. get: function () {
  44935. return this._spriteTexture;
  44936. },
  44937. set: function (value) {
  44938. this._spriteTexture = value;
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44944. var arrayOffset = index * 16;
  44945. if (offsetX === 0)
  44946. offsetX = this._epsilon;
  44947. else if (offsetX === 1)
  44948. offsetX = 1 - this._epsilon;
  44949. if (offsetY === 0)
  44950. offsetY = this._epsilon;
  44951. else if (offsetY === 1)
  44952. offsetY = 1 - this._epsilon;
  44953. this._vertexData[arrayOffset] = sprite.position.x;
  44954. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44955. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44956. this._vertexData[arrayOffset + 3] = sprite.angle;
  44957. this._vertexData[arrayOffset + 4] = sprite.width;
  44958. this._vertexData[arrayOffset + 5] = sprite.height;
  44959. this._vertexData[arrayOffset + 6] = offsetX;
  44960. this._vertexData[arrayOffset + 7] = offsetY;
  44961. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44962. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44963. var offset = (sprite.cellIndex / rowSize) >> 0;
  44964. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44965. this._vertexData[arrayOffset + 11] = offset;
  44966. // Color
  44967. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44968. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44969. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44970. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44971. };
  44972. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44973. var count = Math.min(this._capacity, this.sprites.length);
  44974. var min = BABYLON.Vector3.Zero();
  44975. var max = BABYLON.Vector3.Zero();
  44976. var distance = Number.MAX_VALUE;
  44977. var currentSprite = null;
  44978. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44979. var cameraView = camera.getViewMatrix();
  44980. for (var index = 0; index < count; index++) {
  44981. var sprite = this.sprites[index];
  44982. if (!sprite) {
  44983. continue;
  44984. }
  44985. if (predicate) {
  44986. if (!predicate(sprite)) {
  44987. continue;
  44988. }
  44989. }
  44990. else if (!sprite.isPickable) {
  44991. continue;
  44992. }
  44993. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44994. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44995. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44996. if (ray.intersectsBoxMinMax(min, max)) {
  44997. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44998. if (distance > currentDistance) {
  44999. distance = currentDistance;
  45000. currentSprite = sprite;
  45001. if (fastCheck) {
  45002. break;
  45003. }
  45004. }
  45005. }
  45006. }
  45007. if (currentSprite) {
  45008. var result = new BABYLON.PickingInfo();
  45009. result.hit = true;
  45010. result.pickedSprite = currentSprite;
  45011. result.distance = distance;
  45012. return result;
  45013. }
  45014. return null;
  45015. };
  45016. SpriteManager.prototype.render = function () {
  45017. // Check
  45018. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  45019. return;
  45020. var engine = this._scene.getEngine();
  45021. var baseSize = this._spriteTexture.getBaseSize();
  45022. // Sprites
  45023. var deltaTime = engine.getDeltaTime();
  45024. var max = Math.min(this._capacity, this.sprites.length);
  45025. var rowSize = baseSize.width / this.cellWidth;
  45026. var offset = 0;
  45027. for (var index = 0; index < max; index++) {
  45028. var sprite = this.sprites[index];
  45029. if (!sprite) {
  45030. continue;
  45031. }
  45032. sprite._animate(deltaTime);
  45033. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  45034. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  45035. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  45036. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  45037. }
  45038. this._buffer.update(this._vertexData);
  45039. // Render
  45040. var effect = this._effectBase;
  45041. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45042. effect = this._effectFog;
  45043. }
  45044. engine.enableEffect(effect);
  45045. var viewMatrix = this._scene.getViewMatrix();
  45046. effect.setTexture("diffuseSampler", this._spriteTexture);
  45047. effect.setMatrix("view", viewMatrix);
  45048. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45049. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  45050. // Fog
  45051. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45052. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  45053. effect.setColor3("vFogColor", this._scene.fogColor);
  45054. }
  45055. // VBOs
  45056. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45057. // Draw order
  45058. engine.setDepthFunctionToLessOrEqual();
  45059. effect.setBool("alphaTest", true);
  45060. engine.setColorWrite(false);
  45061. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45062. engine.setColorWrite(true);
  45063. effect.setBool("alphaTest", false);
  45064. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45065. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45066. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45067. };
  45068. SpriteManager.prototype.dispose = function () {
  45069. if (this._buffer) {
  45070. this._buffer.dispose();
  45071. this._buffer = null;
  45072. }
  45073. if (this._indexBuffer) {
  45074. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45075. this._indexBuffer = null;
  45076. }
  45077. if (this._spriteTexture) {
  45078. this._spriteTexture.dispose();
  45079. this._spriteTexture = null;
  45080. }
  45081. // Remove from scene
  45082. var index = this._scene.spriteManagers.indexOf(this);
  45083. this._scene.spriteManagers.splice(index, 1);
  45084. // Callback
  45085. this.onDisposeObservable.notifyObservers(this);
  45086. this.onDisposeObservable.clear();
  45087. };
  45088. return SpriteManager;
  45089. }());
  45090. BABYLON.SpriteManager = SpriteManager;
  45091. })(BABYLON || (BABYLON = {}));
  45092. //# sourceMappingURL=babylon.spriteManager.js.map
  45093. var BABYLON;
  45094. (function (BABYLON) {
  45095. var Sprite = /** @class */ (function () {
  45096. function Sprite(name, manager) {
  45097. this.name = name;
  45098. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45099. this.width = 1.0;
  45100. this.height = 1.0;
  45101. this.angle = 0;
  45102. this.cellIndex = 0;
  45103. this.invertU = 0;
  45104. this.invertV = 0;
  45105. this.animations = new Array();
  45106. this.isPickable = false;
  45107. this._animationStarted = false;
  45108. this._loopAnimation = false;
  45109. this._fromIndex = 0;
  45110. this._toIndex = 0;
  45111. this._delay = 0;
  45112. this._direction = 1;
  45113. this._time = 0;
  45114. this._manager = manager;
  45115. this._manager.sprites.push(this);
  45116. this.position = BABYLON.Vector3.Zero();
  45117. }
  45118. Object.defineProperty(Sprite.prototype, "size", {
  45119. get: function () {
  45120. return this.width;
  45121. },
  45122. set: function (value) {
  45123. this.width = value;
  45124. this.height = value;
  45125. },
  45126. enumerable: true,
  45127. configurable: true
  45128. });
  45129. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45130. this._fromIndex = from;
  45131. this._toIndex = to;
  45132. this._loopAnimation = loop;
  45133. this._delay = delay;
  45134. this._animationStarted = true;
  45135. this._direction = from < to ? 1 : -1;
  45136. this.cellIndex = from;
  45137. this._time = 0;
  45138. this._onAnimationEnd = onAnimationEnd;
  45139. };
  45140. Sprite.prototype.stopAnimation = function () {
  45141. this._animationStarted = false;
  45142. };
  45143. Sprite.prototype._animate = function (deltaTime) {
  45144. if (!this._animationStarted)
  45145. return;
  45146. this._time += deltaTime;
  45147. if (this._time > this._delay) {
  45148. this._time = this._time % this._delay;
  45149. this.cellIndex += this._direction;
  45150. if (this.cellIndex > this._toIndex) {
  45151. if (this._loopAnimation) {
  45152. this.cellIndex = this._fromIndex;
  45153. }
  45154. else {
  45155. this.cellIndex = this._toIndex;
  45156. this._animationStarted = false;
  45157. if (this._onAnimationEnd) {
  45158. this._onAnimationEnd();
  45159. }
  45160. if (this.disposeWhenFinishedAnimating) {
  45161. this.dispose();
  45162. }
  45163. }
  45164. }
  45165. }
  45166. };
  45167. Sprite.prototype.dispose = function () {
  45168. for (var i = 0; i < this._manager.sprites.length; i++) {
  45169. if (this._manager.sprites[i] == this) {
  45170. this._manager.sprites.splice(i, 1);
  45171. }
  45172. }
  45173. };
  45174. return Sprite;
  45175. }());
  45176. BABYLON.Sprite = Sprite;
  45177. })(BABYLON || (BABYLON = {}));
  45178. //# sourceMappingURL=babylon.sprite.js.map
  45179. var BABYLON;
  45180. (function (BABYLON) {
  45181. var IntersectionInfo = /** @class */ (function () {
  45182. function IntersectionInfo(bu, bv, distance) {
  45183. this.bu = bu;
  45184. this.bv = bv;
  45185. this.distance = distance;
  45186. this.faceId = 0;
  45187. this.subMeshId = 0;
  45188. }
  45189. return IntersectionInfo;
  45190. }());
  45191. BABYLON.IntersectionInfo = IntersectionInfo;
  45192. var PickingInfo = /** @class */ (function () {
  45193. function PickingInfo() {
  45194. this.hit = false;
  45195. this.distance = 0;
  45196. this.pickedPoint = null;
  45197. this.pickedMesh = null;
  45198. this.bu = 0;
  45199. this.bv = 0;
  45200. this.faceId = -1;
  45201. this.subMeshId = 0;
  45202. this.pickedSprite = null;
  45203. }
  45204. // Methods
  45205. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45206. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45207. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45208. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45209. return null;
  45210. }
  45211. var indices = this.pickedMesh.getIndices();
  45212. if (!indices) {
  45213. return null;
  45214. }
  45215. var result;
  45216. if (useVerticesNormals) {
  45217. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45218. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45219. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45220. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45221. normal0 = normal0.scale(this.bu);
  45222. normal1 = normal1.scale(this.bv);
  45223. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45224. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45225. }
  45226. else {
  45227. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45228. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45229. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45230. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45231. var p1p2 = vertex1.subtract(vertex2);
  45232. var p3p2 = vertex3.subtract(vertex2);
  45233. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45234. }
  45235. if (useWorldCoordinates) {
  45236. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45237. }
  45238. return BABYLON.Vector3.Normalize(result);
  45239. };
  45240. PickingInfo.prototype.getTextureCoordinates = function () {
  45241. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45242. return null;
  45243. }
  45244. var indices = this.pickedMesh.getIndices();
  45245. if (!indices) {
  45246. return null;
  45247. }
  45248. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45249. if (!uvs) {
  45250. return null;
  45251. }
  45252. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45253. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45254. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45255. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45256. uv1 = uv1.scale(this.bu);
  45257. uv2 = uv2.scale(this.bv);
  45258. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45259. };
  45260. return PickingInfo;
  45261. }());
  45262. BABYLON.PickingInfo = PickingInfo;
  45263. })(BABYLON || (BABYLON = {}));
  45264. //# sourceMappingURL=babylon.pickingInfo.js.map
  45265. var BABYLON;
  45266. (function (BABYLON) {
  45267. var Ray = /** @class */ (function () {
  45268. function Ray(origin, direction, length) {
  45269. if (length === void 0) { length = Number.MAX_VALUE; }
  45270. this.origin = origin;
  45271. this.direction = direction;
  45272. this.length = length;
  45273. }
  45274. // Methods
  45275. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45276. var d = 0.0;
  45277. var maxValue = Number.MAX_VALUE;
  45278. var inv;
  45279. var min;
  45280. var max;
  45281. var temp;
  45282. if (Math.abs(this.direction.x) < 0.0000001) {
  45283. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45284. return false;
  45285. }
  45286. }
  45287. else {
  45288. inv = 1.0 / this.direction.x;
  45289. min = (minimum.x - this.origin.x) * inv;
  45290. max = (maximum.x - this.origin.x) * inv;
  45291. if (max === -Infinity) {
  45292. max = Infinity;
  45293. }
  45294. if (min > max) {
  45295. temp = min;
  45296. min = max;
  45297. max = temp;
  45298. }
  45299. d = Math.max(min, d);
  45300. maxValue = Math.min(max, maxValue);
  45301. if (d > maxValue) {
  45302. return false;
  45303. }
  45304. }
  45305. if (Math.abs(this.direction.y) < 0.0000001) {
  45306. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45307. return false;
  45308. }
  45309. }
  45310. else {
  45311. inv = 1.0 / this.direction.y;
  45312. min = (minimum.y - this.origin.y) * inv;
  45313. max = (maximum.y - this.origin.y) * inv;
  45314. if (max === -Infinity) {
  45315. max = Infinity;
  45316. }
  45317. if (min > max) {
  45318. temp = min;
  45319. min = max;
  45320. max = temp;
  45321. }
  45322. d = Math.max(min, d);
  45323. maxValue = Math.min(max, maxValue);
  45324. if (d > maxValue) {
  45325. return false;
  45326. }
  45327. }
  45328. if (Math.abs(this.direction.z) < 0.0000001) {
  45329. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45330. return false;
  45331. }
  45332. }
  45333. else {
  45334. inv = 1.0 / this.direction.z;
  45335. min = (minimum.z - this.origin.z) * inv;
  45336. max = (maximum.z - this.origin.z) * inv;
  45337. if (max === -Infinity) {
  45338. max = Infinity;
  45339. }
  45340. if (min > max) {
  45341. temp = min;
  45342. min = max;
  45343. max = temp;
  45344. }
  45345. d = Math.max(min, d);
  45346. maxValue = Math.min(max, maxValue);
  45347. if (d > maxValue) {
  45348. return false;
  45349. }
  45350. }
  45351. return true;
  45352. };
  45353. Ray.prototype.intersectsBox = function (box) {
  45354. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45355. };
  45356. Ray.prototype.intersectsSphere = function (sphere) {
  45357. var x = sphere.center.x - this.origin.x;
  45358. var y = sphere.center.y - this.origin.y;
  45359. var z = sphere.center.z - this.origin.z;
  45360. var pyth = (x * x) + (y * y) + (z * z);
  45361. var rr = sphere.radius * sphere.radius;
  45362. if (pyth <= rr) {
  45363. return true;
  45364. }
  45365. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45366. if (dot < 0.0) {
  45367. return false;
  45368. }
  45369. var temp = pyth - (dot * dot);
  45370. return temp <= rr;
  45371. };
  45372. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45373. if (!this._edge1) {
  45374. this._edge1 = BABYLON.Vector3.Zero();
  45375. this._edge2 = BABYLON.Vector3.Zero();
  45376. this._pvec = BABYLON.Vector3.Zero();
  45377. this._tvec = BABYLON.Vector3.Zero();
  45378. this._qvec = BABYLON.Vector3.Zero();
  45379. }
  45380. vertex1.subtractToRef(vertex0, this._edge1);
  45381. vertex2.subtractToRef(vertex0, this._edge2);
  45382. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45383. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45384. if (det === 0) {
  45385. return null;
  45386. }
  45387. var invdet = 1 / det;
  45388. this.origin.subtractToRef(vertex0, this._tvec);
  45389. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45390. if (bu < 0 || bu > 1.0) {
  45391. return null;
  45392. }
  45393. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45394. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45395. if (bv < 0 || bu + bv > 1.0) {
  45396. return null;
  45397. }
  45398. //check if the distance is longer than the predefined length.
  45399. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45400. if (distance > this.length) {
  45401. return null;
  45402. }
  45403. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45404. };
  45405. Ray.prototype.intersectsPlane = function (plane) {
  45406. var distance;
  45407. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45408. if (Math.abs(result1) < 9.99999997475243E-07) {
  45409. return null;
  45410. }
  45411. else {
  45412. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45413. distance = (-plane.d - result2) / result1;
  45414. if (distance < 0.0) {
  45415. if (distance < -9.99999997475243E-07) {
  45416. return null;
  45417. }
  45418. else {
  45419. return 0;
  45420. }
  45421. }
  45422. return distance;
  45423. }
  45424. };
  45425. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45426. var tm = BABYLON.Tmp.Matrix[0];
  45427. mesh.getWorldMatrix().invertToRef(tm);
  45428. if (this._tmpRay) {
  45429. Ray.TransformToRef(this, tm, this._tmpRay);
  45430. }
  45431. else {
  45432. this._tmpRay = Ray.Transform(this, tm);
  45433. }
  45434. return mesh.intersects(this._tmpRay, fastCheck);
  45435. };
  45436. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45437. if (results) {
  45438. results.length = 0;
  45439. }
  45440. else {
  45441. results = [];
  45442. }
  45443. for (var i = 0; i < meshes.length; i++) {
  45444. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45445. if (pickInfo.hit) {
  45446. results.push(pickInfo);
  45447. }
  45448. }
  45449. results.sort(this._comparePickingInfo);
  45450. return results;
  45451. };
  45452. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45453. if (pickingInfoA.distance < pickingInfoB.distance) {
  45454. return -1;
  45455. }
  45456. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45457. return 1;
  45458. }
  45459. else {
  45460. return 0;
  45461. }
  45462. };
  45463. /**
  45464. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45465. * @param sega the first point of the segment to test the intersection against
  45466. * @param segb the second point of the segment to test the intersection against
  45467. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45468. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45469. */
  45470. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45471. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45472. var u = segb.subtract(sega);
  45473. var v = rsegb.subtract(this.origin);
  45474. var w = sega.subtract(this.origin);
  45475. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45476. var b = BABYLON.Vector3.Dot(u, v);
  45477. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45478. var d = BABYLON.Vector3.Dot(u, w);
  45479. var e = BABYLON.Vector3.Dot(v, w);
  45480. var D = a * c - b * b; // always >= 0
  45481. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45482. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45483. // compute the line parameters of the two closest points
  45484. if (D < Ray.smallnum) {
  45485. sN = 0.0; // force using point P0 on segment S1
  45486. sD = 1.0; // to prevent possible division by 0.0 later
  45487. tN = e;
  45488. tD = c;
  45489. }
  45490. else {
  45491. sN = (b * e - c * d);
  45492. tN = (a * e - b * d);
  45493. if (sN < 0.0) {
  45494. sN = 0.0;
  45495. tN = e;
  45496. tD = c;
  45497. }
  45498. else if (sN > sD) {
  45499. sN = sD;
  45500. tN = e + b;
  45501. tD = c;
  45502. }
  45503. }
  45504. if (tN < 0.0) {
  45505. tN = 0.0;
  45506. // recompute sc for this edge
  45507. if (-d < 0.0) {
  45508. sN = 0.0;
  45509. }
  45510. else if (-d > a)
  45511. sN = sD;
  45512. else {
  45513. sN = -d;
  45514. sD = a;
  45515. }
  45516. }
  45517. else if (tN > tD) {
  45518. tN = tD;
  45519. // recompute sc for this edge
  45520. if ((-d + b) < 0.0) {
  45521. sN = 0;
  45522. }
  45523. else if ((-d + b) > a) {
  45524. sN = sD;
  45525. }
  45526. else {
  45527. sN = (-d + b);
  45528. sD = a;
  45529. }
  45530. }
  45531. // finally do the division to get sc and tc
  45532. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45533. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45534. // get the difference of the two closest points
  45535. var qtc = v.multiplyByFloats(tc, tc, tc);
  45536. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45537. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45538. if (isIntersected) {
  45539. return qtc.length();
  45540. }
  45541. return -1;
  45542. };
  45543. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45544. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45545. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45546. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45547. this.direction.normalize();
  45548. return this;
  45549. };
  45550. // Statics
  45551. Ray.Zero = function () {
  45552. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45553. };
  45554. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45555. var result = Ray.Zero();
  45556. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45557. };
  45558. /**
  45559. * 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
  45560. * transformed to the given world matrix.
  45561. * @param origin The origin point
  45562. * @param end The end point
  45563. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45564. */
  45565. Ray.CreateNewFromTo = function (origin, end, world) {
  45566. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45567. var direction = end.subtract(origin);
  45568. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45569. direction.normalize();
  45570. return Ray.Transform(new Ray(origin, direction, length), world);
  45571. };
  45572. Ray.Transform = function (ray, matrix) {
  45573. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45574. Ray.TransformToRef(ray, matrix, result);
  45575. return result;
  45576. };
  45577. Ray.TransformToRef = function (ray, matrix, result) {
  45578. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45579. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45580. result.length = ray.length;
  45581. var dir = result.direction;
  45582. var len = dir.length();
  45583. if (!(len === 0 || len === 1)) {
  45584. var num = 1.0 / len;
  45585. dir.x *= num;
  45586. dir.y *= num;
  45587. dir.z *= num;
  45588. result.length *= len;
  45589. }
  45590. };
  45591. Ray.smallnum = 0.00000001;
  45592. Ray.rayl = 10e8;
  45593. return Ray;
  45594. }());
  45595. BABYLON.Ray = Ray;
  45596. })(BABYLON || (BABYLON = {}));
  45597. //# sourceMappingURL=babylon.ray.js.map
  45598. var BABYLON;
  45599. (function (BABYLON) {
  45600. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45601. if (boxMin.x > sphereCenter.x + sphereRadius)
  45602. return false;
  45603. if (sphereCenter.x - sphereRadius > boxMax.x)
  45604. return false;
  45605. if (boxMin.y > sphereCenter.y + sphereRadius)
  45606. return false;
  45607. if (sphereCenter.y - sphereRadius > boxMax.y)
  45608. return false;
  45609. if (boxMin.z > sphereCenter.z + sphereRadius)
  45610. return false;
  45611. if (sphereCenter.z - sphereRadius > boxMax.z)
  45612. return false;
  45613. return true;
  45614. };
  45615. var getLowestRoot = (function () {
  45616. var result = { root: 0, found: false };
  45617. return function (a, b, c, maxR) {
  45618. result.root = 0;
  45619. result.found = false;
  45620. var determinant = b * b - 4.0 * a * c;
  45621. if (determinant < 0)
  45622. return result;
  45623. var sqrtD = Math.sqrt(determinant);
  45624. var r1 = (-b - sqrtD) / (2.0 * a);
  45625. var r2 = (-b + sqrtD) / (2.0 * a);
  45626. if (r1 > r2) {
  45627. var temp = r2;
  45628. r2 = r1;
  45629. r1 = temp;
  45630. }
  45631. if (r1 > 0 && r1 < maxR) {
  45632. result.root = r1;
  45633. result.found = true;
  45634. return result;
  45635. }
  45636. if (r2 > 0 && r2 < maxR) {
  45637. result.root = r2;
  45638. result.found = true;
  45639. return result;
  45640. }
  45641. return result;
  45642. };
  45643. })();
  45644. var Collider = /** @class */ (function () {
  45645. function Collider() {
  45646. this._collisionPoint = BABYLON.Vector3.Zero();
  45647. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45648. this._tempVector = BABYLON.Vector3.Zero();
  45649. this._tempVector2 = BABYLON.Vector3.Zero();
  45650. this._tempVector3 = BABYLON.Vector3.Zero();
  45651. this._tempVector4 = BABYLON.Vector3.Zero();
  45652. this._edge = BABYLON.Vector3.Zero();
  45653. this._baseToVertex = BABYLON.Vector3.Zero();
  45654. this._destinationPoint = BABYLON.Vector3.Zero();
  45655. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45656. this._displacementVector = BABYLON.Vector3.Zero();
  45657. this._radius = BABYLON.Vector3.One();
  45658. this._retry = 0;
  45659. this._basePointWorld = BABYLON.Vector3.Zero();
  45660. this._velocityWorld = BABYLON.Vector3.Zero();
  45661. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45662. this._collisionMask = -1;
  45663. }
  45664. Object.defineProperty(Collider.prototype, "collisionMask", {
  45665. get: function () {
  45666. return this._collisionMask;
  45667. },
  45668. set: function (mask) {
  45669. this._collisionMask = !isNaN(mask) ? mask : -1;
  45670. },
  45671. enumerable: true,
  45672. configurable: true
  45673. });
  45674. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45675. /**
  45676. * Gets the plane normal used to compute the sliding response (in local space)
  45677. */
  45678. get: function () {
  45679. return this._slidePlaneNormal;
  45680. },
  45681. enumerable: true,
  45682. configurable: true
  45683. });
  45684. // Methods
  45685. Collider.prototype._initialize = function (source, dir, e) {
  45686. this._velocity = dir;
  45687. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45688. this._basePoint = source;
  45689. source.multiplyToRef(this._radius, this._basePointWorld);
  45690. dir.multiplyToRef(this._radius, this._velocityWorld);
  45691. this._velocityWorldLength = this._velocityWorld.length();
  45692. this._epsilon = e;
  45693. this.collisionFound = false;
  45694. };
  45695. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45696. pa.subtractToRef(point, this._tempVector);
  45697. pb.subtractToRef(point, this._tempVector2);
  45698. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45699. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45700. if (d < 0)
  45701. return false;
  45702. pc.subtractToRef(point, this._tempVector3);
  45703. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45704. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45705. if (d < 0)
  45706. return false;
  45707. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45708. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45709. return d >= 0;
  45710. };
  45711. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45712. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45713. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45714. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45715. return false;
  45716. }
  45717. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45718. return false;
  45719. return true;
  45720. };
  45721. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45722. var t0;
  45723. var embeddedInPlane = false;
  45724. //defensive programming, actually not needed.
  45725. if (!trianglePlaneArray) {
  45726. trianglePlaneArray = [];
  45727. }
  45728. if (!trianglePlaneArray[faceIndex]) {
  45729. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45730. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45731. }
  45732. var trianglePlane = trianglePlaneArray[faceIndex];
  45733. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45734. return;
  45735. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45736. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45737. if (normalDotVelocity == 0) {
  45738. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45739. return;
  45740. embeddedInPlane = true;
  45741. t0 = 0;
  45742. }
  45743. else {
  45744. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45745. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45746. if (t0 > t1) {
  45747. var temp = t1;
  45748. t1 = t0;
  45749. t0 = temp;
  45750. }
  45751. if (t0 > 1.0 || t1 < 0.0)
  45752. return;
  45753. if (t0 < 0)
  45754. t0 = 0;
  45755. if (t0 > 1.0)
  45756. t0 = 1.0;
  45757. }
  45758. this._collisionPoint.copyFromFloats(0, 0, 0);
  45759. var found = false;
  45760. var t = 1.0;
  45761. if (!embeddedInPlane) {
  45762. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45763. this._velocity.scaleToRef(t0, this._tempVector);
  45764. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45765. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45766. found = true;
  45767. t = t0;
  45768. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45769. }
  45770. }
  45771. if (!found) {
  45772. var velocitySquaredLength = this._velocity.lengthSquared();
  45773. var a = velocitySquaredLength;
  45774. this._basePoint.subtractToRef(p1, this._tempVector);
  45775. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45776. var c = this._tempVector.lengthSquared() - 1.0;
  45777. var lowestRoot = getLowestRoot(a, b, c, t);
  45778. if (lowestRoot.found) {
  45779. t = lowestRoot.root;
  45780. found = true;
  45781. this._collisionPoint.copyFrom(p1);
  45782. }
  45783. this._basePoint.subtractToRef(p2, this._tempVector);
  45784. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45785. c = this._tempVector.lengthSquared() - 1.0;
  45786. lowestRoot = getLowestRoot(a, b, c, t);
  45787. if (lowestRoot.found) {
  45788. t = lowestRoot.root;
  45789. found = true;
  45790. this._collisionPoint.copyFrom(p2);
  45791. }
  45792. this._basePoint.subtractToRef(p3, this._tempVector);
  45793. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45794. c = this._tempVector.lengthSquared() - 1.0;
  45795. lowestRoot = getLowestRoot(a, b, c, t);
  45796. if (lowestRoot.found) {
  45797. t = lowestRoot.root;
  45798. found = true;
  45799. this._collisionPoint.copyFrom(p3);
  45800. }
  45801. p2.subtractToRef(p1, this._edge);
  45802. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45803. var edgeSquaredLength = this._edge.lengthSquared();
  45804. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45805. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45806. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45807. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45808. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45809. lowestRoot = getLowestRoot(a, b, c, t);
  45810. if (lowestRoot.found) {
  45811. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45812. if (f >= 0.0 && f <= 1.0) {
  45813. t = lowestRoot.root;
  45814. found = true;
  45815. this._edge.scaleInPlace(f);
  45816. p1.addToRef(this._edge, this._collisionPoint);
  45817. }
  45818. }
  45819. p3.subtractToRef(p2, this._edge);
  45820. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45821. edgeSquaredLength = this._edge.lengthSquared();
  45822. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45823. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45824. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45825. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45826. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45827. lowestRoot = getLowestRoot(a, b, c, t);
  45828. if (lowestRoot.found) {
  45829. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45830. if (f >= 0.0 && f <= 1.0) {
  45831. t = lowestRoot.root;
  45832. found = true;
  45833. this._edge.scaleInPlace(f);
  45834. p2.addToRef(this._edge, this._collisionPoint);
  45835. }
  45836. }
  45837. p1.subtractToRef(p3, this._edge);
  45838. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45839. edgeSquaredLength = this._edge.lengthSquared();
  45840. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45841. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45842. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45843. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45844. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45845. lowestRoot = getLowestRoot(a, b, c, t);
  45846. if (lowestRoot.found) {
  45847. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45848. if (f >= 0.0 && f <= 1.0) {
  45849. t = lowestRoot.root;
  45850. found = true;
  45851. this._edge.scaleInPlace(f);
  45852. p3.addToRef(this._edge, this._collisionPoint);
  45853. }
  45854. }
  45855. }
  45856. if (found) {
  45857. var distToCollision = t * this._velocity.length();
  45858. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45859. if (!this.intersectionPoint) {
  45860. this.intersectionPoint = this._collisionPoint.clone();
  45861. }
  45862. else {
  45863. this.intersectionPoint.copyFrom(this._collisionPoint);
  45864. }
  45865. this._nearestDistance = distToCollision;
  45866. this.collisionFound = true;
  45867. }
  45868. }
  45869. };
  45870. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45871. for (var i = indexStart; i < indexEnd; i += 3) {
  45872. var p1 = pts[indices[i] - decal];
  45873. var p2 = pts[indices[i + 1] - decal];
  45874. var p3 = pts[indices[i + 2] - decal];
  45875. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45876. }
  45877. };
  45878. Collider.prototype._getResponse = function (pos, vel) {
  45879. pos.addToRef(vel, this._destinationPoint);
  45880. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45881. this._basePoint.addToRef(vel, pos);
  45882. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45883. this._slidePlaneNormal.normalize();
  45884. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45885. pos.addInPlace(this._displacementVector);
  45886. this.intersectionPoint.addInPlace(this._displacementVector);
  45887. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45888. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45889. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45890. };
  45891. return Collider;
  45892. }());
  45893. BABYLON.Collider = Collider;
  45894. })(BABYLON || (BABYLON = {}));
  45895. //# sourceMappingURL=babylon.collider.js.map
  45896. var BABYLON;
  45897. (function (BABYLON) {
  45898. //WebWorker code will be inserted to this variable.
  45899. BABYLON.CollisionWorker = "";
  45900. var WorkerTaskType;
  45901. (function (WorkerTaskType) {
  45902. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45903. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45904. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45905. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45906. var WorkerReplyType;
  45907. (function (WorkerReplyType) {
  45908. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45909. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45910. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45911. var CollisionCoordinatorWorker = /** @class */ (function () {
  45912. function CollisionCoordinatorWorker() {
  45913. var _this = this;
  45914. this._scaledPosition = BABYLON.Vector3.Zero();
  45915. this._scaledVelocity = BABYLON.Vector3.Zero();
  45916. this.onMeshUpdated = function (transformNode) {
  45917. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45918. };
  45919. this.onGeometryUpdated = function (geometry) {
  45920. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45921. };
  45922. this._afterRender = function () {
  45923. if (!_this._init)
  45924. return;
  45925. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45926. return;
  45927. }
  45928. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45929. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45930. if (_this._runningUpdated > 4) {
  45931. return;
  45932. }
  45933. ++_this._runningUpdated;
  45934. var payload = {
  45935. updatedMeshes: _this._addUpdateMeshesList,
  45936. updatedGeometries: _this._addUpdateGeometriesList,
  45937. removedGeometries: _this._toRemoveGeometryArray,
  45938. removedMeshes: _this._toRemoveMeshesArray
  45939. };
  45940. var message = {
  45941. payload: payload,
  45942. taskType: WorkerTaskType.UPDATE
  45943. };
  45944. var serializable = [];
  45945. for (var id in payload.updatedGeometries) {
  45946. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45947. //prepare transferables
  45948. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45949. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45950. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45951. }
  45952. }
  45953. _this._worker.postMessage(message, serializable);
  45954. _this._addUpdateMeshesList = {};
  45955. _this._addUpdateGeometriesList = {};
  45956. _this._toRemoveGeometryArray = [];
  45957. _this._toRemoveMeshesArray = [];
  45958. };
  45959. this._onMessageFromWorker = function (e) {
  45960. var returnData = e.data;
  45961. if (returnData.error != WorkerReplyType.SUCCESS) {
  45962. //TODO what errors can be returned from the worker?
  45963. BABYLON.Tools.Warn("error returned from worker!");
  45964. return;
  45965. }
  45966. switch (returnData.taskType) {
  45967. case WorkerTaskType.INIT:
  45968. _this._init = true;
  45969. //Update the worked with ALL of the scene's current state
  45970. _this._scene.meshes.forEach(function (mesh) {
  45971. _this.onMeshAdded(mesh);
  45972. });
  45973. _this._scene.getGeometries().forEach(function (geometry) {
  45974. _this.onGeometryAdded(geometry);
  45975. });
  45976. break;
  45977. case WorkerTaskType.UPDATE:
  45978. _this._runningUpdated--;
  45979. break;
  45980. case WorkerTaskType.COLLIDE:
  45981. var returnPayload = returnData.payload;
  45982. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45983. return;
  45984. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45985. if (callback) {
  45986. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45987. if (mesh) {
  45988. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45989. }
  45990. }
  45991. //cleanup
  45992. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45993. break;
  45994. }
  45995. };
  45996. this._collisionsCallbackArray = [];
  45997. this._init = false;
  45998. this._runningUpdated = 0;
  45999. this._addUpdateMeshesList = {};
  46000. this._addUpdateGeometriesList = {};
  46001. this._toRemoveGeometryArray = [];
  46002. this._toRemoveMeshesArray = [];
  46003. }
  46004. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46005. if (!this._init)
  46006. return;
  46007. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  46008. return;
  46009. position.divideToRef(collider._radius, this._scaledPosition);
  46010. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46011. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  46012. var payload = {
  46013. collider: {
  46014. position: this._scaledPosition.asArray(),
  46015. velocity: this._scaledVelocity.asArray(),
  46016. radius: collider._radius.asArray()
  46017. },
  46018. collisionId: collisionIndex,
  46019. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  46020. maximumRetry: maximumRetry
  46021. };
  46022. var message = {
  46023. payload: payload,
  46024. taskType: WorkerTaskType.COLLIDE
  46025. };
  46026. this._worker.postMessage(message);
  46027. };
  46028. CollisionCoordinatorWorker.prototype.init = function (scene) {
  46029. this._scene = scene;
  46030. this._scene.registerAfterRender(this._afterRender);
  46031. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  46032. this._worker = new Worker(workerUrl);
  46033. this._worker.onmessage = this._onMessageFromWorker;
  46034. var message = {
  46035. payload: {},
  46036. taskType: WorkerTaskType.INIT
  46037. };
  46038. this._worker.postMessage(message);
  46039. };
  46040. CollisionCoordinatorWorker.prototype.destroy = function () {
  46041. this._scene.unregisterAfterRender(this._afterRender);
  46042. this._worker.terminate();
  46043. };
  46044. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  46045. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  46046. this.onMeshUpdated(mesh);
  46047. };
  46048. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  46049. this._toRemoveMeshesArray.push(mesh.uniqueId);
  46050. };
  46051. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  46052. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  46053. geometry.onGeometryUpdated = this.onGeometryUpdated;
  46054. this.onGeometryUpdated(geometry);
  46055. };
  46056. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  46057. this._toRemoveGeometryArray.push(geometry.id);
  46058. };
  46059. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  46060. var submeshes = [];
  46061. if (mesh.subMeshes) {
  46062. submeshes = mesh.subMeshes.map(function (sm, idx) {
  46063. var boundingInfo = sm.getBoundingInfo();
  46064. return {
  46065. position: idx,
  46066. verticesStart: sm.verticesStart,
  46067. verticesCount: sm.verticesCount,
  46068. indexStart: sm.indexStart,
  46069. indexCount: sm.indexCount,
  46070. hasMaterial: !!sm.getMaterial(),
  46071. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46072. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46073. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46074. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  46075. };
  46076. });
  46077. }
  46078. var geometryId = null;
  46079. if (mesh instanceof BABYLON.Mesh) {
  46080. var geometry = mesh.geometry;
  46081. geometryId = geometry ? geometry.id : null;
  46082. }
  46083. else if (mesh instanceof BABYLON.InstancedMesh) {
  46084. var geometry = mesh.sourceMesh.geometry;
  46085. geometryId = geometry ? geometry.id : null;
  46086. }
  46087. var boundingInfo = mesh.getBoundingInfo();
  46088. return {
  46089. uniqueId: mesh.uniqueId,
  46090. id: mesh.id,
  46091. name: mesh.name,
  46092. geometryId: geometryId,
  46093. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46094. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46095. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46096. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  46097. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  46098. subMeshes: submeshes,
  46099. checkCollisions: mesh.checkCollisions
  46100. };
  46101. };
  46102. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  46103. return {
  46104. id: geometry.id,
  46105. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  46106. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  46107. indices: new Uint32Array(geometry.getIndices() || []),
  46108. };
  46109. };
  46110. return CollisionCoordinatorWorker;
  46111. }());
  46112. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  46113. var CollisionCoordinatorLegacy = /** @class */ (function () {
  46114. function CollisionCoordinatorLegacy() {
  46115. this._scaledPosition = BABYLON.Vector3.Zero();
  46116. this._scaledVelocity = BABYLON.Vector3.Zero();
  46117. this._finalPosition = BABYLON.Vector3.Zero();
  46118. }
  46119. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46120. position.divideToRef(collider._radius, this._scaledPosition);
  46121. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46122. collider.collidedMesh = null;
  46123. collider._retry = 0;
  46124. collider._initialVelocity = this._scaledVelocity;
  46125. collider._initialPosition = this._scaledPosition;
  46126. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46127. this._finalPosition.multiplyInPlace(collider._radius);
  46128. //run the callback
  46129. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46130. };
  46131. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46132. this._scene = scene;
  46133. };
  46134. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46135. //Legacy need no destruction method.
  46136. };
  46137. //No update in legacy mode
  46138. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46139. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46140. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46141. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46142. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46143. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46144. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46145. if (excludedMesh === void 0) { excludedMesh = null; }
  46146. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46147. if (collider._retry >= maximumRetry) {
  46148. finalPosition.copyFrom(position);
  46149. return;
  46150. }
  46151. // Check if this is a mesh else camera or -1
  46152. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46153. collider._initialize(position, velocity, closeDistance);
  46154. // Check all meshes
  46155. for (var index = 0; index < this._scene.meshes.length; index++) {
  46156. var mesh = this._scene.meshes[index];
  46157. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46158. mesh._checkCollision(collider);
  46159. }
  46160. }
  46161. if (!collider.collisionFound) {
  46162. position.addToRef(velocity, finalPosition);
  46163. return;
  46164. }
  46165. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46166. collider._getResponse(position, velocity);
  46167. }
  46168. if (velocity.length() <= closeDistance) {
  46169. finalPosition.copyFrom(position);
  46170. return;
  46171. }
  46172. collider._retry++;
  46173. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46174. };
  46175. return CollisionCoordinatorLegacy;
  46176. }());
  46177. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46178. })(BABYLON || (BABYLON = {}));
  46179. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46180. var BABYLON;
  46181. (function (BABYLON) {
  46182. var Particle = /** @class */ (function () {
  46183. function Particle(particleSystem) {
  46184. this.particleSystem = particleSystem;
  46185. this.position = BABYLON.Vector3.Zero();
  46186. this.direction = BABYLON.Vector3.Zero();
  46187. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46188. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46189. this.lifeTime = 1.0;
  46190. this.age = 0;
  46191. this.size = 0;
  46192. this.angle = 0;
  46193. this.angularSpeed = 0;
  46194. this._currentFrameCounter = 0;
  46195. this.cellIndex = 0;
  46196. if (!this.particleSystem.isAnimationSheetEnabled) {
  46197. return;
  46198. }
  46199. this.cellIndex = this.particleSystem.startSpriteCellID;
  46200. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46201. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46202. }
  46203. else {
  46204. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46205. }
  46206. }
  46207. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46208. // (ageOffset / scaledUpdateSpeed) / available cells
  46209. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46210. this._currentFrameCounter += scaledUpdateSpeed;
  46211. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46212. this._currentFrameCounter = 0;
  46213. this.cellIndex++;
  46214. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46215. this.cellIndex = this.particleSystem.endSpriteCellID;
  46216. }
  46217. }
  46218. };
  46219. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46220. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46221. this.cellIndex++;
  46222. this._currentFrameCounter = 0;
  46223. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46224. if (this.particleSystem.spriteCellLoop) {
  46225. this.cellIndex = this.particleSystem.startSpriteCellID;
  46226. }
  46227. else {
  46228. this.cellIndex = this.particleSystem.endSpriteCellID;
  46229. }
  46230. }
  46231. }
  46232. else {
  46233. this._currentFrameCounter++;
  46234. }
  46235. };
  46236. Particle.prototype.copyTo = function (other) {
  46237. other.position.copyFrom(this.position);
  46238. other.direction.copyFrom(this.direction);
  46239. other.color.copyFrom(this.color);
  46240. other.colorStep.copyFrom(this.colorStep);
  46241. other.lifeTime = this.lifeTime;
  46242. other.age = this.age;
  46243. other.size = this.size;
  46244. other.angle = this.angle;
  46245. other.angularSpeed = this.angularSpeed;
  46246. other.particleSystem = this.particleSystem;
  46247. other.cellIndex = this.cellIndex;
  46248. };
  46249. return Particle;
  46250. }());
  46251. BABYLON.Particle = Particle;
  46252. })(BABYLON || (BABYLON = {}));
  46253. //# sourceMappingURL=babylon.particle.js.map
  46254. var BABYLON;
  46255. (function (BABYLON) {
  46256. var ParticleSystem = /** @class */ (function () {
  46257. // end of sheet animation
  46258. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46259. if (customEffect === void 0) { customEffect = null; }
  46260. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46261. if (epsilon === void 0) { epsilon = 0.01; }
  46262. var _this = this;
  46263. this.name = name;
  46264. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46265. // Members
  46266. this.animations = [];
  46267. this.renderingGroupId = 0;
  46268. this.emitter = null;
  46269. this.emitRate = 10;
  46270. this.manualEmitCount = -1;
  46271. this.updateSpeed = 0.01;
  46272. this.targetStopDuration = 0;
  46273. this.disposeOnStop = false;
  46274. this.minEmitPower = 1;
  46275. this.maxEmitPower = 1;
  46276. this.minLifeTime = 1;
  46277. this.maxLifeTime = 1;
  46278. this.minSize = 1;
  46279. this.maxSize = 1;
  46280. this.minAngularSpeed = 0;
  46281. this.maxAngularSpeed = 0;
  46282. this.layerMask = 0x0FFFFFFF;
  46283. this.customShader = null;
  46284. this.preventAutoStart = false;
  46285. /**
  46286. * An event triggered when the system is disposed.
  46287. * @type {BABYLON.Observable}
  46288. */
  46289. this.onDisposeObservable = new BABYLON.Observable();
  46290. this.onAnimationEnd = null;
  46291. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46292. this.forceDepthWrite = false;
  46293. this.gravity = BABYLON.Vector3.Zero();
  46294. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46295. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46296. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46297. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46298. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46299. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46300. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46301. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46302. this.particles = new Array();
  46303. this._stockParticles = new Array();
  46304. this._newPartsExcess = 0;
  46305. this._vertexBuffers = {};
  46306. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46307. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46308. this._scaledDirection = BABYLON.Vector3.Zero();
  46309. this._scaledGravity = BABYLON.Vector3.Zero();
  46310. this._currentRenderId = -1;
  46311. this._started = false;
  46312. this._stopped = false;
  46313. this._actualFrame = 0;
  46314. // sheet animation
  46315. this.startSpriteCellID = 0;
  46316. this.endSpriteCellID = 0;
  46317. this.spriteCellLoop = true;
  46318. this.spriteCellChangeSpeed = 0;
  46319. this.spriteCellWidth = 0;
  46320. this.spriteCellHeight = 0;
  46321. this._vertexBufferSize = 11;
  46322. this.appendParticleVertexes = null;
  46323. this.id = name;
  46324. this._capacity = capacity;
  46325. this._epsilon = epsilon;
  46326. if (_isAnimationSheetEnabled) {
  46327. this._vertexBufferSize = 12;
  46328. }
  46329. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46330. this._customEffect = customEffect;
  46331. scene.particleSystems.push(this);
  46332. this._createIndexBuffer();
  46333. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46334. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46335. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46336. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46337. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46338. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46339. if (this._isAnimationSheetEnabled) {
  46340. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46341. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46342. }
  46343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46344. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46345. this._vertexBuffers["options"] = options;
  46346. // Default behaviors
  46347. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46348. this.updateFunction = function (particles) {
  46349. for (var index = 0; index < particles.length; index++) {
  46350. var particle = particles[index];
  46351. particle.age += _this._scaledUpdateSpeed;
  46352. if (particle.age >= particle.lifeTime) {
  46353. _this.recycleParticle(particle);
  46354. index--;
  46355. continue;
  46356. }
  46357. else {
  46358. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46359. particle.color.addInPlace(_this._scaledColorStep);
  46360. if (particle.color.a < 0)
  46361. particle.color.a = 0;
  46362. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46363. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46364. particle.position.addInPlace(_this._scaledDirection);
  46365. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46366. particle.direction.addInPlace(_this._scaledGravity);
  46367. if (_this._isAnimationSheetEnabled) {
  46368. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46369. }
  46370. }
  46371. }
  46372. };
  46373. }
  46374. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46375. set: function (callback) {
  46376. if (this._onDisposeObserver) {
  46377. this.onDisposeObservable.remove(this._onDisposeObserver);
  46378. }
  46379. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46380. },
  46381. enumerable: true,
  46382. configurable: true
  46383. });
  46384. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46385. get: function () {
  46386. return this._isAnimationSheetEnabled;
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. ParticleSystem.prototype._createIndexBuffer = function () {
  46392. var indices = [];
  46393. var index = 0;
  46394. for (var count = 0; count < this._capacity; count++) {
  46395. indices.push(index);
  46396. indices.push(index + 1);
  46397. indices.push(index + 2);
  46398. indices.push(index);
  46399. indices.push(index + 2);
  46400. indices.push(index + 3);
  46401. index += 4;
  46402. }
  46403. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46404. };
  46405. ParticleSystem.prototype.recycleParticle = function (particle) {
  46406. var lastParticle = this.particles.pop();
  46407. if (lastParticle !== particle) {
  46408. lastParticle.copyTo(particle);
  46409. this._stockParticles.push(lastParticle);
  46410. }
  46411. };
  46412. ParticleSystem.prototype.getCapacity = function () {
  46413. return this._capacity;
  46414. };
  46415. ParticleSystem.prototype.isAlive = function () {
  46416. return this._alive;
  46417. };
  46418. ParticleSystem.prototype.isStarted = function () {
  46419. return this._started;
  46420. };
  46421. ParticleSystem.prototype.start = function () {
  46422. this._started = true;
  46423. this._stopped = false;
  46424. this._actualFrame = 0;
  46425. };
  46426. ParticleSystem.prototype.stop = function () {
  46427. this._stopped = true;
  46428. };
  46429. // animation sheet
  46430. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46431. var offset = index * this._vertexBufferSize;
  46432. this._vertexData[offset] = particle.position.x;
  46433. this._vertexData[offset + 1] = particle.position.y;
  46434. this._vertexData[offset + 2] = particle.position.z;
  46435. this._vertexData[offset + 3] = particle.color.r;
  46436. this._vertexData[offset + 4] = particle.color.g;
  46437. this._vertexData[offset + 5] = particle.color.b;
  46438. this._vertexData[offset + 6] = particle.color.a;
  46439. this._vertexData[offset + 7] = particle.angle;
  46440. this._vertexData[offset + 8] = particle.size;
  46441. this._vertexData[offset + 9] = offsetX;
  46442. this._vertexData[offset + 10] = offsetY;
  46443. };
  46444. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46445. if (offsetX === 0)
  46446. offsetX = this._epsilon;
  46447. else if (offsetX === 1)
  46448. offsetX = 1 - this._epsilon;
  46449. if (offsetY === 0)
  46450. offsetY = this._epsilon;
  46451. else if (offsetY === 1)
  46452. offsetY = 1 - this._epsilon;
  46453. var offset = index * this._vertexBufferSize;
  46454. this._vertexData[offset] = particle.position.x;
  46455. this._vertexData[offset + 1] = particle.position.y;
  46456. this._vertexData[offset + 2] = particle.position.z;
  46457. this._vertexData[offset + 3] = particle.color.r;
  46458. this._vertexData[offset + 4] = particle.color.g;
  46459. this._vertexData[offset + 5] = particle.color.b;
  46460. this._vertexData[offset + 6] = particle.color.a;
  46461. this._vertexData[offset + 7] = particle.angle;
  46462. this._vertexData[offset + 8] = particle.size;
  46463. this._vertexData[offset + 9] = offsetX;
  46464. this._vertexData[offset + 10] = offsetY;
  46465. this._vertexData[offset + 11] = particle.cellIndex;
  46466. };
  46467. ParticleSystem.prototype._update = function (newParticles) {
  46468. // Update current
  46469. this._alive = this.particles.length > 0;
  46470. this.updateFunction(this.particles);
  46471. // Add new ones
  46472. var worldMatrix;
  46473. if (this.emitter.position) {
  46474. var emitterMesh = this.emitter;
  46475. worldMatrix = emitterMesh.getWorldMatrix();
  46476. }
  46477. else {
  46478. var emitterPosition = this.emitter;
  46479. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46480. }
  46481. var particle;
  46482. for (var index = 0; index < newParticles; index++) {
  46483. if (this.particles.length === this._capacity) {
  46484. break;
  46485. }
  46486. if (this._stockParticles.length !== 0) {
  46487. particle = this._stockParticles.pop();
  46488. particle.age = 0;
  46489. particle.cellIndex = this.startSpriteCellID;
  46490. }
  46491. else {
  46492. particle = new BABYLON.Particle(this);
  46493. }
  46494. this.particles.push(particle);
  46495. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46496. if (this.startDirectionFunction) {
  46497. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46498. }
  46499. else {
  46500. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46501. }
  46502. if (this.startPositionFunction) {
  46503. this.startPositionFunction(worldMatrix, particle.position, particle);
  46504. }
  46505. else {
  46506. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46507. }
  46508. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46509. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46510. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46511. var step = ParticleSystem.randomNumber(0, 1.0);
  46512. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46513. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46514. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46515. }
  46516. };
  46517. ParticleSystem.prototype._getEffect = function () {
  46518. if (this._customEffect) {
  46519. return this._customEffect;
  46520. }
  46521. ;
  46522. var defines = [];
  46523. if (this._scene.clipPlane) {
  46524. defines.push("#define CLIPPLANE");
  46525. }
  46526. if (this._isAnimationSheetEnabled) {
  46527. defines.push("#define ANIMATESHEET");
  46528. }
  46529. // Effect
  46530. var join = defines.join("\n");
  46531. if (this._cachedDefines !== join) {
  46532. this._cachedDefines = join;
  46533. var attributesNamesOrOptions;
  46534. var effectCreationOption;
  46535. if (this._isAnimationSheetEnabled) {
  46536. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46537. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46538. }
  46539. else {
  46540. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46541. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46542. }
  46543. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46544. }
  46545. return this._effect;
  46546. };
  46547. ParticleSystem.prototype.animate = function () {
  46548. if (!this._started)
  46549. return;
  46550. var effect = this._getEffect();
  46551. // Check
  46552. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46553. return;
  46554. if (this._currentRenderId === this._scene.getRenderId()) {
  46555. return;
  46556. }
  46557. this._currentRenderId = this._scene.getRenderId();
  46558. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46559. // determine the number of particles we need to create
  46560. var newParticles;
  46561. if (this.manualEmitCount > -1) {
  46562. newParticles = this.manualEmitCount;
  46563. this._newPartsExcess = 0;
  46564. this.manualEmitCount = 0;
  46565. }
  46566. else {
  46567. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46568. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46569. }
  46570. if (this._newPartsExcess > 1.0) {
  46571. newParticles += this._newPartsExcess >> 0;
  46572. this._newPartsExcess -= this._newPartsExcess >> 0;
  46573. }
  46574. this._alive = false;
  46575. if (!this._stopped) {
  46576. this._actualFrame += this._scaledUpdateSpeed;
  46577. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46578. this.stop();
  46579. }
  46580. else {
  46581. newParticles = 0;
  46582. }
  46583. this._update(newParticles);
  46584. // Stopped?
  46585. if (this._stopped) {
  46586. if (!this._alive) {
  46587. this._started = false;
  46588. if (this.onAnimationEnd) {
  46589. this.onAnimationEnd();
  46590. }
  46591. if (this.disposeOnStop) {
  46592. this._scene._toBeDisposed.push(this);
  46593. }
  46594. }
  46595. }
  46596. // Animation sheet
  46597. if (this._isAnimationSheetEnabled) {
  46598. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46599. }
  46600. else {
  46601. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46602. }
  46603. // Update VBO
  46604. var offset = 0;
  46605. for (var index = 0; index < this.particles.length; index++) {
  46606. var particle = this.particles[index];
  46607. this.appendParticleVertexes(offset, particle);
  46608. offset += 4;
  46609. }
  46610. if (this._vertexBuffer) {
  46611. this._vertexBuffer.update(this._vertexData);
  46612. }
  46613. };
  46614. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46615. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46616. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46617. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46618. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46619. };
  46620. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46621. this._appendParticleVertex(offset++, particle, 0, 0);
  46622. this._appendParticleVertex(offset++, particle, 1, 0);
  46623. this._appendParticleVertex(offset++, particle, 1, 1);
  46624. this._appendParticleVertex(offset++, particle, 0, 1);
  46625. };
  46626. ParticleSystem.prototype.rebuild = function () {
  46627. this._createIndexBuffer();
  46628. if (this._vertexBuffer) {
  46629. this._vertexBuffer._rebuild();
  46630. }
  46631. };
  46632. ParticleSystem.prototype.render = function () {
  46633. var effect = this._getEffect();
  46634. // Check
  46635. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46636. return 0;
  46637. var engine = this._scene.getEngine();
  46638. // Render
  46639. engine.enableEffect(effect);
  46640. engine.setState(false);
  46641. var viewMatrix = this._scene.getViewMatrix();
  46642. effect.setTexture("diffuseSampler", this.particleTexture);
  46643. effect.setMatrix("view", viewMatrix);
  46644. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46645. if (this._isAnimationSheetEnabled) {
  46646. var baseSize = this.particleTexture.getBaseSize();
  46647. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46648. }
  46649. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46650. if (this._scene.clipPlane) {
  46651. var clipPlane = this._scene.clipPlane;
  46652. var invView = viewMatrix.clone();
  46653. invView.invert();
  46654. effect.setMatrix("invView", invView);
  46655. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46656. }
  46657. // VBOs
  46658. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46659. // Draw order
  46660. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46661. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46662. }
  46663. else {
  46664. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46665. }
  46666. if (this.forceDepthWrite) {
  46667. engine.setDepthWrite(true);
  46668. }
  46669. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46670. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46671. return this.particles.length;
  46672. };
  46673. ParticleSystem.prototype.dispose = function () {
  46674. if (this._vertexBuffer) {
  46675. this._vertexBuffer.dispose();
  46676. this._vertexBuffer = null;
  46677. }
  46678. if (this._indexBuffer) {
  46679. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46680. this._indexBuffer = null;
  46681. }
  46682. if (this.particleTexture) {
  46683. this.particleTexture.dispose();
  46684. this.particleTexture = null;
  46685. }
  46686. // Remove from scene
  46687. var index = this._scene.particleSystems.indexOf(this);
  46688. if (index > -1) {
  46689. this._scene.particleSystems.splice(index, 1);
  46690. }
  46691. // Callback
  46692. this.onDisposeObservable.notifyObservers(this);
  46693. this.onDisposeObservable.clear();
  46694. };
  46695. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46696. if (radius === void 0) { radius = 1; }
  46697. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46698. this.particleEmitterType = particleEmitter;
  46699. return particleEmitter;
  46700. };
  46701. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46702. if (radius === void 0) { radius = 1; }
  46703. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46704. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46705. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46706. this.particleEmitterType = particleEmitter;
  46707. return particleEmitter;
  46708. };
  46709. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46710. if (radius === void 0) { radius = 1; }
  46711. if (angle === void 0) { angle = Math.PI / 4; }
  46712. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46713. this.particleEmitterType = particleEmitter;
  46714. return particleEmitter;
  46715. };
  46716. // 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.
  46717. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46718. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46719. this.direction1 = direction1;
  46720. this.direction2 = direction2;
  46721. this.minEmitBox = minEmitBox;
  46722. this.maxEmitBox = maxEmitBox;
  46723. this.particleEmitterType = particleEmitter;
  46724. return particleEmitter;
  46725. };
  46726. ParticleSystem.randomNumber = function (min, max) {
  46727. if (min === max) {
  46728. return (min);
  46729. }
  46730. var random = Math.random();
  46731. return ((random * (max - min)) + min);
  46732. };
  46733. // Clone
  46734. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46735. var custom = null;
  46736. var program = null;
  46737. if (this.customShader != null) {
  46738. program = this.customShader;
  46739. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46740. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46741. }
  46742. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46743. result.customShader = program;
  46744. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46745. if (newEmitter === undefined) {
  46746. newEmitter = this.emitter;
  46747. }
  46748. result.emitter = newEmitter;
  46749. if (this.particleTexture) {
  46750. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46751. }
  46752. if (!this.preventAutoStart) {
  46753. result.start();
  46754. }
  46755. return result;
  46756. };
  46757. ParticleSystem.prototype.serialize = function () {
  46758. var serializationObject = {};
  46759. serializationObject.name = this.name;
  46760. serializationObject.id = this.id;
  46761. // Emitter
  46762. if (this.emitter.position) {
  46763. var emitterMesh = this.emitter;
  46764. serializationObject.emitterId = emitterMesh.id;
  46765. }
  46766. else {
  46767. var emitterPosition = this.emitter;
  46768. serializationObject.emitter = emitterPosition.asArray();
  46769. }
  46770. serializationObject.capacity = this.getCapacity();
  46771. if (this.particleTexture) {
  46772. serializationObject.textureName = this.particleTexture.name;
  46773. }
  46774. // Animations
  46775. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46776. // Particle system
  46777. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46778. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46779. serializationObject.minSize = this.minSize;
  46780. serializationObject.maxSize = this.maxSize;
  46781. serializationObject.minEmitPower = this.minEmitPower;
  46782. serializationObject.maxEmitPower = this.maxEmitPower;
  46783. serializationObject.minLifeTime = this.minLifeTime;
  46784. serializationObject.maxLifeTime = this.maxLifeTime;
  46785. serializationObject.emitRate = this.emitRate;
  46786. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46787. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46788. serializationObject.gravity = this.gravity.asArray();
  46789. serializationObject.direction1 = this.direction1.asArray();
  46790. serializationObject.direction2 = this.direction2.asArray();
  46791. serializationObject.color1 = this.color1.asArray();
  46792. serializationObject.color2 = this.color2.asArray();
  46793. serializationObject.colorDead = this.colorDead.asArray();
  46794. serializationObject.updateSpeed = this.updateSpeed;
  46795. serializationObject.targetStopDuration = this.targetStopDuration;
  46796. serializationObject.textureMask = this.textureMask.asArray();
  46797. serializationObject.blendMode = this.blendMode;
  46798. serializationObject.customShader = this.customShader;
  46799. serializationObject.preventAutoStart = this.preventAutoStart;
  46800. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46801. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46802. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46803. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46804. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46805. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46806. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46807. return serializationObject;
  46808. };
  46809. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46810. var name = parsedParticleSystem.name;
  46811. var custom = null;
  46812. var program = null;
  46813. if (parsedParticleSystem.customShader) {
  46814. program = parsedParticleSystem.customShader;
  46815. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46816. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46817. }
  46818. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46819. particleSystem.customShader = program;
  46820. if (parsedParticleSystem.id) {
  46821. particleSystem.id = parsedParticleSystem.id;
  46822. }
  46823. // Auto start
  46824. if (parsedParticleSystem.preventAutoStart) {
  46825. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46826. }
  46827. // Texture
  46828. if (parsedParticleSystem.textureName) {
  46829. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46830. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46831. }
  46832. // Emitter
  46833. if (parsedParticleSystem.emitterId) {
  46834. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46835. }
  46836. else {
  46837. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46838. }
  46839. // Animations
  46840. if (parsedParticleSystem.animations) {
  46841. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46842. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46843. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46844. }
  46845. }
  46846. if (parsedParticleSystem.autoAnimate) {
  46847. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46848. }
  46849. // Particle system
  46850. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46851. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46852. particleSystem.minSize = parsedParticleSystem.minSize;
  46853. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46854. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46855. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46856. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46857. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46858. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46859. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46860. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46861. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46862. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46863. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46864. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46865. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46866. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46867. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46868. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46869. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46870. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46871. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46872. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46873. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46874. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46875. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46876. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46877. if (!particleSystem.preventAutoStart) {
  46878. particleSystem.start();
  46879. }
  46880. return particleSystem;
  46881. };
  46882. // Statics
  46883. ParticleSystem.BLENDMODE_ONEONE = 0;
  46884. ParticleSystem.BLENDMODE_STANDARD = 1;
  46885. return ParticleSystem;
  46886. }());
  46887. BABYLON.ParticleSystem = ParticleSystem;
  46888. })(BABYLON || (BABYLON = {}));
  46889. //# sourceMappingURL=babylon.particleSystem.js.map
  46890. var BABYLON;
  46891. (function (BABYLON) {
  46892. var BoxParticleEmitter = /** @class */ (function () {
  46893. // to be updated like the rest of emitters when breaking changes.
  46894. // all property should be come public variables and passed through constructor.
  46895. function BoxParticleEmitter(_particleSystem) {
  46896. this._particleSystem = _particleSystem;
  46897. }
  46898. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46899. get: function () {
  46900. return this._particleSystem.direction1;
  46901. },
  46902. set: function (value) {
  46903. this._particleSystem.direction1 = value;
  46904. },
  46905. enumerable: true,
  46906. configurable: true
  46907. });
  46908. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46909. get: function () {
  46910. return this._particleSystem.direction2;
  46911. },
  46912. set: function (value) {
  46913. this._particleSystem.direction2 = value;
  46914. },
  46915. enumerable: true,
  46916. configurable: true
  46917. });
  46918. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46919. get: function () {
  46920. return this._particleSystem.minEmitBox;
  46921. },
  46922. set: function (value) {
  46923. this._particleSystem.minEmitBox = value;
  46924. },
  46925. enumerable: true,
  46926. configurable: true
  46927. });
  46928. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46929. get: function () {
  46930. return this._particleSystem.maxEmitBox;
  46931. },
  46932. set: function (value) {
  46933. this._particleSystem.maxEmitBox = value;
  46934. },
  46935. enumerable: true,
  46936. configurable: true
  46937. });
  46938. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46939. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46940. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46941. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46942. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46943. };
  46944. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46945. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46946. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46947. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46949. };
  46950. return BoxParticleEmitter;
  46951. }());
  46952. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46953. })(BABYLON || (BABYLON = {}));
  46954. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46955. var BABYLON;
  46956. (function (BABYLON) {
  46957. var ConeParticleEmitter = /** @class */ (function () {
  46958. function ConeParticleEmitter(radius, angle) {
  46959. this.radius = radius;
  46960. this.angle = angle;
  46961. }
  46962. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46963. if (this.angle === 0) {
  46964. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46965. }
  46966. else {
  46967. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46968. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46969. var randX = Math.cos(phi) * Math.sin(theta);
  46970. var randY = Math.cos(theta);
  46971. var randZ = Math.sin(phi) * Math.sin(theta);
  46972. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46973. }
  46974. };
  46975. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46976. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46977. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46978. var randX = radius * Math.sin(s);
  46979. var randZ = radius * Math.cos(s);
  46980. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46981. };
  46982. return ConeParticleEmitter;
  46983. }());
  46984. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46985. })(BABYLON || (BABYLON = {}));
  46986. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46987. var BABYLON;
  46988. (function (BABYLON) {
  46989. var SphereParticleEmitter = /** @class */ (function () {
  46990. function SphereParticleEmitter(radius) {
  46991. this.radius = radius;
  46992. }
  46993. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46994. // measure the direction Vector from the emitter to the particle.
  46995. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46996. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46997. };
  46998. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46999. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  47000. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  47001. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  47002. var randY = this.radius * Math.cos(theta);
  47003. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  47004. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  47005. };
  47006. return SphereParticleEmitter;
  47007. }());
  47008. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  47009. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  47010. __extends(SphereDirectedParticleEmitter, _super);
  47011. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  47012. var _this = _super.call(this, radius) || this;
  47013. _this.direction1 = direction1;
  47014. _this.direction2 = direction2;
  47015. return _this;
  47016. }
  47017. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  47018. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  47019. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  47020. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  47021. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  47022. };
  47023. return SphereDirectedParticleEmitter;
  47024. }(SphereParticleEmitter));
  47025. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  47026. })(BABYLON || (BABYLON = {}));
  47027. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  47028. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  47029. var BABYLON;
  47030. (function (BABYLON) {
  47031. var SolidParticle = /** @class */ (function () {
  47032. /**
  47033. * Creates a Solid Particle object.
  47034. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47035. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47036. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47037. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  47038. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47039. * `shapeId` (integer) is the model shape identifier in the SPS.
  47040. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47041. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47042. */
  47043. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47044. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  47045. this.idx = 0; // particle global index
  47046. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47047. this.position = BABYLON.Vector3.Zero(); // position
  47048. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47049. this.scaling = BABYLON.Vector3.One(); // scaling
  47050. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47051. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47052. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  47053. this.alive = true; // alive
  47054. this.isVisible = true; // visibility
  47055. this._pos = 0; // index of this particle in the global "positions" array
  47056. this._ind = 0; // index of this particle in the global "indices" array
  47057. this.shapeId = 0; // model shape id
  47058. this.idxInShape = 0; // index of the particle in its shape id
  47059. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  47060. this.idx = particleIndex;
  47061. this._pos = positionIndex;
  47062. this._ind = indiceIndex;
  47063. this._model = model;
  47064. this.shapeId = shapeId;
  47065. this.idxInShape = idxInShape;
  47066. this._sps = sps;
  47067. if (modelBoundingInfo) {
  47068. this._modelBoundingInfo = modelBoundingInfo;
  47069. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47070. }
  47071. }
  47072. Object.defineProperty(SolidParticle.prototype, "scale", {
  47073. /**
  47074. * legacy support, changed scale to scaling
  47075. */
  47076. get: function () {
  47077. return this.scaling;
  47078. },
  47079. set: function (scale) {
  47080. this.scaling = scale;
  47081. },
  47082. enumerable: true,
  47083. configurable: true
  47084. });
  47085. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47086. /**
  47087. * legacy support, changed quaternion to rotationQuaternion
  47088. */
  47089. get: function () {
  47090. return this.rotationQuaternion;
  47091. },
  47092. set: function (q) {
  47093. this.rotationQuaternion = q;
  47094. },
  47095. enumerable: true,
  47096. configurable: true
  47097. });
  47098. /**
  47099. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47100. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47101. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47102. */
  47103. SolidParticle.prototype.intersectsMesh = function (target) {
  47104. if (!this._boundingInfo || !target._boundingInfo) {
  47105. return false;
  47106. }
  47107. if (this._sps._bSphereOnly) {
  47108. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47109. }
  47110. return this._boundingInfo.intersects(target._boundingInfo, false);
  47111. };
  47112. return SolidParticle;
  47113. }());
  47114. BABYLON.SolidParticle = SolidParticle;
  47115. var ModelShape = /** @class */ (function () {
  47116. /**
  47117. * 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.
  47118. * SPS internal tool, don't use it manually.
  47119. */
  47120. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  47121. this._indicesLength = 0; // length of the shape in the model indices array
  47122. this.shapeID = id;
  47123. this._shape = shape;
  47124. this._indicesLength = indicesLength;
  47125. this._shapeUV = shapeUV;
  47126. this._positionFunction = posFunction;
  47127. this._vertexFunction = vtxFunction;
  47128. }
  47129. return ModelShape;
  47130. }());
  47131. BABYLON.ModelShape = ModelShape;
  47132. var DepthSortedParticle = /** @class */ (function () {
  47133. function DepthSortedParticle() {
  47134. this.ind = 0; // index of the particle in the "indices" array
  47135. this.indicesLength = 0; // length of the particle shape in the "indices" array
  47136. this.sqDistance = 0.0; // squared distance from the particle to the camera
  47137. }
  47138. return DepthSortedParticle;
  47139. }());
  47140. BABYLON.DepthSortedParticle = DepthSortedParticle;
  47141. })(BABYLON || (BABYLON = {}));
  47142. //# sourceMappingURL=babylon.solidParticle.js.map
  47143. var BABYLON;
  47144. (function (BABYLON) {
  47145. /**
  47146. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47147. */
  47148. var SolidParticleSystem = /** @class */ (function () {
  47149. /**
  47150. * Creates a SPS (Solid Particle System) object.
  47151. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47152. * `scene` (Scene) is the scene in which the SPS is added.
  47153. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47154. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47155. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47156. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47157. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47158. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47159. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47160. */
  47161. function SolidParticleSystem(name, scene, options) {
  47162. // public members
  47163. /**
  47164. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47165. * Example : var p = SPS.particles[i];
  47166. */
  47167. this.particles = new Array();
  47168. /**
  47169. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47170. */
  47171. this.nbParticles = 0;
  47172. /**
  47173. * If the particles must ever face the camera (default false). Useful for planar particles.
  47174. */
  47175. this.billboard = false;
  47176. /**
  47177. * Recompute normals when adding a shape
  47178. */
  47179. this.recomputeNormals = true;
  47180. /**
  47181. * This a counter ofr your own usage. It's not set by any SPS functions.
  47182. */
  47183. this.counter = 0;
  47184. /**
  47185. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47186. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47187. */
  47188. this.vars = {};
  47189. this._positions = new Array();
  47190. this._indices = new Array();
  47191. this._normals = new Array();
  47192. this._colors = new Array();
  47193. this._uvs = new Array();
  47194. this._index = 0; // indices index
  47195. this._updatable = true;
  47196. this._pickable = false;
  47197. this._isVisibilityBoxLocked = false;
  47198. this._alwaysVisible = false;
  47199. this._depthSort = false;
  47200. this._shapeCounter = 0;
  47201. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47202. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47203. this._computeParticleColor = true;
  47204. this._computeParticleTexture = true;
  47205. this._computeParticleRotation = true;
  47206. this._computeParticleVertex = false;
  47207. this._computeBoundingBox = false;
  47208. this._depthSortParticles = true;
  47209. this._cam_axisZ = BABYLON.Vector3.Zero();
  47210. this._cam_axisY = BABYLON.Vector3.Zero();
  47211. this._cam_axisX = BABYLON.Vector3.Zero();
  47212. this._axisZ = BABYLON.Axis.Z;
  47213. this._camDir = BABYLON.Vector3.Zero();
  47214. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47215. this._rotMatrix = new BABYLON.Matrix();
  47216. this._invertMatrix = new BABYLON.Matrix();
  47217. this._rotated = BABYLON.Vector3.Zero();
  47218. this._quaternion = new BABYLON.Quaternion();
  47219. this._vertex = BABYLON.Vector3.Zero();
  47220. this._normal = BABYLON.Vector3.Zero();
  47221. this._yaw = 0.0;
  47222. this._pitch = 0.0;
  47223. this._roll = 0.0;
  47224. this._halfroll = 0.0;
  47225. this._halfpitch = 0.0;
  47226. this._halfyaw = 0.0;
  47227. this._sinRoll = 0.0;
  47228. this._cosRoll = 0.0;
  47229. this._sinPitch = 0.0;
  47230. this._cosPitch = 0.0;
  47231. this._sinYaw = 0.0;
  47232. this._cosYaw = 0.0;
  47233. this._mustUnrotateFixedNormals = false;
  47234. this._minimum = BABYLON.Tmp.Vector3[0];
  47235. this._maximum = BABYLON.Tmp.Vector3[1];
  47236. this._minBbox = BABYLON.Tmp.Vector3[4];
  47237. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47238. this._particlesIntersect = false;
  47239. this._depthSortFunction = function (p1, p2) {
  47240. return (p2.sqDistance - p1.sqDistance);
  47241. };
  47242. this._needs32Bits = false;
  47243. this._bSphereOnly = false;
  47244. this._bSphereRadiusFactor = 1.0;
  47245. this.name = name;
  47246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47247. this._camera = scene.activeCamera;
  47248. this._pickable = options ? options.isPickable : false;
  47249. this._depthSort = options ? options.enableDepthSort : false;
  47250. this._particlesIntersect = options ? options.particleIntersection : false;
  47251. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47252. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47253. if (options && options.updatable) {
  47254. this._updatable = options.updatable;
  47255. }
  47256. else {
  47257. this._updatable = true;
  47258. }
  47259. if (this._pickable) {
  47260. this.pickedParticles = [];
  47261. }
  47262. if (this._depthSort) {
  47263. this.depthSortedParticles = [];
  47264. }
  47265. }
  47266. /**
  47267. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47268. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47269. */
  47270. SolidParticleSystem.prototype.buildMesh = function () {
  47271. if (this.nbParticles === 0) {
  47272. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47273. this.addShape(triangle, 1);
  47274. triangle.dispose();
  47275. }
  47276. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47277. this._positions32 = new Float32Array(this._positions);
  47278. this._uvs32 = new Float32Array(this._uvs);
  47279. this._colors32 = new Float32Array(this._colors);
  47280. if (this.recomputeNormals) {
  47281. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47282. }
  47283. this._normals32 = new Float32Array(this._normals);
  47284. this._fixedNormal32 = new Float32Array(this._normals);
  47285. if (this._mustUnrotateFixedNormals) {
  47286. this._unrotateFixedNormals();
  47287. }
  47288. var vertexData = new BABYLON.VertexData();
  47289. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47290. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47291. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47292. if (this._uvs32) {
  47293. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47294. ;
  47295. }
  47296. if (this._colors32) {
  47297. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47298. }
  47299. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47300. vertexData.applyToMesh(mesh, this._updatable);
  47301. this.mesh = mesh;
  47302. this.mesh.isPickable = this._pickable;
  47303. // free memory
  47304. if (!this._depthSort) {
  47305. this._indices = null;
  47306. }
  47307. this._positions = null;
  47308. this._normals = null;
  47309. this._uvs = null;
  47310. this._colors = null;
  47311. if (!this._updatable) {
  47312. this.particles.length = 0;
  47313. }
  47314. return mesh;
  47315. };
  47316. /**
  47317. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47318. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47319. * Thus the particles generated from `digest()` have their property `position` set yet.
  47320. * `mesh` ( Mesh ) is the mesh to be digested
  47321. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47322. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47323. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47324. */
  47325. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47326. var size = (options && options.facetNb) || 1;
  47327. var number = (options && options.number) || 0;
  47328. var delta = (options && options.delta) || 0;
  47329. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47330. var meshInd = mesh.getIndices();
  47331. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47332. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47333. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47334. var f = 0; // facet counter
  47335. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47336. // compute size from number
  47337. if (number) {
  47338. number = (number > totalFacets) ? totalFacets : number;
  47339. size = Math.round(totalFacets / number);
  47340. delta = 0;
  47341. }
  47342. else {
  47343. size = (size > totalFacets) ? totalFacets : size;
  47344. }
  47345. var facetPos = []; // submesh positions
  47346. var facetInd = []; // submesh indices
  47347. var facetUV = []; // submesh UV
  47348. var facetCol = []; // submesh colors
  47349. var barycenter = BABYLON.Tmp.Vector3[0];
  47350. var sizeO = size;
  47351. while (f < totalFacets) {
  47352. size = sizeO + Math.floor((1 + delta) * Math.random());
  47353. if (f > totalFacets - size) {
  47354. size = totalFacets - f;
  47355. }
  47356. // reset temp arrays
  47357. facetPos.length = 0;
  47358. facetInd.length = 0;
  47359. facetUV.length = 0;
  47360. facetCol.length = 0;
  47361. // iterate over "size" facets
  47362. var fi = 0;
  47363. for (var j = f * 3; j < (f + size) * 3; j++) {
  47364. facetInd.push(fi);
  47365. var i = meshInd[j];
  47366. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47367. if (meshUV) {
  47368. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47369. }
  47370. if (meshCol) {
  47371. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47372. }
  47373. fi++;
  47374. }
  47375. // create a model shape for each single particle
  47376. var idx = this.nbParticles;
  47377. var shape = this._posToShape(facetPos);
  47378. var shapeUV = this._uvsToShapeUV(facetUV);
  47379. // compute the barycenter of the shape
  47380. var v;
  47381. for (v = 0; v < shape.length; v++) {
  47382. barycenter.addInPlace(shape[v]);
  47383. }
  47384. barycenter.scaleInPlace(1 / shape.length);
  47385. // shift the shape from its barycenter to the origin
  47386. for (v = 0; v < shape.length; v++) {
  47387. shape[v].subtractInPlace(barycenter);
  47388. }
  47389. var bInfo;
  47390. if (this._particlesIntersect) {
  47391. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47392. }
  47393. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47394. // add the particle in the SPS
  47395. var currentPos = this._positions.length;
  47396. var currentInd = this._indices.length;
  47397. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47398. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47399. // initialize the particle position
  47400. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47401. this._index += shape.length;
  47402. idx++;
  47403. this.nbParticles++;
  47404. this._shapeCounter++;
  47405. f += size;
  47406. }
  47407. return this;
  47408. };
  47409. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47410. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47411. var index = 0;
  47412. var idx = 0;
  47413. for (var p = 0; p < this.particles.length; p++) {
  47414. this._particle = this.particles[p];
  47415. this._shape = this._particle._model._shape;
  47416. if (this._particle.rotationQuaternion) {
  47417. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47418. }
  47419. else {
  47420. this._yaw = this._particle.rotation.y;
  47421. this._pitch = this._particle.rotation.x;
  47422. this._roll = this._particle.rotation.z;
  47423. this._quaternionRotationYPR();
  47424. }
  47425. this._quaternionToRotationMatrix();
  47426. this._rotMatrix.invertToRef(this._invertMatrix);
  47427. for (var pt = 0; pt < this._shape.length; pt++) {
  47428. idx = index + pt * 3;
  47429. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47430. this._fixedNormal32[idx] = this._normal.x;
  47431. this._fixedNormal32[idx + 1] = this._normal.y;
  47432. this._fixedNormal32[idx + 2] = this._normal.z;
  47433. }
  47434. index = idx + 3;
  47435. }
  47436. };
  47437. //reset copy
  47438. SolidParticleSystem.prototype._resetCopy = function () {
  47439. this._copy.position.x = 0;
  47440. this._copy.position.y = 0;
  47441. this._copy.position.z = 0;
  47442. this._copy.rotation.x = 0;
  47443. this._copy.rotation.y = 0;
  47444. this._copy.rotation.z = 0;
  47445. this._copy.rotationQuaternion = null;
  47446. this._copy.scaling.x = 1.0;
  47447. this._copy.scaling.y = 1.0;
  47448. this._copy.scaling.z = 1.0;
  47449. this._copy.uvs.x = 0;
  47450. this._copy.uvs.y = 0;
  47451. this._copy.uvs.z = 1.0;
  47452. this._copy.uvs.w = 1.0;
  47453. this._copy.color = null;
  47454. };
  47455. // _meshBuilder : inserts the shape model in the global SPS mesh
  47456. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47457. var i;
  47458. var u = 0;
  47459. var c = 0;
  47460. var n = 0;
  47461. this._resetCopy();
  47462. if (options && options.positionFunction) {
  47463. options.positionFunction(this._copy, idx, idxInShape);
  47464. this._mustUnrotateFixedNormals = true;
  47465. }
  47466. if (this._copy.rotationQuaternion) {
  47467. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47468. }
  47469. else {
  47470. this._yaw = this._copy.rotation.y;
  47471. this._pitch = this._copy.rotation.x;
  47472. this._roll = this._copy.rotation.z;
  47473. this._quaternionRotationYPR();
  47474. }
  47475. this._quaternionToRotationMatrix();
  47476. for (i = 0; i < shape.length; i++) {
  47477. this._vertex.x = shape[i].x;
  47478. this._vertex.y = shape[i].y;
  47479. this._vertex.z = shape[i].z;
  47480. if (options && options.vertexFunction) {
  47481. options.vertexFunction(this._copy, this._vertex, i);
  47482. }
  47483. this._vertex.x *= this._copy.scaling.x;
  47484. this._vertex.y *= this._copy.scaling.y;
  47485. this._vertex.z *= this._copy.scaling.z;
  47486. this._vertex.x += this._copy.pivot.x;
  47487. this._vertex.y += this._copy.pivot.y;
  47488. this._vertex.z += this._copy.pivot.z;
  47489. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47490. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47491. if (meshUV) {
  47492. 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);
  47493. u += 2;
  47494. }
  47495. if (this._copy.color) {
  47496. this._color = this._copy.color;
  47497. }
  47498. else if (meshCol && meshCol[c] !== undefined) {
  47499. this._color.r = meshCol[c];
  47500. this._color.g = meshCol[c + 1];
  47501. this._color.b = meshCol[c + 2];
  47502. this._color.a = meshCol[c + 3];
  47503. }
  47504. else {
  47505. this._color.r = 1.0;
  47506. this._color.g = 1.0;
  47507. this._color.b = 1.0;
  47508. this._color.a = 1.0;
  47509. }
  47510. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47511. c += 4;
  47512. if (!this.recomputeNormals && meshNor) {
  47513. this._normal.x = meshNor[n];
  47514. this._normal.y = meshNor[n + 1];
  47515. this._normal.z = meshNor[n + 2];
  47516. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47517. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47518. n += 3;
  47519. }
  47520. }
  47521. for (i = 0; i < meshInd.length; i++) {
  47522. var current_ind = p + meshInd[i];
  47523. indices.push(current_ind);
  47524. if (current_ind > 65535) {
  47525. this._needs32Bits = true;
  47526. }
  47527. }
  47528. if (this._pickable) {
  47529. var nbfaces = meshInd.length / 3;
  47530. for (i = 0; i < nbfaces; i++) {
  47531. this.pickedParticles.push({ idx: idx, faceId: i });
  47532. }
  47533. }
  47534. if (this._depthSort) {
  47535. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47536. }
  47537. return this._copy;
  47538. };
  47539. // returns a shape array from positions array
  47540. SolidParticleSystem.prototype._posToShape = function (positions) {
  47541. var shape = [];
  47542. for (var i = 0; i < positions.length; i += 3) {
  47543. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47544. }
  47545. return shape;
  47546. };
  47547. // returns a shapeUV array from a Vector4 uvs
  47548. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47549. var shapeUV = [];
  47550. if (uvs) {
  47551. for (var i = 0; i < uvs.length; i++)
  47552. shapeUV.push(uvs[i]);
  47553. }
  47554. return shapeUV;
  47555. };
  47556. // adds a new particle object in the particles array
  47557. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47558. if (bInfo === void 0) { bInfo = null; }
  47559. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47560. this.particles.push(sp);
  47561. return sp;
  47562. };
  47563. /**
  47564. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47565. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47566. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47567. * `nb` (positive integer) the number of particles to be created from this model
  47568. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47569. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47570. */
  47571. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47572. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47573. var meshInd = mesh.getIndices();
  47574. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47575. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47576. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47577. var bbInfo;
  47578. if (this._particlesIntersect) {
  47579. bbInfo = mesh.getBoundingInfo();
  47580. }
  47581. var shape = this._posToShape(meshPos);
  47582. var shapeUV = this._uvsToShapeUV(meshUV);
  47583. var posfunc = options ? options.positionFunction : null;
  47584. var vtxfunc = options ? options.vertexFunction : null;
  47585. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47586. // particles
  47587. var sp;
  47588. var currentCopy;
  47589. var idx = this.nbParticles;
  47590. for (var i = 0; i < nb; i++) {
  47591. var currentPos = this._positions.length;
  47592. var currentInd = this._indices.length;
  47593. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47594. if (this._updatable) {
  47595. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47596. sp.position.copyFrom(currentCopy.position);
  47597. sp.rotation.copyFrom(currentCopy.rotation);
  47598. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47599. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47600. }
  47601. if (currentCopy.color && sp.color) {
  47602. sp.color.copyFrom(currentCopy.color);
  47603. }
  47604. sp.scaling.copyFrom(currentCopy.scaling);
  47605. sp.uvs.copyFrom(currentCopy.uvs);
  47606. }
  47607. this._index += shape.length;
  47608. idx++;
  47609. }
  47610. this.nbParticles += nb;
  47611. this._shapeCounter++;
  47612. return this._shapeCounter - 1;
  47613. };
  47614. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47615. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47616. this._resetCopy();
  47617. if (particle._model._positionFunction) {
  47618. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47619. }
  47620. if (this._copy.rotationQuaternion) {
  47621. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47622. }
  47623. else {
  47624. this._yaw = this._copy.rotation.y;
  47625. this._pitch = this._copy.rotation.x;
  47626. this._roll = this._copy.rotation.z;
  47627. this._quaternionRotationYPR();
  47628. }
  47629. this._quaternionToRotationMatrix();
  47630. this._shape = particle._model._shape;
  47631. for (var pt = 0; pt < this._shape.length; pt++) {
  47632. this._vertex.x = this._shape[pt].x;
  47633. this._vertex.y = this._shape[pt].y;
  47634. this._vertex.z = this._shape[pt].z;
  47635. if (particle._model._vertexFunction) {
  47636. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47637. }
  47638. this._vertex.x *= this._copy.scaling.x;
  47639. this._vertex.y *= this._copy.scaling.y;
  47640. this._vertex.z *= this._copy.scaling.z;
  47641. this._vertex.x += this._copy.pivot.x;
  47642. this._vertex.y += this._copy.pivot.y;
  47643. this._vertex.z += this._copy.pivot.z;
  47644. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47645. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47646. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47647. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47648. }
  47649. particle.position.x = 0.0;
  47650. particle.position.y = 0.0;
  47651. particle.position.z = 0.0;
  47652. particle.rotation.x = 0.0;
  47653. particle.rotation.y = 0.0;
  47654. particle.rotation.z = 0.0;
  47655. particle.rotationQuaternion = null;
  47656. particle.scaling.x = 1.0;
  47657. particle.scaling.y = 1.0;
  47658. particle.scaling.z = 1.0;
  47659. };
  47660. /**
  47661. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47662. * Returns the SPS.
  47663. */
  47664. SolidParticleSystem.prototype.rebuildMesh = function () {
  47665. for (var p = 0; p < this.particles.length; p++) {
  47666. this._rebuildParticle(this.particles[p]);
  47667. }
  47668. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47669. return this;
  47670. };
  47671. /**
  47672. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47673. * This method calls `updateParticle()` for each particle of the SPS.
  47674. * For an animated SPS, it is usually called within the render loop.
  47675. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47676. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47677. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47678. * Returns the SPS.
  47679. */
  47680. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47681. if (start === void 0) { start = 0; }
  47682. if (end === void 0) { end = this.nbParticles - 1; }
  47683. if (update === void 0) { update = true; }
  47684. if (!this._updatable) {
  47685. return this;
  47686. }
  47687. // custom beforeUpdate
  47688. this.beforeUpdateParticles(start, end, update);
  47689. this._cam_axisX.x = 1.0;
  47690. this._cam_axisX.y = 0.0;
  47691. this._cam_axisX.z = 0.0;
  47692. this._cam_axisY.x = 0.0;
  47693. this._cam_axisY.y = 1.0;
  47694. this._cam_axisY.z = 0.0;
  47695. this._cam_axisZ.x = 0.0;
  47696. this._cam_axisZ.y = 0.0;
  47697. this._cam_axisZ.z = 1.0;
  47698. // cases when the World Matrix is to be computed first
  47699. if (this.billboard || this._depthSort) {
  47700. this.mesh.computeWorldMatrix(true);
  47701. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47702. }
  47703. // if the particles will always face the camera
  47704. if (this.billboard) {
  47705. // compute the camera position and un-rotate it by the current mesh rotation
  47706. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47707. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47708. this._cam_axisZ.normalize();
  47709. // same for camera up vector extracted from the cam view matrix
  47710. var view = this._camera.getViewMatrix(true);
  47711. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47712. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47713. this._cam_axisY.normalize();
  47714. this._cam_axisX.normalize();
  47715. }
  47716. // if depthSort, compute the camera global position in the mesh local system
  47717. if (this._depthSort) {
  47718. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47719. }
  47720. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47721. var idx = 0; // current position index in the global array positions32
  47722. var index = 0; // position start index in the global array positions32 of the current particle
  47723. var colidx = 0; // current color index in the global array colors32
  47724. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47725. var uvidx = 0; // current uv index in the global array uvs32
  47726. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47727. var pt = 0; // current index in the particle model shape
  47728. if (this.mesh.isFacetDataEnabled) {
  47729. this._computeBoundingBox = true;
  47730. }
  47731. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47732. if (this._computeBoundingBox) {
  47733. if (start == 0 && end == this.nbParticles - 1) {
  47734. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47735. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47736. }
  47737. else {
  47738. if (this.mesh._boundingInfo) {
  47739. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47740. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47741. }
  47742. }
  47743. }
  47744. // particle loop
  47745. index = this.particles[start]._pos;
  47746. var vpos = (index / 3) | 0;
  47747. colorIndex = vpos * 4;
  47748. uvIndex = vpos * 2;
  47749. for (var p = start; p <= end; p++) {
  47750. this._particle = this.particles[p];
  47751. this._shape = this._particle._model._shape;
  47752. this._shapeUV = this._particle._model._shapeUV;
  47753. // call to custom user function to update the particle properties
  47754. this.updateParticle(this._particle);
  47755. // camera-particle distance for depth sorting
  47756. if (this._depthSort && this._depthSortParticles) {
  47757. var dsp = this.depthSortedParticles[p];
  47758. dsp.ind = this._particle._ind;
  47759. dsp.indicesLength = this._particle._model._indicesLength;
  47760. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47761. }
  47762. // skip the computations for inactive or already invisible particles
  47763. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47764. // increment indexes for the next particle
  47765. pt = this._shape.length;
  47766. index += pt * 3;
  47767. colorIndex += pt * 4;
  47768. uvIndex += pt * 2;
  47769. continue;
  47770. }
  47771. if (this._particle.isVisible) {
  47772. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47773. // particle rotation matrix
  47774. if (this.billboard) {
  47775. this._particle.rotation.x = 0.0;
  47776. this._particle.rotation.y = 0.0;
  47777. }
  47778. if (this._computeParticleRotation || this.billboard) {
  47779. if (this._particle.rotationQuaternion) {
  47780. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47781. }
  47782. else {
  47783. this._yaw = this._particle.rotation.y;
  47784. this._pitch = this._particle.rotation.x;
  47785. this._roll = this._particle.rotation.z;
  47786. this._quaternionRotationYPR();
  47787. }
  47788. this._quaternionToRotationMatrix();
  47789. }
  47790. // particle vertex loop
  47791. for (pt = 0; pt < this._shape.length; pt++) {
  47792. idx = index + pt * 3;
  47793. colidx = colorIndex + pt * 4;
  47794. uvidx = uvIndex + pt * 2;
  47795. this._vertex.x = this._shape[pt].x;
  47796. this._vertex.y = this._shape[pt].y;
  47797. this._vertex.z = this._shape[pt].z;
  47798. if (this._computeParticleVertex) {
  47799. this.updateParticleVertex(this._particle, this._vertex, pt);
  47800. }
  47801. // positions
  47802. this._vertex.x *= this._particle.scaling.x;
  47803. this._vertex.y *= this._particle.scaling.y;
  47804. this._vertex.z *= this._particle.scaling.z;
  47805. this._vertex.x += this._particle.pivot.x;
  47806. this._vertex.y += this._particle.pivot.y;
  47807. this._vertex.z += this._particle.pivot.z;
  47808. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47809. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47810. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47811. 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;
  47812. 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;
  47813. 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;
  47814. if (this._computeBoundingBox) {
  47815. if (this._positions32[idx] < this._minimum.x) {
  47816. this._minimum.x = this._positions32[idx];
  47817. }
  47818. if (this._positions32[idx] > this._maximum.x) {
  47819. this._maximum.x = this._positions32[idx];
  47820. }
  47821. if (this._positions32[idx + 1] < this._minimum.y) {
  47822. this._minimum.y = this._positions32[idx + 1];
  47823. }
  47824. if (this._positions32[idx + 1] > this._maximum.y) {
  47825. this._maximum.y = this._positions32[idx + 1];
  47826. }
  47827. if (this._positions32[idx + 2] < this._minimum.z) {
  47828. this._minimum.z = this._positions32[idx + 2];
  47829. }
  47830. if (this._positions32[idx + 2] > this._maximum.z) {
  47831. this._maximum.z = this._positions32[idx + 2];
  47832. }
  47833. }
  47834. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47835. if (!this._computeParticleVertex) {
  47836. this._normal.x = this._fixedNormal32[idx];
  47837. this._normal.y = this._fixedNormal32[idx + 1];
  47838. this._normal.z = this._fixedNormal32[idx + 2];
  47839. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47840. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47841. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47842. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47843. 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;
  47844. 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;
  47845. }
  47846. if (this._computeParticleColor && this._particle.color) {
  47847. this._colors32[colidx] = this._particle.color.r;
  47848. this._colors32[colidx + 1] = this._particle.color.g;
  47849. this._colors32[colidx + 2] = this._particle.color.b;
  47850. this._colors32[colidx + 3] = this._particle.color.a;
  47851. }
  47852. if (this._computeParticleTexture) {
  47853. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47854. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47855. }
  47856. }
  47857. }
  47858. else {
  47859. this._particle._stillInvisible = true; // mark the particle as invisible
  47860. for (pt = 0; pt < this._shape.length; pt++) {
  47861. idx = index + pt * 3;
  47862. colidx = colorIndex + pt * 4;
  47863. uvidx = uvIndex + pt * 2;
  47864. this._positions32[idx] = 0.0;
  47865. this._positions32[idx + 1] = 0.0;
  47866. this._positions32[idx + 2] = 0.0;
  47867. this._normals32[idx] = 0.0;
  47868. this._normals32[idx + 1] = 0.0;
  47869. this._normals32[idx + 2] = 0.0;
  47870. if (this._computeParticleColor && this._particle.color) {
  47871. this._colors32[colidx] = this._particle.color.r;
  47872. this._colors32[colidx + 1] = this._particle.color.g;
  47873. this._colors32[colidx + 2] = this._particle.color.b;
  47874. this._colors32[colidx + 3] = this._particle.color.a;
  47875. }
  47876. if (this._computeParticleTexture) {
  47877. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47878. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47879. }
  47880. }
  47881. }
  47882. // if the particle intersections must be computed : update the bbInfo
  47883. if (this._particlesIntersect) {
  47884. var bInfo = this._particle._boundingInfo;
  47885. var bBox = bInfo.boundingBox;
  47886. var bSphere = bInfo.boundingSphere;
  47887. if (!this._bSphereOnly) {
  47888. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47889. for (var b = 0; b < bBox.vectors.length; b++) {
  47890. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47891. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47892. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47893. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47894. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47895. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47896. 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;
  47897. 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;
  47898. 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;
  47899. }
  47900. bBox._update(this.mesh._worldMatrix);
  47901. }
  47902. // place and scale the particle bouding sphere in the SPS local system, then update it
  47903. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47904. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47905. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47906. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47907. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47908. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47909. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47910. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47911. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47912. 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));
  47913. bSphere._update(this.mesh._worldMatrix);
  47914. }
  47915. // increment indexes for the next particle
  47916. index = idx + 3;
  47917. colorIndex = colidx + 4;
  47918. uvIndex = uvidx + 2;
  47919. }
  47920. // if the VBO must be updated
  47921. if (update) {
  47922. if (this._computeParticleColor) {
  47923. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47924. }
  47925. if (this._computeParticleTexture) {
  47926. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47927. }
  47928. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47929. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47930. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47931. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47932. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47933. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47934. for (var i = 0; i < this._normals32.length; i++) {
  47935. this._fixedNormal32[i] = this._normals32[i];
  47936. }
  47937. }
  47938. if (!this.mesh.areNormalsFrozen) {
  47939. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47940. }
  47941. }
  47942. if (this._depthSort && this._depthSortParticles) {
  47943. this.depthSortedParticles.sort(this._depthSortFunction);
  47944. var dspl = this.depthSortedParticles.length;
  47945. var sorted = 0;
  47946. var lind = 0;
  47947. var sind = 0;
  47948. var sid = 0;
  47949. for (sorted = 0; sorted < dspl; sorted++) {
  47950. lind = this.depthSortedParticles[sorted].indicesLength;
  47951. sind = this.depthSortedParticles[sorted].ind;
  47952. for (var i = 0; i < lind; i++) {
  47953. this._indices32[sid] = this._indices[sind + i];
  47954. sid++;
  47955. }
  47956. }
  47957. this.mesh.updateIndices(this._indices32);
  47958. }
  47959. }
  47960. if (this._computeBoundingBox) {
  47961. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47962. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47963. }
  47964. this.afterUpdateParticles(start, end, update);
  47965. return this;
  47966. };
  47967. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47968. this._halfroll = this._roll * 0.5;
  47969. this._halfpitch = this._pitch * 0.5;
  47970. this._halfyaw = this._yaw * 0.5;
  47971. this._sinRoll = Math.sin(this._halfroll);
  47972. this._cosRoll = Math.cos(this._halfroll);
  47973. this._sinPitch = Math.sin(this._halfpitch);
  47974. this._cosPitch = Math.cos(this._halfpitch);
  47975. this._sinYaw = Math.sin(this._halfyaw);
  47976. this._cosYaw = Math.cos(this._halfyaw);
  47977. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47978. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47979. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47980. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47981. };
  47982. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47983. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47984. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47985. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47986. this._rotMatrix.m[3] = 0;
  47987. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47988. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47989. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47990. this._rotMatrix.m[7] = 0;
  47991. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47992. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47993. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47994. this._rotMatrix.m[11] = 0;
  47995. this._rotMatrix.m[12] = 0;
  47996. this._rotMatrix.m[13] = 0;
  47997. this._rotMatrix.m[14] = 0;
  47998. this._rotMatrix.m[15] = 1.0;
  47999. };
  48000. /**
  48001. * Disposes the SPS.
  48002. * Returns nothing.
  48003. */
  48004. SolidParticleSystem.prototype.dispose = function () {
  48005. this.mesh.dispose();
  48006. this.vars = null;
  48007. // drop references to internal big arrays for the GC
  48008. this._positions = null;
  48009. this._indices = null;
  48010. this._normals = null;
  48011. this._uvs = null;
  48012. this._colors = null;
  48013. this._indices32 = null;
  48014. this._positions32 = null;
  48015. this._normals32 = null;
  48016. this._fixedNormal32 = null;
  48017. this._uvs32 = null;
  48018. this._colors32 = null;
  48019. this.pickedParticles = null;
  48020. };
  48021. /**
  48022. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48023. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48024. * Returns the SPS.
  48025. */
  48026. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48027. if (!this._isVisibilityBoxLocked) {
  48028. this.mesh.refreshBoundingInfo();
  48029. }
  48030. return this;
  48031. };
  48032. /**
  48033. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48034. * @param size the size (float) of the visibility box
  48035. * note : this doesn't lock the SPS mesh bounding box.
  48036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48037. */
  48038. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48039. var vis = size / 2;
  48040. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48041. };
  48042. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48043. // getter and setter
  48044. get: function () {
  48045. return this._alwaysVisible;
  48046. },
  48047. /**
  48048. * Sets the SPS as always visible or not
  48049. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48050. */
  48051. set: function (val) {
  48052. this._alwaysVisible = val;
  48053. this.mesh.alwaysSelectAsActiveMesh = val;
  48054. },
  48055. enumerable: true,
  48056. configurable: true
  48057. });
  48058. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48059. get: function () {
  48060. return this._isVisibilityBoxLocked;
  48061. },
  48062. /**
  48063. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48064. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48065. */
  48066. set: function (val) {
  48067. this._isVisibilityBoxLocked = val;
  48068. var boundingInfo = this.mesh.getBoundingInfo();
  48069. boundingInfo.isLocked = val;
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48075. // getters
  48076. get: function () {
  48077. return this._computeParticleRotation;
  48078. },
  48079. // Optimizer setters
  48080. /**
  48081. * Tells to `setParticles()` to compute the particle rotations or not.
  48082. * Default value : true. The SPS is faster when it's set to false.
  48083. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48084. */
  48085. set: function (val) {
  48086. this._computeParticleRotation = val;
  48087. },
  48088. enumerable: true,
  48089. configurable: true
  48090. });
  48091. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48092. get: function () {
  48093. return this._computeParticleColor;
  48094. },
  48095. /**
  48096. * Tells to `setParticles()` to compute the particle colors or not.
  48097. * Default value : true. The SPS is faster when it's set to false.
  48098. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48099. */
  48100. set: function (val) {
  48101. this._computeParticleColor = val;
  48102. },
  48103. enumerable: true,
  48104. configurable: true
  48105. });
  48106. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48107. get: function () {
  48108. return this._computeParticleTexture;
  48109. },
  48110. /**
  48111. * Tells to `setParticles()` to compute the particle textures or not.
  48112. * Default value : true. The SPS is faster when it's set to false.
  48113. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48114. */
  48115. set: function (val) {
  48116. this._computeParticleTexture = val;
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48122. get: function () {
  48123. return this._computeParticleVertex;
  48124. },
  48125. /**
  48126. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48127. * Default value : false. The SPS is faster when it's set to false.
  48128. * Note : the particle custom vertex positions aren't stored values.
  48129. */
  48130. set: function (val) {
  48131. this._computeParticleVertex = val;
  48132. },
  48133. enumerable: true,
  48134. configurable: true
  48135. });
  48136. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48137. get: function () {
  48138. return this._computeBoundingBox;
  48139. },
  48140. /**
  48141. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48142. */
  48143. set: function (val) {
  48144. this._computeBoundingBox = val;
  48145. },
  48146. enumerable: true,
  48147. configurable: true
  48148. });
  48149. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48150. get: function () {
  48151. return this._depthSortParticles;
  48152. },
  48153. /**
  48154. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48155. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48156. * Default : `true`
  48157. */
  48158. set: function (val) {
  48159. this._depthSortParticles = val;
  48160. },
  48161. enumerable: true,
  48162. configurable: true
  48163. });
  48164. // =======================================================================
  48165. // Particle behavior logic
  48166. // these following methods may be overwritten by the user to fit his needs
  48167. /**
  48168. * This function does nothing. It may be overwritten to set all the particle first values.
  48169. * The SPS doesn't call this function, you may have to call it by your own.
  48170. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48171. */
  48172. SolidParticleSystem.prototype.initParticles = function () {
  48173. };
  48174. /**
  48175. * This function does nothing. It may be overwritten to recycle a particle.
  48176. * The SPS doesn't call this function, you may have to call it by your own.
  48177. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48178. */
  48179. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48180. return particle;
  48181. };
  48182. /**
  48183. * Updates a particle : this function should be overwritten by the user.
  48184. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48185. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48186. * ex : just set a particle position or velocity and recycle conditions
  48187. */
  48188. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48189. return particle;
  48190. };
  48191. /**
  48192. * Updates a vertex of a particle : it can be overwritten by the user.
  48193. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48194. * @param particle the current particle
  48195. * @param vertex the current index of the current particle
  48196. * @param pt the index of the current vertex in the particle shape
  48197. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48198. * ex : just set a vertex particle position
  48199. */
  48200. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48201. return vertex;
  48202. };
  48203. /**
  48204. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48205. * This does nothing and may be overwritten by the user.
  48206. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48207. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48208. * @param update the boolean update value actually passed to setParticles()
  48209. */
  48210. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48211. };
  48212. /**
  48213. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48214. * This will be passed three parameters.
  48215. * This does nothing and may be overwritten by the user.
  48216. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48217. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48218. * @param update the boolean update value actually passed to setParticles()
  48219. */
  48220. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48221. };
  48222. return SolidParticleSystem;
  48223. }());
  48224. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48225. })(BABYLON || (BABYLON = {}));
  48226. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48227. var BABYLON;
  48228. (function (BABYLON) {
  48229. var ShaderMaterial = /** @class */ (function (_super) {
  48230. __extends(ShaderMaterial, _super);
  48231. function ShaderMaterial(name, scene, shaderPath, options) {
  48232. var _this = _super.call(this, name, scene) || this;
  48233. _this._textures = {};
  48234. _this._textureArrays = {};
  48235. _this._floats = {};
  48236. _this._ints = {};
  48237. _this._floatsArrays = {};
  48238. _this._colors3 = {};
  48239. _this._colors3Arrays = {};
  48240. _this._colors4 = {};
  48241. _this._vectors2 = {};
  48242. _this._vectors3 = {};
  48243. _this._vectors4 = {};
  48244. _this._matrices = {};
  48245. _this._matrices3x3 = {};
  48246. _this._matrices2x2 = {};
  48247. _this._vectors2Arrays = {};
  48248. _this._vectors3Arrays = {};
  48249. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48250. _this._shaderPath = shaderPath;
  48251. options.needAlphaBlending = options.needAlphaBlending || false;
  48252. options.needAlphaTesting = options.needAlphaTesting || false;
  48253. options.attributes = options.attributes || ["position", "normal", "uv"];
  48254. options.uniforms = options.uniforms || ["worldViewProjection"];
  48255. options.uniformBuffers = options.uniformBuffers || [];
  48256. options.samplers = options.samplers || [];
  48257. options.defines = options.defines || [];
  48258. _this._options = options;
  48259. return _this;
  48260. }
  48261. ShaderMaterial.prototype.getClassName = function () {
  48262. return "ShaderMaterial";
  48263. };
  48264. ShaderMaterial.prototype.needAlphaBlending = function () {
  48265. return this._options.needAlphaBlending;
  48266. };
  48267. ShaderMaterial.prototype.needAlphaTesting = function () {
  48268. return this._options.needAlphaTesting;
  48269. };
  48270. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48271. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48272. this._options.uniforms.push(uniformName);
  48273. }
  48274. };
  48275. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48276. if (this._options.samplers.indexOf(name) === -1) {
  48277. this._options.samplers.push(name);
  48278. }
  48279. this._textures[name] = texture;
  48280. return this;
  48281. };
  48282. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48283. if (this._options.samplers.indexOf(name) === -1) {
  48284. this._options.samplers.push(name);
  48285. }
  48286. this._checkUniform(name);
  48287. this._textureArrays[name] = textures;
  48288. return this;
  48289. };
  48290. ShaderMaterial.prototype.setFloat = function (name, value) {
  48291. this._checkUniform(name);
  48292. this._floats[name] = value;
  48293. return this;
  48294. };
  48295. ShaderMaterial.prototype.setInt = function (name, value) {
  48296. this._checkUniform(name);
  48297. this._ints[name] = value;
  48298. return this;
  48299. };
  48300. ShaderMaterial.prototype.setFloats = function (name, value) {
  48301. this._checkUniform(name);
  48302. this._floatsArrays[name] = value;
  48303. return this;
  48304. };
  48305. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48306. this._checkUniform(name);
  48307. this._colors3[name] = value;
  48308. return this;
  48309. };
  48310. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48311. this._checkUniform(name);
  48312. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48313. color.toArray(arr, arr.length);
  48314. return arr;
  48315. }, []);
  48316. return this;
  48317. };
  48318. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48319. this._checkUniform(name);
  48320. this._colors4[name] = value;
  48321. return this;
  48322. };
  48323. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48324. this._checkUniform(name);
  48325. this._vectors2[name] = value;
  48326. return this;
  48327. };
  48328. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48329. this._checkUniform(name);
  48330. this._vectors3[name] = value;
  48331. return this;
  48332. };
  48333. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48334. this._checkUniform(name);
  48335. this._vectors4[name] = value;
  48336. return this;
  48337. };
  48338. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48339. this._checkUniform(name);
  48340. this._matrices[name] = value;
  48341. return this;
  48342. };
  48343. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48344. this._checkUniform(name);
  48345. this._matrices3x3[name] = value;
  48346. return this;
  48347. };
  48348. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48349. this._checkUniform(name);
  48350. this._matrices2x2[name] = value;
  48351. return this;
  48352. };
  48353. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48354. this._checkUniform(name);
  48355. this._vectors2Arrays[name] = value;
  48356. return this;
  48357. };
  48358. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48359. this._checkUniform(name);
  48360. this._vectors3Arrays[name] = value;
  48361. return this;
  48362. };
  48363. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48364. if (!mesh) {
  48365. return true;
  48366. }
  48367. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48368. return false;
  48369. }
  48370. return false;
  48371. };
  48372. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48373. var scene = this.getScene();
  48374. var engine = scene.getEngine();
  48375. if (!this.checkReadyOnEveryCall) {
  48376. if (this._renderId === scene.getRenderId()) {
  48377. if (this._checkCache(scene, mesh, useInstances)) {
  48378. return true;
  48379. }
  48380. }
  48381. }
  48382. // Instances
  48383. var defines = [];
  48384. var attribs = [];
  48385. var fallbacks = new BABYLON.EffectFallbacks();
  48386. if (useInstances) {
  48387. defines.push("#define INSTANCES");
  48388. }
  48389. for (var index = 0; index < this._options.defines.length; index++) {
  48390. defines.push(this._options.defines[index]);
  48391. }
  48392. for (var index = 0; index < this._options.attributes.length; index++) {
  48393. attribs.push(this._options.attributes[index]);
  48394. }
  48395. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48396. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48397. defines.push("#define VERTEXCOLOR");
  48398. }
  48399. // Bones
  48400. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48403. if (mesh.numBoneInfluencers > 4) {
  48404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48406. }
  48407. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48408. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48409. fallbacks.addCPUSkinningFallback(0, mesh);
  48410. if (this._options.uniforms.indexOf("mBones") === -1) {
  48411. this._options.uniforms.push("mBones");
  48412. }
  48413. }
  48414. else {
  48415. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48416. }
  48417. // Textures
  48418. for (var name in this._textures) {
  48419. if (!this._textures[name].isReady()) {
  48420. return false;
  48421. }
  48422. }
  48423. // Alpha test
  48424. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  48425. defines.push("#define ALPHATEST");
  48426. }
  48427. var previousEffect = this._effect;
  48428. var join = defines.join("\n");
  48429. this._effect = engine.createEffect(this._shaderPath, {
  48430. attributes: attribs,
  48431. uniformsNames: this._options.uniforms,
  48432. uniformBuffersNames: this._options.uniformBuffers,
  48433. samplers: this._options.samplers,
  48434. defines: join,
  48435. fallbacks: fallbacks,
  48436. onCompiled: this.onCompiled,
  48437. onError: this.onError
  48438. }, engine);
  48439. if (!this._effect.isReady()) {
  48440. return false;
  48441. }
  48442. if (previousEffect !== this._effect) {
  48443. scene.resetCachedMaterial();
  48444. }
  48445. this._renderId = scene.getRenderId();
  48446. return true;
  48447. };
  48448. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48449. var scene = this.getScene();
  48450. if (!this._effect) {
  48451. return;
  48452. }
  48453. if (this._options.uniforms.indexOf("world") !== -1) {
  48454. this._effect.setMatrix("world", world);
  48455. }
  48456. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48457. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48458. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48459. }
  48460. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48461. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48462. }
  48463. };
  48464. ShaderMaterial.prototype.bind = function (world, mesh) {
  48465. // Std values
  48466. this.bindOnlyWorldMatrix(world);
  48467. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48468. if (this._options.uniforms.indexOf("view") !== -1) {
  48469. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48470. }
  48471. if (this._options.uniforms.indexOf("projection") !== -1) {
  48472. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48473. }
  48474. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48475. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48476. }
  48477. // Bones
  48478. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48479. var name;
  48480. // Texture
  48481. for (name in this._textures) {
  48482. this._effect.setTexture(name, this._textures[name]);
  48483. }
  48484. // Texture arrays
  48485. for (name in this._textureArrays) {
  48486. this._effect.setTextureArray(name, this._textureArrays[name]);
  48487. }
  48488. // Int
  48489. for (name in this._ints) {
  48490. this._effect.setInt(name, this._ints[name]);
  48491. }
  48492. // Float
  48493. for (name in this._floats) {
  48494. this._effect.setFloat(name, this._floats[name]);
  48495. }
  48496. // Floats
  48497. for (name in this._floatsArrays) {
  48498. this._effect.setArray(name, this._floatsArrays[name]);
  48499. }
  48500. // Color3
  48501. for (name in this._colors3) {
  48502. this._effect.setColor3(name, this._colors3[name]);
  48503. }
  48504. for (name in this._colors3Arrays) {
  48505. this._effect.setArray3(name, this._colors3Arrays[name]);
  48506. }
  48507. // Color4
  48508. for (name in this._colors4) {
  48509. var color = this._colors4[name];
  48510. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48511. }
  48512. // Vector2
  48513. for (name in this._vectors2) {
  48514. this._effect.setVector2(name, this._vectors2[name]);
  48515. }
  48516. // Vector3
  48517. for (name in this._vectors3) {
  48518. this._effect.setVector3(name, this._vectors3[name]);
  48519. }
  48520. // Vector4
  48521. for (name in this._vectors4) {
  48522. this._effect.setVector4(name, this._vectors4[name]);
  48523. }
  48524. // Matrix
  48525. for (name in this._matrices) {
  48526. this._effect.setMatrix(name, this._matrices[name]);
  48527. }
  48528. // Matrix 3x3
  48529. for (name in this._matrices3x3) {
  48530. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48531. }
  48532. // Matrix 2x2
  48533. for (name in this._matrices2x2) {
  48534. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48535. }
  48536. // Vector2Array
  48537. for (name in this._vectors2Arrays) {
  48538. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48539. }
  48540. // Vector3Array
  48541. for (name in this._vectors3Arrays) {
  48542. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48543. }
  48544. }
  48545. this._afterBind(mesh);
  48546. };
  48547. ShaderMaterial.prototype.getActiveTextures = function () {
  48548. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48549. for (var name in this._textures) {
  48550. activeTextures.push(this._textures[name]);
  48551. }
  48552. for (var name in this._textureArrays) {
  48553. var array = this._textureArrays[name];
  48554. for (var index = 0; index < array.length; index++) {
  48555. activeTextures.push(array[index]);
  48556. }
  48557. }
  48558. return activeTextures;
  48559. };
  48560. ShaderMaterial.prototype.hasTexture = function (texture) {
  48561. if (_super.prototype.hasTexture.call(this, texture)) {
  48562. return true;
  48563. }
  48564. for (var name in this._textures) {
  48565. if (this._textures[name] === texture) {
  48566. return true;
  48567. }
  48568. }
  48569. for (var name in this._textureArrays) {
  48570. var array = this._textureArrays[name];
  48571. for (var index = 0; index < array.length; index++) {
  48572. if (array[index] === texture) {
  48573. return true;
  48574. }
  48575. }
  48576. }
  48577. return false;
  48578. };
  48579. ShaderMaterial.prototype.clone = function (name) {
  48580. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48581. return newShaderMaterial;
  48582. };
  48583. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48584. if (forceDisposeTextures) {
  48585. var name;
  48586. for (name in this._textures) {
  48587. this._textures[name].dispose();
  48588. }
  48589. for (name in this._textureArrays) {
  48590. var array = this._textureArrays[name];
  48591. for (var index = 0; index < array.length; index++) {
  48592. array[index].dispose();
  48593. }
  48594. }
  48595. }
  48596. this._textures = {};
  48597. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48598. };
  48599. ShaderMaterial.prototype.serialize = function () {
  48600. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48601. serializationObject.customType = "BABYLON.ShaderMaterial";
  48602. serializationObject.options = this._options;
  48603. serializationObject.shaderPath = this._shaderPath;
  48604. var name;
  48605. // Texture
  48606. serializationObject.textures = {};
  48607. for (name in this._textures) {
  48608. serializationObject.textures[name] = this._textures[name].serialize();
  48609. }
  48610. // Texture arrays
  48611. serializationObject.textureArrays = {};
  48612. for (name in this._textureArrays) {
  48613. serializationObject.textureArrays[name] = [];
  48614. var array = this._textureArrays[name];
  48615. for (var index = 0; index < array.length; index++) {
  48616. serializationObject.textureArrays[name].push(array[index].serialize());
  48617. }
  48618. }
  48619. // Float
  48620. serializationObject.floats = {};
  48621. for (name in this._floats) {
  48622. serializationObject.floats[name] = this._floats[name];
  48623. }
  48624. // Float s
  48625. serializationObject.FloatArrays = {};
  48626. for (name in this._floatsArrays) {
  48627. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48628. }
  48629. // Color3
  48630. serializationObject.colors3 = {};
  48631. for (name in this._colors3) {
  48632. serializationObject.colors3[name] = this._colors3[name].asArray();
  48633. }
  48634. // Color3 array
  48635. serializationObject.colors3Arrays = {};
  48636. for (name in this._colors3Arrays) {
  48637. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48638. }
  48639. // Color4
  48640. serializationObject.colors4 = {};
  48641. for (name in this._colors4) {
  48642. serializationObject.colors4[name] = this._colors4[name].asArray();
  48643. }
  48644. // Vector2
  48645. serializationObject.vectors2 = {};
  48646. for (name in this._vectors2) {
  48647. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48648. }
  48649. // Vector3
  48650. serializationObject.vectors3 = {};
  48651. for (name in this._vectors3) {
  48652. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48653. }
  48654. // Vector4
  48655. serializationObject.vectors4 = {};
  48656. for (name in this._vectors4) {
  48657. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48658. }
  48659. // Matrix
  48660. serializationObject.matrices = {};
  48661. for (name in this._matrices) {
  48662. serializationObject.matrices[name] = this._matrices[name].asArray();
  48663. }
  48664. // Matrix 3x3
  48665. serializationObject.matrices3x3 = {};
  48666. for (name in this._matrices3x3) {
  48667. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48668. }
  48669. // Matrix 2x2
  48670. serializationObject.matrices2x2 = {};
  48671. for (name in this._matrices2x2) {
  48672. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48673. }
  48674. // Vector2Array
  48675. serializationObject.vectors2Arrays = {};
  48676. for (name in this._vectors2Arrays) {
  48677. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48678. }
  48679. // Vector3Array
  48680. serializationObject.vectors3Arrays = {};
  48681. for (name in this._vectors3Arrays) {
  48682. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48683. }
  48684. return serializationObject;
  48685. };
  48686. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48687. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48688. var name;
  48689. // Texture
  48690. for (name in source.textures) {
  48691. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48692. }
  48693. // Texture arrays
  48694. for (name in source.textureArrays) {
  48695. var array = source.textureArrays[name];
  48696. var textureArray = new Array();
  48697. for (var index = 0; index < array.length; index++) {
  48698. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48699. }
  48700. material.setTextureArray(name, textureArray);
  48701. }
  48702. // Float
  48703. for (name in source.floats) {
  48704. material.setFloat(name, source.floats[name]);
  48705. }
  48706. // Float s
  48707. for (name in source.floatsArrays) {
  48708. material.setFloats(name, source.floatsArrays[name]);
  48709. }
  48710. // Color3
  48711. for (name in source.colors3) {
  48712. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48713. }
  48714. // Color3 arrays
  48715. for (name in source.colors3Arrays) {
  48716. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48717. if (i % 3 === 0) {
  48718. arr.push([num]);
  48719. }
  48720. else {
  48721. arr[arr.length - 1].push(num);
  48722. }
  48723. return arr;
  48724. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48725. material.setColor3Array(name, colors);
  48726. }
  48727. // Color4
  48728. for (name in source.colors4) {
  48729. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48730. }
  48731. // Vector2
  48732. for (name in source.vectors2) {
  48733. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48734. }
  48735. // Vector3
  48736. for (name in source.vectors3) {
  48737. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48738. }
  48739. // Vector4
  48740. for (name in source.vectors4) {
  48741. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48742. }
  48743. // Matrix
  48744. for (name in source.matrices) {
  48745. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48746. }
  48747. // Matrix 3x3
  48748. for (name in source.matrices3x3) {
  48749. material.setMatrix3x3(name, source.matrices3x3[name]);
  48750. }
  48751. // Matrix 2x2
  48752. for (name in source.matrices2x2) {
  48753. material.setMatrix2x2(name, source.matrices2x2[name]);
  48754. }
  48755. // Vector2Array
  48756. for (name in source.vectors2Arrays) {
  48757. material.setArray2(name, source.vectors2Arrays[name]);
  48758. }
  48759. // Vector3Array
  48760. for (name in source.vectors3Arrays) {
  48761. material.setArray3(name, source.vectors3Arrays[name]);
  48762. }
  48763. return material;
  48764. };
  48765. return ShaderMaterial;
  48766. }(BABYLON.Material));
  48767. BABYLON.ShaderMaterial = ShaderMaterial;
  48768. })(BABYLON || (BABYLON = {}));
  48769. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48770. var BABYLON;
  48771. (function (BABYLON) {
  48772. var GroundMesh = /** @class */ (function (_super) {
  48773. __extends(GroundMesh, _super);
  48774. function GroundMesh(name, scene) {
  48775. var _this = _super.call(this, name, scene) || this;
  48776. _this.generateOctree = false;
  48777. return _this;
  48778. }
  48779. GroundMesh.prototype.getClassName = function () {
  48780. return "GroundMesh";
  48781. };
  48782. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48783. get: function () {
  48784. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48785. },
  48786. enumerable: true,
  48787. configurable: true
  48788. });
  48789. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48790. get: function () {
  48791. return this._subdivisionsX;
  48792. },
  48793. enumerable: true,
  48794. configurable: true
  48795. });
  48796. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48797. get: function () {
  48798. return this._subdivisionsY;
  48799. },
  48800. enumerable: true,
  48801. configurable: true
  48802. });
  48803. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48804. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48805. this._subdivisionsX = chunksCount;
  48806. this._subdivisionsY = chunksCount;
  48807. this.subdivide(chunksCount);
  48808. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48809. };
  48810. /**
  48811. * Returns a height (y) value in the Worl system :
  48812. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48813. * Returns the ground y position if (x, z) are outside the ground surface.
  48814. */
  48815. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48816. var world = this.getWorldMatrix();
  48817. var invMat = BABYLON.Tmp.Matrix[5];
  48818. world.invertToRef(invMat);
  48819. var tmpVect = BABYLON.Tmp.Vector3[8];
  48820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48821. x = tmpVect.x;
  48822. z = tmpVect.z;
  48823. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48824. return this.position.y;
  48825. }
  48826. if (!this._heightQuads || this._heightQuads.length == 0) {
  48827. this._initHeightQuads();
  48828. this._computeHeightQuads();
  48829. }
  48830. var facet = this._getFacetAt(x, z);
  48831. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48832. // return y in the World system
  48833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48834. return tmpVect.y;
  48835. };
  48836. /**
  48837. * Returns a normalized vector (Vector3) orthogonal to the ground
  48838. * at the ground coordinates (x, z) expressed in the World system.
  48839. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48840. */
  48841. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48842. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48843. this.getNormalAtCoordinatesToRef(x, z, normal);
  48844. return normal;
  48845. };
  48846. /**
  48847. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48848. * at the ground coordinates (x, z) expressed in the World system.
  48849. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48850. * Returns the GroundMesh.
  48851. */
  48852. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48853. var world = this.getWorldMatrix();
  48854. var tmpMat = BABYLON.Tmp.Matrix[5];
  48855. world.invertToRef(tmpMat);
  48856. var tmpVect = BABYLON.Tmp.Vector3[8];
  48857. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48858. x = tmpVect.x;
  48859. z = tmpVect.z;
  48860. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48861. return this;
  48862. }
  48863. if (!this._heightQuads || this._heightQuads.length == 0) {
  48864. this._initHeightQuads();
  48865. this._computeHeightQuads();
  48866. }
  48867. var facet = this._getFacetAt(x, z);
  48868. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48869. return this;
  48870. };
  48871. /**
  48872. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48873. * if the ground has been updated.
  48874. * This can be used in the render loop.
  48875. * Returns the GroundMesh.
  48876. */
  48877. GroundMesh.prototype.updateCoordinateHeights = function () {
  48878. if (!this._heightQuads || this._heightQuads.length == 0) {
  48879. this._initHeightQuads();
  48880. }
  48881. this._computeHeightQuads();
  48882. return this;
  48883. };
  48884. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48885. GroundMesh.prototype._getFacetAt = function (x, z) {
  48886. // retrieve col and row from x, z coordinates in the ground local system
  48887. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48888. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48889. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48890. var facet;
  48891. if (z < quad.slope.x * x + quad.slope.y) {
  48892. facet = quad.facet1;
  48893. }
  48894. else {
  48895. facet = quad.facet2;
  48896. }
  48897. return facet;
  48898. };
  48899. // Creates and populates the heightMap array with "facet" elements :
  48900. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48901. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48902. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48903. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48904. // Returns the GroundMesh.
  48905. GroundMesh.prototype._initHeightQuads = function () {
  48906. var subdivisionsX = this._subdivisionsX;
  48907. var subdivisionsY = this._subdivisionsY;
  48908. this._heightQuads = new Array();
  48909. for (var row = 0; row < subdivisionsY; row++) {
  48910. for (var col = 0; col < subdivisionsX; col++) {
  48911. 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) };
  48912. this._heightQuads[row * subdivisionsX + col] = quad;
  48913. }
  48914. }
  48915. return this;
  48916. };
  48917. // Compute each quad element values and update the the heightMap array :
  48918. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48919. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48920. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48921. // Returns the GroundMesh.
  48922. GroundMesh.prototype._computeHeightQuads = function () {
  48923. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48924. if (!positions) {
  48925. return this;
  48926. }
  48927. var v1 = BABYLON.Tmp.Vector3[3];
  48928. var v2 = BABYLON.Tmp.Vector3[2];
  48929. var v3 = BABYLON.Tmp.Vector3[1];
  48930. var v4 = BABYLON.Tmp.Vector3[0];
  48931. var v1v2 = BABYLON.Tmp.Vector3[4];
  48932. var v1v3 = BABYLON.Tmp.Vector3[5];
  48933. var v1v4 = BABYLON.Tmp.Vector3[6];
  48934. var norm1 = BABYLON.Tmp.Vector3[7];
  48935. var norm2 = BABYLON.Tmp.Vector3[8];
  48936. var i = 0;
  48937. var j = 0;
  48938. var k = 0;
  48939. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48940. var h = 0;
  48941. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48942. var d2 = 0;
  48943. var subdivisionsX = this._subdivisionsX;
  48944. var subdivisionsY = this._subdivisionsY;
  48945. for (var row = 0; row < subdivisionsY; row++) {
  48946. for (var col = 0; col < subdivisionsX; col++) {
  48947. i = col * 3;
  48948. j = row * (subdivisionsX + 1) * 3;
  48949. k = (row + 1) * (subdivisionsX + 1) * 3;
  48950. v1.x = positions[j + i];
  48951. v1.y = positions[j + i + 1];
  48952. v1.z = positions[j + i + 2];
  48953. v2.x = positions[j + i + 3];
  48954. v2.y = positions[j + i + 4];
  48955. v2.z = positions[j + i + 5];
  48956. v3.x = positions[k + i];
  48957. v3.y = positions[k + i + 1];
  48958. v3.z = positions[k + i + 2];
  48959. v4.x = positions[k + i + 3];
  48960. v4.y = positions[k + i + 4];
  48961. v4.z = positions[k + i + 5];
  48962. // 2D slope V1V4
  48963. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48964. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48965. // facet equations :
  48966. // we compute each facet normal vector
  48967. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48968. // we compute the value d by applying the equation to v1 which belongs to the plane
  48969. // then we store the facet equation in a Vector4
  48970. v2.subtractToRef(v1, v1v2);
  48971. v3.subtractToRef(v1, v1v3);
  48972. v4.subtractToRef(v1, v1v4);
  48973. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48974. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48975. norm1.normalize();
  48976. norm2.normalize();
  48977. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48978. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48979. var quad = this._heightQuads[row * subdivisionsX + col];
  48980. quad.slope.copyFromFloats(cd, h);
  48981. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48982. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48983. }
  48984. }
  48985. return this;
  48986. };
  48987. GroundMesh.prototype.serialize = function (serializationObject) {
  48988. _super.prototype.serialize.call(this, serializationObject);
  48989. serializationObject.subdivisionsX = this._subdivisionsX;
  48990. serializationObject.subdivisionsY = this._subdivisionsY;
  48991. serializationObject.minX = this._minX;
  48992. serializationObject.maxX = this._maxX;
  48993. serializationObject.minZ = this._minZ;
  48994. serializationObject.maxZ = this._maxZ;
  48995. serializationObject.width = this._width;
  48996. serializationObject.height = this._height;
  48997. };
  48998. GroundMesh.Parse = function (parsedMesh, scene) {
  48999. var result = new GroundMesh(parsedMesh.name, scene);
  49000. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  49001. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  49002. result._minX = parsedMesh.minX;
  49003. result._maxX = parsedMesh.maxX;
  49004. result._minZ = parsedMesh.minZ;
  49005. result._maxZ = parsedMesh.maxZ;
  49006. result._width = parsedMesh.width;
  49007. result._height = parsedMesh.height;
  49008. return result;
  49009. };
  49010. return GroundMesh;
  49011. }(BABYLON.Mesh));
  49012. BABYLON.GroundMesh = GroundMesh;
  49013. })(BABYLON || (BABYLON = {}));
  49014. //# sourceMappingURL=babylon.groundMesh.js.map
  49015. var BABYLON;
  49016. (function (BABYLON) {
  49017. /**
  49018. * Creates an instance based on a source mesh.
  49019. */
  49020. var InstancedMesh = /** @class */ (function (_super) {
  49021. __extends(InstancedMesh, _super);
  49022. function InstancedMesh(name, source) {
  49023. var _this = _super.call(this, name, source.getScene()) || this;
  49024. source.instances.push(_this);
  49025. _this._sourceMesh = source;
  49026. _this.position.copyFrom(source.position);
  49027. _this.rotation.copyFrom(source.rotation);
  49028. _this.scaling.copyFrom(source.scaling);
  49029. if (source.rotationQuaternion) {
  49030. _this.rotationQuaternion = source.rotationQuaternion.clone();
  49031. }
  49032. _this.infiniteDistance = source.infiniteDistance;
  49033. _this.setPivotMatrix(source.getPivotMatrix());
  49034. _this.refreshBoundingInfo();
  49035. _this._syncSubMeshes();
  49036. return _this;
  49037. }
  49038. /**
  49039. * Returns the string "InstancedMesh".
  49040. */
  49041. InstancedMesh.prototype.getClassName = function () {
  49042. return "InstancedMesh";
  49043. };
  49044. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  49045. // Methods
  49046. get: function () {
  49047. return this._sourceMesh.receiveShadows;
  49048. },
  49049. enumerable: true,
  49050. configurable: true
  49051. });
  49052. Object.defineProperty(InstancedMesh.prototype, "material", {
  49053. get: function () {
  49054. return this._sourceMesh.material;
  49055. },
  49056. enumerable: true,
  49057. configurable: true
  49058. });
  49059. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  49060. get: function () {
  49061. return this._sourceMesh.visibility;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  49067. get: function () {
  49068. return this._sourceMesh.skeleton;
  49069. },
  49070. enumerable: true,
  49071. configurable: true
  49072. });
  49073. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  49074. get: function () {
  49075. return this._sourceMesh.renderingGroupId;
  49076. },
  49077. enumerable: true,
  49078. configurable: true
  49079. });
  49080. /**
  49081. * Returns the total number of vertices (integer).
  49082. */
  49083. InstancedMesh.prototype.getTotalVertices = function () {
  49084. return this._sourceMesh.getTotalVertices();
  49085. };
  49086. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  49087. get: function () {
  49088. return this._sourceMesh;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. /**
  49094. * Is this node ready to be used/rendered
  49095. * @return {boolean} is it ready
  49096. */
  49097. InstancedMesh.prototype.isReady = function () {
  49098. return this._sourceMesh.isReady(true);
  49099. };
  49100. /**
  49101. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  49102. */
  49103. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  49104. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  49105. };
  49106. /**
  49107. * Sets the vertex data of the mesh geometry for the requested `kind`.
  49108. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  49109. * The `data` are either a numeric array either a Float32Array.
  49110. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  49111. * 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).
  49112. * Note that a new underlying VertexBuffer object is created each call.
  49113. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  49114. *
  49115. * Possible `kind` values :
  49116. * - BABYLON.VertexBuffer.PositionKind
  49117. * - BABYLON.VertexBuffer.UVKind
  49118. * - BABYLON.VertexBuffer.UV2Kind
  49119. * - BABYLON.VertexBuffer.UV3Kind
  49120. * - BABYLON.VertexBuffer.UV4Kind
  49121. * - BABYLON.VertexBuffer.UV5Kind
  49122. * - BABYLON.VertexBuffer.UV6Kind
  49123. * - BABYLON.VertexBuffer.ColorKind
  49124. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49125. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49126. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49127. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49128. *
  49129. * Returns the Mesh.
  49130. */
  49131. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  49132. if (this.sourceMesh) {
  49133. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  49134. }
  49135. return this.sourceMesh;
  49136. };
  49137. /**
  49138. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  49139. * If the mesh has no geometry, it is simply returned as it is.
  49140. * The `data` are either a numeric array either a Float32Array.
  49141. * No new underlying VertexBuffer object is created.
  49142. * 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.
  49143. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  49144. *
  49145. * Possible `kind` values :
  49146. * - BABYLON.VertexBuffer.PositionKind
  49147. * - BABYLON.VertexBuffer.UVKind
  49148. * - BABYLON.VertexBuffer.UV2Kind
  49149. * - BABYLON.VertexBuffer.UV3Kind
  49150. * - BABYLON.VertexBuffer.UV4Kind
  49151. * - BABYLON.VertexBuffer.UV5Kind
  49152. * - BABYLON.VertexBuffer.UV6Kind
  49153. * - BABYLON.VertexBuffer.ColorKind
  49154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49158. *
  49159. * Returns the Mesh.
  49160. */
  49161. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49162. if (this.sourceMesh) {
  49163. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49164. }
  49165. return this.sourceMesh;
  49166. };
  49167. /**
  49168. * Sets the mesh indices.
  49169. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49170. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49171. * This method creates a new index buffer each call.
  49172. * Returns the Mesh.
  49173. */
  49174. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49175. if (totalVertices === void 0) { totalVertices = null; }
  49176. if (this.sourceMesh) {
  49177. this.sourceMesh.setIndices(indices, totalVertices);
  49178. }
  49179. return this.sourceMesh;
  49180. };
  49181. /**
  49182. * Boolean : True if the mesh owns the requested kind of data.
  49183. */
  49184. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49185. return this._sourceMesh.isVerticesDataPresent(kind);
  49186. };
  49187. /**
  49188. * Returns an array of indices (IndicesArray).
  49189. */
  49190. InstancedMesh.prototype.getIndices = function () {
  49191. return this._sourceMesh.getIndices();
  49192. };
  49193. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49194. get: function () {
  49195. return this._sourceMesh._positions;
  49196. },
  49197. enumerable: true,
  49198. configurable: true
  49199. });
  49200. /**
  49201. * Sets a new updated BoundingInfo to the mesh.
  49202. * Returns the mesh.
  49203. */
  49204. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49205. var meshBB = this._sourceMesh.getBoundingInfo();
  49206. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49207. this._updateBoundingInfo();
  49208. return this;
  49209. };
  49210. InstancedMesh.prototype._preActivate = function () {
  49211. if (this._currentLOD) {
  49212. this._currentLOD._preActivate();
  49213. }
  49214. return this;
  49215. };
  49216. InstancedMesh.prototype._activate = function (renderId) {
  49217. if (this._currentLOD) {
  49218. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49219. }
  49220. return this;
  49221. };
  49222. /**
  49223. * Returns the current associated LOD AbstractMesh.
  49224. */
  49225. InstancedMesh.prototype.getLOD = function (camera) {
  49226. if (!camera) {
  49227. return this;
  49228. }
  49229. var boundingInfo = this.getBoundingInfo();
  49230. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49231. if (this._currentLOD === this.sourceMesh) {
  49232. return this;
  49233. }
  49234. return this._currentLOD;
  49235. };
  49236. InstancedMesh.prototype._syncSubMeshes = function () {
  49237. this.releaseSubMeshes();
  49238. if (this._sourceMesh.subMeshes) {
  49239. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49240. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49241. }
  49242. }
  49243. return this;
  49244. };
  49245. InstancedMesh.prototype._generatePointsArray = function () {
  49246. return this._sourceMesh._generatePointsArray();
  49247. };
  49248. /**
  49249. * Creates a new InstancedMesh from the current mesh.
  49250. * - name (string) : the cloned mesh name
  49251. * - newParent (optional Node) : the optional Node to parent the clone to.
  49252. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49253. *
  49254. * Returns the clone.
  49255. */
  49256. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49257. var result = this._sourceMesh.createInstance(name);
  49258. // Deep copy
  49259. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49260. // Bounding info
  49261. this.refreshBoundingInfo();
  49262. // Parent
  49263. if (newParent) {
  49264. result.parent = newParent;
  49265. }
  49266. if (!doNotCloneChildren) {
  49267. // Children
  49268. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49269. var mesh = this.getScene().meshes[index];
  49270. if (mesh.parent === this) {
  49271. mesh.clone(mesh.name, result);
  49272. }
  49273. }
  49274. }
  49275. result.computeWorldMatrix(true);
  49276. return result;
  49277. };
  49278. /**
  49279. * Disposes the InstancedMesh.
  49280. * Returns nothing.
  49281. */
  49282. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49283. // Remove from mesh
  49284. var index = this._sourceMesh.instances.indexOf(this);
  49285. this._sourceMesh.instances.splice(index, 1);
  49286. _super.prototype.dispose.call(this, doNotRecurse);
  49287. };
  49288. return InstancedMesh;
  49289. }(BABYLON.AbstractMesh));
  49290. BABYLON.InstancedMesh = InstancedMesh;
  49291. })(BABYLON || (BABYLON = {}));
  49292. //# sourceMappingURL=babylon.instancedMesh.js.map
  49293. var BABYLON;
  49294. (function (BABYLON) {
  49295. var LinesMesh = /** @class */ (function (_super) {
  49296. __extends(LinesMesh, _super);
  49297. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49298. if (scene === void 0) { scene = null; }
  49299. if (parent === void 0) { parent = null; }
  49300. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49301. _this.useVertexColor = useVertexColor;
  49302. _this.useVertexAlpha = useVertexAlpha;
  49303. _this.color = new BABYLON.Color3(1, 1, 1);
  49304. _this.alpha = 1;
  49305. if (source) {
  49306. _this.color = source.color.clone();
  49307. _this.alpha = source.alpha;
  49308. _this.useVertexColor = source.useVertexColor;
  49309. _this.useVertexAlpha = source.useVertexAlpha;
  49310. }
  49311. _this._intersectionThreshold = 0.1;
  49312. var defines = [];
  49313. var options = {
  49314. attributes: [BABYLON.VertexBuffer.PositionKind],
  49315. uniforms: ["world", "viewProjection"],
  49316. needAlphaBlending: true,
  49317. defines: defines
  49318. };
  49319. if (useVertexAlpha === false) {
  49320. options.needAlphaBlending = false;
  49321. }
  49322. if (!useVertexColor) {
  49323. options.uniforms.push("color");
  49324. }
  49325. else {
  49326. options.defines.push("#define VERTEXCOLOR");
  49327. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49328. }
  49329. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49330. return _this;
  49331. }
  49332. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49333. /**
  49334. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49335. * This margin is expressed in world space coordinates, so its value may vary.
  49336. * Default value is 0.1
  49337. * @returns the intersection Threshold value.
  49338. */
  49339. get: function () {
  49340. return this._intersectionThreshold;
  49341. },
  49342. /**
  49343. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49344. * This margin is expressed in world space coordinates, so its value may vary.
  49345. * @param value the new threshold to apply
  49346. */
  49347. set: function (value) {
  49348. if (this._intersectionThreshold === value) {
  49349. return;
  49350. }
  49351. this._intersectionThreshold = value;
  49352. if (this.geometry) {
  49353. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49354. }
  49355. },
  49356. enumerable: true,
  49357. configurable: true
  49358. });
  49359. /**
  49360. * Returns the string "LineMesh"
  49361. */
  49362. LinesMesh.prototype.getClassName = function () {
  49363. return "LinesMesh";
  49364. };
  49365. Object.defineProperty(LinesMesh.prototype, "material", {
  49366. get: function () {
  49367. return this._colorShader;
  49368. },
  49369. set: function (value) {
  49370. // Do nothing
  49371. },
  49372. enumerable: true,
  49373. configurable: true
  49374. });
  49375. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49376. get: function () {
  49377. return false;
  49378. },
  49379. enumerable: true,
  49380. configurable: true
  49381. });
  49382. LinesMesh.prototype.createInstance = function (name) {
  49383. throw new Error("LinesMeshes do not support createInstance.");
  49384. };
  49385. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49386. if (!this._geometry) {
  49387. return this;
  49388. }
  49389. // VBOs
  49390. this._geometry._bind(this._colorShader.getEffect());
  49391. // Color
  49392. if (!this.useVertexColor) {
  49393. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49394. }
  49395. return this;
  49396. };
  49397. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49398. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49399. return this;
  49400. }
  49401. var engine = this.getScene().getEngine();
  49402. // Draw order
  49403. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49404. return this;
  49405. };
  49406. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49407. this._colorShader.dispose();
  49408. _super.prototype.dispose.call(this, doNotRecurse);
  49409. };
  49410. /**
  49411. * Returns a new LineMesh object cloned from the current one.
  49412. */
  49413. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49414. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49415. };
  49416. return LinesMesh;
  49417. }(BABYLON.Mesh));
  49418. BABYLON.LinesMesh = LinesMesh;
  49419. })(BABYLON || (BABYLON = {}));
  49420. //# sourceMappingURL=babylon.linesMesh.js.map
  49421. var BABYLON;
  49422. (function (BABYLON) {
  49423. var MeshBuilder = /** @class */ (function () {
  49424. function MeshBuilder() {
  49425. }
  49426. MeshBuilder.updateSideOrientation = function (orientation) {
  49427. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49428. return BABYLON.Mesh.DOUBLESIDE;
  49429. }
  49430. if (orientation === undefined || orientation === null) {
  49431. return BABYLON.Mesh.FRONTSIDE;
  49432. }
  49433. return orientation;
  49434. };
  49435. /**
  49436. * Creates a box mesh.
  49437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49438. * The parameter `size` sets the size (float) of each box side (default 1).
  49439. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49440. * 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).
  49441. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49443. * 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).
  49444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49446. */
  49447. MeshBuilder.CreateBox = function (name, options, scene) {
  49448. if (scene === void 0) { scene = null; }
  49449. var box = new BABYLON.Mesh(name, scene);
  49450. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49451. box._originalBuilderSideOrientation = options.sideOrientation;
  49452. var vertexData = BABYLON.VertexData.CreateBox(options);
  49453. vertexData.applyToMesh(box, options.updatable);
  49454. return box;
  49455. };
  49456. /**
  49457. * Creates a sphere mesh.
  49458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49459. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49460. * 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`).
  49461. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49462. * 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
  49463. * 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).
  49464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49465. * 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).
  49466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49468. */
  49469. MeshBuilder.CreateSphere = function (name, options, scene) {
  49470. var sphere = new BABYLON.Mesh(name, scene);
  49471. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49472. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49473. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49474. vertexData.applyToMesh(sphere, options.updatable);
  49475. return sphere;
  49476. };
  49477. /**
  49478. * Creates a plane polygonal mesh. By default, this is a disc.
  49479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49480. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49481. * 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.
  49482. * 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
  49483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49484. * 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).
  49485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49487. */
  49488. MeshBuilder.CreateDisc = function (name, options, scene) {
  49489. if (scene === void 0) { scene = null; }
  49490. var disc = new BABYLON.Mesh(name, scene);
  49491. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49492. disc._originalBuilderSideOrientation = options.sideOrientation;
  49493. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49494. vertexData.applyToMesh(disc, options.updatable);
  49495. return disc;
  49496. };
  49497. /**
  49498. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49499. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49500. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49501. * 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`).
  49502. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49503. * 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.
  49504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49505. * 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).
  49506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49508. */
  49509. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49510. var sphere = new BABYLON.Mesh(name, scene);
  49511. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49512. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49513. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49514. vertexData.applyToMesh(sphere, options.updatable);
  49515. return sphere;
  49516. };
  49517. ;
  49518. /**
  49519. * Creates a ribbon mesh.
  49520. * 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.
  49521. *
  49522. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49523. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49524. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49525. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49526. * 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.
  49527. * 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.
  49528. * 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
  49529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49530. * 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).
  49531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49532. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49533. * 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.
  49534. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49535. * 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
  49536. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49537. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49538. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49539. */
  49540. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49541. if (scene === void 0) { scene = null; }
  49542. var pathArray = options.pathArray;
  49543. var closeArray = options.closeArray;
  49544. var closePath = options.closePath;
  49545. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49546. var instance = options.instance;
  49547. var updatable = options.updatable;
  49548. if (instance) {
  49549. // positionFunction : ribbon case
  49550. // only pathArray and sideOrientation parameters are taken into account for positions update
  49551. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49552. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49553. var positionFunction = function (positions) {
  49554. var minlg = pathArray[0].length;
  49555. var i = 0;
  49556. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49557. for (var si = 1; si <= ns; si++) {
  49558. for (var p = 0; p < pathArray.length; p++) {
  49559. var path = pathArray[p];
  49560. var l = path.length;
  49561. minlg = (minlg < l) ? minlg : l;
  49562. var j = 0;
  49563. while (j < minlg) {
  49564. positions[i] = path[j].x;
  49565. positions[i + 1] = path[j].y;
  49566. positions[i + 2] = path[j].z;
  49567. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49568. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49569. }
  49570. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49571. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49572. }
  49573. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49574. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49575. }
  49576. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49577. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49578. }
  49579. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49580. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49581. }
  49582. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49583. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49584. }
  49585. j++;
  49586. i += 3;
  49587. }
  49588. if (instance._closePath) {
  49589. positions[i] = path[0].x;
  49590. positions[i + 1] = path[0].y;
  49591. positions[i + 2] = path[0].z;
  49592. i += 3;
  49593. }
  49594. }
  49595. }
  49596. };
  49597. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49598. positionFunction(positions);
  49599. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49600. instance._boundingInfo.update(instance._worldMatrix);
  49601. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49602. if (options.colors) {
  49603. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49604. for (var c = 0; c < options.colors.length; c++) {
  49605. colors[c * 4] = options.colors[c].r;
  49606. colors[c * 4 + 1] = options.colors[c].g;
  49607. colors[c * 4 + 2] = options.colors[c].b;
  49608. colors[c * 4 + 3] = options.colors[c].a;
  49609. }
  49610. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49611. }
  49612. if (options.uvs) {
  49613. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49614. for (var i = 0; i < options.uvs.length; i++) {
  49615. uvs[i * 2] = options.uvs[i].x;
  49616. uvs[i * 2 + 1] = options.uvs[i].y;
  49617. }
  49618. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49619. }
  49620. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49621. var indices = instance.getIndices();
  49622. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49623. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49624. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49625. if (instance._closePath) {
  49626. var indexFirst = 0;
  49627. var indexLast = 0;
  49628. for (var p = 0; p < pathArray.length; p++) {
  49629. indexFirst = instance._idx[p] * 3;
  49630. if (p + 1 < pathArray.length) {
  49631. indexLast = (instance._idx[p + 1] - 1) * 3;
  49632. }
  49633. else {
  49634. indexLast = normals.length - 3;
  49635. }
  49636. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49637. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49638. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49639. normals[indexLast] = normals[indexFirst];
  49640. normals[indexLast + 1] = normals[indexFirst + 1];
  49641. normals[indexLast + 2] = normals[indexFirst + 2];
  49642. }
  49643. }
  49644. if (!(instance.areNormalsFrozen)) {
  49645. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49646. }
  49647. }
  49648. return instance;
  49649. }
  49650. else {
  49651. var ribbon = new BABYLON.Mesh(name, scene);
  49652. ribbon._originalBuilderSideOrientation = sideOrientation;
  49653. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49654. if (closePath) {
  49655. ribbon._idx = vertexData._idx;
  49656. }
  49657. ribbon._closePath = closePath;
  49658. ribbon._closeArray = closeArray;
  49659. vertexData.applyToMesh(ribbon, updatable);
  49660. return ribbon;
  49661. }
  49662. };
  49663. /**
  49664. * Creates a cylinder or a cone mesh.
  49665. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49666. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49667. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49668. * 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.
  49669. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49670. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49671. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49672. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49673. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49674. * 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).
  49675. * 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
  49676. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49677. * 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
  49678. * 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.
  49679. * If `enclose` is false, a ring surface is one element.
  49680. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49681. * 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
  49682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49683. * 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).
  49684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateCylinder = function (name, options, scene) {
  49688. var cylinder = new BABYLON.Mesh(name, scene);
  49689. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49690. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49691. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49692. vertexData.applyToMesh(cylinder, options.updatable);
  49693. return cylinder;
  49694. };
  49695. /**
  49696. * Creates a torus mesh.
  49697. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49698. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49699. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49700. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49701. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49702. * 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).
  49703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49705. */
  49706. MeshBuilder.CreateTorus = function (name, options, scene) {
  49707. var torus = new BABYLON.Mesh(name, scene);
  49708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49709. torus._originalBuilderSideOrientation = options.sideOrientation;
  49710. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49711. vertexData.applyToMesh(torus, options.updatable);
  49712. return torus;
  49713. };
  49714. /**
  49715. * Creates a torus knot mesh.
  49716. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49717. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49718. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49719. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49720. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49722. * 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).
  49723. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49725. */
  49726. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49727. var torusKnot = new BABYLON.Mesh(name, scene);
  49728. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49729. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49730. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49731. vertexData.applyToMesh(torusKnot, options.updatable);
  49732. return torusKnot;
  49733. };
  49734. /**
  49735. * Creates a line system mesh.
  49736. * A line system is a pool of many lines gathered in a single mesh.
  49737. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49738. * 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.
  49739. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49740. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49741. * 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
  49742. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49743. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49744. * 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
  49745. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49747. */
  49748. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49749. var instance = options.instance;
  49750. var lines = options.lines;
  49751. var colors = options.colors;
  49752. if (instance) {
  49753. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49754. var vertexColor;
  49755. var lineColors;
  49756. if (colors) {
  49757. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49758. }
  49759. var i = 0;
  49760. var c = 0;
  49761. for (var l = 0; l < lines.length; l++) {
  49762. var points = lines[l];
  49763. for (var p = 0; p < points.length; p++) {
  49764. positions[i] = points[p].x;
  49765. positions[i + 1] = points[p].y;
  49766. positions[i + 2] = points[p].z;
  49767. if (colors && vertexColor) {
  49768. lineColors = colors[l];
  49769. vertexColor[c] = lineColors[p].r;
  49770. vertexColor[c + 1] = lineColors[p].g;
  49771. vertexColor[c + 2] = lineColors[p].b;
  49772. vertexColor[c + 3] = lineColors[p].a;
  49773. c += 4;
  49774. }
  49775. i += 3;
  49776. }
  49777. }
  49778. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49779. if (colors && vertexColor) {
  49780. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49781. }
  49782. return instance;
  49783. }
  49784. // line system creation
  49785. var useVertexColor = (colors) ? true : false;
  49786. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49787. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49788. vertexData.applyToMesh(lineSystem, options.updatable);
  49789. return lineSystem;
  49790. };
  49791. /**
  49792. * Creates a line mesh.
  49793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49794. * 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.
  49795. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49796. * The parameter `points` is an array successive Vector3.
  49797. * 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
  49798. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49799. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49800. * When updating an instance, remember that only point positions can change, not the number of points.
  49801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49802. */
  49803. MeshBuilder.CreateLines = function (name, options, scene) {
  49804. if (scene === void 0) { scene = null; }
  49805. var colors = (options.colors) ? [options.colors] : null;
  49806. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49807. return lines;
  49808. };
  49809. /**
  49810. * Creates a dashed line mesh.
  49811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49812. * 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.
  49813. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49814. * The parameter `points` is an array successive Vector3.
  49815. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49816. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49817. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49818. * 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
  49819. * When updating an instance, remember that only point positions can change, not the number of points.
  49820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49821. */
  49822. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49823. if (scene === void 0) { scene = null; }
  49824. var points = options.points;
  49825. var instance = options.instance;
  49826. var gapSize = options.gapSize || 1;
  49827. var dashSize = options.dashSize || 3;
  49828. if (instance) {
  49829. var positionFunction = function (positions) {
  49830. var curvect = BABYLON.Vector3.Zero();
  49831. var nbSeg = positions.length / 6;
  49832. var lg = 0;
  49833. var nb = 0;
  49834. var shft = 0;
  49835. var dashshft = 0;
  49836. var curshft = 0;
  49837. var p = 0;
  49838. var i = 0;
  49839. var j = 0;
  49840. for (i = 0; i < points.length - 1; i++) {
  49841. points[i + 1].subtractToRef(points[i], curvect);
  49842. lg += curvect.length();
  49843. }
  49844. shft = lg / nbSeg;
  49845. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49846. for (i = 0; i < points.length - 1; i++) {
  49847. points[i + 1].subtractToRef(points[i], curvect);
  49848. nb = Math.floor(curvect.length() / shft);
  49849. curvect.normalize();
  49850. j = 0;
  49851. while (j < nb && p < positions.length) {
  49852. curshft = shft * j;
  49853. positions[p] = points[i].x + curshft * curvect.x;
  49854. positions[p + 1] = points[i].y + curshft * curvect.y;
  49855. positions[p + 2] = points[i].z + curshft * curvect.z;
  49856. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49857. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49858. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49859. p += 6;
  49860. j++;
  49861. }
  49862. }
  49863. while (p < positions.length) {
  49864. positions[p] = points[i].x;
  49865. positions[p + 1] = points[i].y;
  49866. positions[p + 2] = points[i].z;
  49867. p += 3;
  49868. }
  49869. };
  49870. instance.updateMeshPositions(positionFunction, false);
  49871. return instance;
  49872. }
  49873. // dashed lines creation
  49874. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49875. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49876. vertexData.applyToMesh(dashedLines, options.updatable);
  49877. dashedLines.dashSize = dashSize;
  49878. dashedLines.gapSize = gapSize;
  49879. return dashedLines;
  49880. };
  49881. /**
  49882. * Creates an extruded shape mesh.
  49883. * 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.
  49884. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49885. *
  49886. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49887. * 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
  49888. * extruded along the Z axis.
  49889. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49890. * 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.
  49891. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49892. * 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
  49893. * 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
  49894. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49896. * 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).
  49897. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49898. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49900. */
  49901. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49902. if (scene === void 0) { scene = null; }
  49903. var path = options.path;
  49904. var shape = options.shape;
  49905. var scale = options.scale || 1;
  49906. var rotation = options.rotation || 0;
  49907. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49908. var updatable = options.updatable;
  49909. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49910. var instance = options.instance || null;
  49911. var invertUV = options.invertUV || false;
  49912. 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);
  49913. };
  49914. /**
  49915. * Creates an custom extruded shape mesh.
  49916. * 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.
  49917. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49918. *
  49919. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49920. * 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
  49921. * extruded along the Z axis.
  49922. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49923. * 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
  49924. * and the distance of this point from the begining of the path :
  49925. * ```javascript
  49926. * var rotationFunction = function(i, distance) {
  49927. * // do things
  49928. * return rotationValue; }
  49929. * ```
  49930. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49931. * 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
  49932. * and the distance of this point from the begining of the path :
  49933. * ```javascript
  49934. * var scaleFunction = function(i, distance) {
  49935. * // do things
  49936. * return scaleValue;}
  49937. * ```
  49938. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49939. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49940. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49941. * 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
  49942. * 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
  49943. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49945. * 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).
  49946. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49947. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49949. */
  49950. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49951. var path = options.path;
  49952. var shape = options.shape;
  49953. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49954. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49955. var ribbonCloseArray = options.ribbonCloseArray || false;
  49956. var ribbonClosePath = options.ribbonClosePath || false;
  49957. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49958. var updatable = options.updatable;
  49959. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49960. var instance = options.instance;
  49961. var invertUV = options.invertUV || false;
  49962. 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);
  49963. };
  49964. /**
  49965. * Creates lathe mesh.
  49966. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49967. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49968. *
  49969. * 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
  49970. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49971. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49972. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49973. * 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.
  49974. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49975. * 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
  49976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49977. * 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).
  49978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49979. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49981. */
  49982. MeshBuilder.CreateLathe = function (name, options, scene) {
  49983. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49984. var closed = (options.closed === undefined) ? true : options.closed;
  49985. var shape = options.shape;
  49986. var radius = options.radius || 1;
  49987. var tessellation = options.tessellation || 64;
  49988. var updatable = options.updatable;
  49989. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49990. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49991. var pi2 = Math.PI * 2;
  49992. var paths = new Array();
  49993. var invertUV = options.invertUV || false;
  49994. var i = 0;
  49995. var p = 0;
  49996. var step = pi2 / tessellation * arc;
  49997. var rotated;
  49998. var path = new Array();
  49999. ;
  50000. for (i = 0; i <= tessellation; i++) {
  50001. var path = [];
  50002. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  50003. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  50004. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  50005. }
  50006. for (p = 0; p < shape.length; p++) {
  50007. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  50008. path.push(rotated);
  50009. }
  50010. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  50011. 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));
  50012. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  50013. }
  50014. paths.push(path);
  50015. }
  50016. // lathe ribbon
  50017. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50018. return lathe;
  50019. };
  50020. /**
  50021. * Creates a plane mesh.
  50022. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  50023. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  50024. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  50025. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  50026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  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. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50030. */
  50031. MeshBuilder.CreatePlane = function (name, options, scene) {
  50032. var plane = new BABYLON.Mesh(name, scene);
  50033. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50034. plane._originalBuilderSideOrientation = options.sideOrientation;
  50035. var vertexData = BABYLON.VertexData.CreatePlane(options);
  50036. vertexData.applyToMesh(plane, options.updatable);
  50037. if (options.sourcePlane) {
  50038. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  50039. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  50040. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  50041. plane.rotate(vectorProduct, product);
  50042. }
  50043. return plane;
  50044. };
  50045. /**
  50046. * Creates a ground mesh.
  50047. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  50048. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  50049. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  50050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50051. */
  50052. MeshBuilder.CreateGround = function (name, options, scene) {
  50053. var ground = new BABYLON.GroundMesh(name, scene);
  50054. ground._setReady(false);
  50055. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  50056. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  50057. ground._width = options.width || 1;
  50058. ground._height = options.height || 1;
  50059. ground._maxX = ground._width / 2;
  50060. ground._maxZ = ground._height / 2;
  50061. ground._minX = -ground._maxX;
  50062. ground._minZ = -ground._maxZ;
  50063. var vertexData = BABYLON.VertexData.CreateGround(options);
  50064. vertexData.applyToMesh(ground, options.updatable);
  50065. ground._setReady(true);
  50066. return ground;
  50067. };
  50068. /**
  50069. * Creates a tiled ground mesh.
  50070. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  50071. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  50072. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  50073. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  50074. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  50075. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  50076. * numbers of subdivisions on the ground width and height of each tile.
  50077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50078. */
  50079. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  50080. var tiledGround = new BABYLON.Mesh(name, scene);
  50081. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  50082. vertexData.applyToMesh(tiledGround, options.updatable);
  50083. return tiledGround;
  50084. };
  50085. /**
  50086. * Creates a ground mesh from a height map.
  50087. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  50088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  50089. * The parameter `url` sets the URL of the height map image resource.
  50090. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  50091. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  50092. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  50093. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  50094. * 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.
  50095. * 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).
  50096. * This function is passed the newly built mesh :
  50097. * ```javascript
  50098. * function(mesh) { // do things
  50099. * return; }
  50100. * ```
  50101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50102. */
  50103. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  50104. var width = options.width || 10.0;
  50105. var height = options.height || 10.0;
  50106. var subdivisions = options.subdivisions || 1 | 0;
  50107. var minHeight = options.minHeight || 0.0;
  50108. var maxHeight = options.maxHeight || 1.0;
  50109. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  50110. var updatable = options.updatable;
  50111. var onReady = options.onReady;
  50112. var ground = new BABYLON.GroundMesh(name, scene);
  50113. ground._subdivisionsX = subdivisions;
  50114. ground._subdivisionsY = subdivisions;
  50115. ground._width = width;
  50116. ground._height = height;
  50117. ground._maxX = ground._width / 2.0;
  50118. ground._maxZ = ground._height / 2.0;
  50119. ground._minX = -ground._maxX;
  50120. ground._minZ = -ground._maxZ;
  50121. ground._setReady(false);
  50122. var onload = function (img) {
  50123. // Getting height map data
  50124. var canvas = document.createElement("canvas");
  50125. var context = canvas.getContext("2d");
  50126. if (!context) {
  50127. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  50128. }
  50129. if (scene.isDisposed) {
  50130. return;
  50131. }
  50132. var bufferWidth = img.width;
  50133. var bufferHeight = img.height;
  50134. canvas.width = bufferWidth;
  50135. canvas.height = bufferHeight;
  50136. context.drawImage(img, 0, 0);
  50137. // Create VertexData from map data
  50138. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  50139. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  50140. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  50141. width: width, height: height,
  50142. subdivisions: subdivisions,
  50143. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  50144. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  50145. });
  50146. vertexData.applyToMesh(ground, updatable);
  50147. ground._setReady(true);
  50148. //execute ready callback, if set
  50149. if (onReady) {
  50150. onReady(ground);
  50151. }
  50152. };
  50153. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50154. return ground;
  50155. };
  50156. /**
  50157. * Creates a polygon mesh.
  50158. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50159. * 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.
  50160. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50162. * 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).
  50163. * Remember you can only change the shape positions, not their number when updating a polygon.
  50164. */
  50165. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50166. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50167. var shape = options.shape;
  50168. var holes = options.holes || [];
  50169. var depth = options.depth || 0;
  50170. var contours = [];
  50171. var hole = [];
  50172. for (var i = 0; i < shape.length; i++) {
  50173. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50174. }
  50175. var epsilon = 0.00000001;
  50176. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50177. contours.pop();
  50178. }
  50179. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50180. for (var hNb = 0; hNb < holes.length; hNb++) {
  50181. hole = [];
  50182. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50183. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50184. }
  50185. polygonTriangulation.addHole(hole);
  50186. }
  50187. var polygon = polygonTriangulation.build(options.updatable, depth);
  50188. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50189. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50190. vertexData.applyToMesh(polygon, options.updatable);
  50191. return polygon;
  50192. };
  50193. ;
  50194. /**
  50195. * Creates an extruded polygon mesh, with depth in the Y direction.
  50196. * 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).
  50197. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50198. */
  50199. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50200. return MeshBuilder.CreatePolygon(name, options, scene);
  50201. };
  50202. ;
  50203. /**
  50204. * Creates a tube mesh.
  50205. * 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.
  50206. *
  50207. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50208. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50209. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50210. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50211. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50212. * 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.
  50213. * It must return a radius value (positive float) :
  50214. * ```javascript
  50215. * var radiusFunction = function(i, distance) {
  50216. * // do things
  50217. * return radius; }
  50218. * ```
  50219. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50220. * 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
  50221. * 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
  50222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50223. * 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).
  50224. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50225. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50227. */
  50228. MeshBuilder.CreateTube = function (name, options, scene) {
  50229. var path = options.path;
  50230. var instance = options.instance;
  50231. var radius = 1.0;
  50232. if (instance) {
  50233. radius = instance.radius;
  50234. }
  50235. if (options.radius !== undefined) {
  50236. radius = options.radius;
  50237. }
  50238. ;
  50239. var tessellation = options.tessellation || 64 | 0;
  50240. var radiusFunction = options.radiusFunction || null;
  50241. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50242. var invertUV = options.invertUV || false;
  50243. var updatable = options.updatable;
  50244. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50245. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50246. // tube geometry
  50247. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50248. var tangents = path3D.getTangents();
  50249. var normals = path3D.getNormals();
  50250. var distances = path3D.getDistances();
  50251. var pi2 = Math.PI * 2;
  50252. var step = pi2 / tessellation * arc;
  50253. var returnRadius = function () { return radius; };
  50254. var radiusFunctionFinal = radiusFunction || returnRadius;
  50255. var circlePath;
  50256. var rad;
  50257. var normal;
  50258. var rotated;
  50259. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50260. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50261. for (var i = 0; i < path.length; i++) {
  50262. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50263. circlePath = Array(); // current circle array
  50264. normal = normals[i]; // current normal
  50265. for (var t = 0; t < tessellation; t++) {
  50266. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50267. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50268. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50269. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50270. circlePath[t] = rotated;
  50271. }
  50272. circlePaths[index] = circlePath;
  50273. index++;
  50274. }
  50275. // cap
  50276. var capPath = function (nbPoints, pathIndex) {
  50277. var pointCap = Array();
  50278. for (var i = 0; i < nbPoints; i++) {
  50279. pointCap.push(path[pathIndex]);
  50280. }
  50281. return pointCap;
  50282. };
  50283. switch (cap) {
  50284. case BABYLON.Mesh.NO_CAP:
  50285. break;
  50286. case BABYLON.Mesh.CAP_START:
  50287. circlePaths[0] = capPath(tessellation, 0);
  50288. circlePaths[1] = circlePaths[2].slice(0);
  50289. break;
  50290. case BABYLON.Mesh.CAP_END:
  50291. circlePaths[index] = circlePaths[index - 1].slice(0);
  50292. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50293. break;
  50294. case BABYLON.Mesh.CAP_ALL:
  50295. circlePaths[0] = capPath(tessellation, 0);
  50296. circlePaths[1] = circlePaths[2].slice(0);
  50297. circlePaths[index] = circlePaths[index - 1].slice(0);
  50298. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50299. break;
  50300. default:
  50301. break;
  50302. }
  50303. return circlePaths;
  50304. };
  50305. var path3D;
  50306. var pathArray;
  50307. if (instance) {
  50308. var arc = options.arc || instance.arc;
  50309. path3D = (instance.path3D).update(path);
  50310. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50311. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50312. instance.path3D = path3D;
  50313. instance.pathArray = pathArray;
  50314. instance.arc = arc;
  50315. instance.radius = radius;
  50316. return instance;
  50317. }
  50318. // tube creation
  50319. path3D = new BABYLON.Path3D(path);
  50320. var newPathArray = new Array();
  50321. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50322. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50323. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50324. tube.pathArray = pathArray;
  50325. tube.path3D = path3D;
  50326. tube.tessellation = tessellation;
  50327. tube.cap = cap;
  50328. tube.arc = options.arc;
  50329. tube.radius = radius;
  50330. return tube;
  50331. };
  50332. /**
  50333. * Creates a polyhedron mesh.
  50334. *
  50335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50336. * 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
  50337. * to choose the wanted type.
  50338. * The parameter `size` (positive float, default 1) sets the polygon size.
  50339. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50340. * 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`.
  50341. * 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
  50342. * 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)`).
  50343. * 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
  50344. * 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.
  50345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50346. * 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).
  50347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50349. */
  50350. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50351. var polyhedron = new BABYLON.Mesh(name, scene);
  50352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50353. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50354. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50355. vertexData.applyToMesh(polyhedron, options.updatable);
  50356. return polyhedron;
  50357. };
  50358. /**
  50359. * Creates a decal mesh.
  50360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50361. * 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.
  50362. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50363. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50364. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50365. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50366. */
  50367. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50368. var indices = sourceMesh.getIndices();
  50369. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50370. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50371. var position = options.position || BABYLON.Vector3.Zero();
  50372. var normal = options.normal || BABYLON.Vector3.Up();
  50373. var size = options.size || BABYLON.Vector3.One();
  50374. var angle = options.angle || 0;
  50375. // Getting correct rotation
  50376. if (!normal) {
  50377. var target = new BABYLON.Vector3(0, 0, 1);
  50378. var camera = sourceMesh.getScene().activeCamera;
  50379. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50380. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50381. }
  50382. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50383. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50384. var pitch = Math.atan2(normal.y, len);
  50385. // Matrix
  50386. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50387. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50388. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50389. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50390. var vertexData = new BABYLON.VertexData();
  50391. vertexData.indices = [];
  50392. vertexData.positions = [];
  50393. vertexData.normals = [];
  50394. vertexData.uvs = [];
  50395. var currentVertexDataIndex = 0;
  50396. var extractDecalVector3 = function (indexId) {
  50397. var result = new BABYLON.PositionNormalVertex();
  50398. if (!indices || !positions || !normals) {
  50399. return result;
  50400. }
  50401. var vertexId = indices[indexId];
  50402. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50403. // Send vector to decal local world
  50404. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50405. // Get normal
  50406. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50407. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50408. return result;
  50409. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50410. var clip = function (vertices, axis) {
  50411. if (vertices.length === 0) {
  50412. return vertices;
  50413. }
  50414. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50415. var clipVertices = function (v0, v1) {
  50416. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50417. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50418. };
  50419. var result = new Array();
  50420. for (var index = 0; index < vertices.length; index += 3) {
  50421. var v1Out;
  50422. var v2Out;
  50423. var v3Out;
  50424. var total = 0;
  50425. var nV1 = null;
  50426. var nV2 = null;
  50427. var nV3 = null;
  50428. var nV4 = null;
  50429. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50430. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50431. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50432. v1Out = d1 > 0;
  50433. v2Out = d2 > 0;
  50434. v3Out = d3 > 0;
  50435. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50436. switch (total) {
  50437. case 0:
  50438. result.push(vertices[index]);
  50439. result.push(vertices[index + 1]);
  50440. result.push(vertices[index + 2]);
  50441. break;
  50442. case 1:
  50443. if (v1Out) {
  50444. nV1 = vertices[index + 1];
  50445. nV2 = vertices[index + 2];
  50446. nV3 = clipVertices(vertices[index], nV1);
  50447. nV4 = clipVertices(vertices[index], nV2);
  50448. }
  50449. if (v2Out) {
  50450. nV1 = vertices[index];
  50451. nV2 = vertices[index + 2];
  50452. nV3 = clipVertices(vertices[index + 1], nV1);
  50453. nV4 = clipVertices(vertices[index + 1], nV2);
  50454. result.push(nV3);
  50455. result.push(nV2.clone());
  50456. result.push(nV1.clone());
  50457. result.push(nV2.clone());
  50458. result.push(nV3.clone());
  50459. result.push(nV4);
  50460. break;
  50461. }
  50462. if (v3Out) {
  50463. nV1 = vertices[index];
  50464. nV2 = vertices[index + 1];
  50465. nV3 = clipVertices(vertices[index + 2], nV1);
  50466. nV4 = clipVertices(vertices[index + 2], nV2);
  50467. }
  50468. if (nV1 && nV2 && nV3 && nV4) {
  50469. result.push(nV1.clone());
  50470. result.push(nV2.clone());
  50471. result.push(nV3);
  50472. result.push(nV4);
  50473. result.push(nV3.clone());
  50474. result.push(nV2.clone());
  50475. }
  50476. break;
  50477. case 2:
  50478. if (!v1Out) {
  50479. nV1 = vertices[index].clone();
  50480. nV2 = clipVertices(nV1, vertices[index + 1]);
  50481. nV3 = clipVertices(nV1, vertices[index + 2]);
  50482. result.push(nV1);
  50483. result.push(nV2);
  50484. result.push(nV3);
  50485. }
  50486. if (!v2Out) {
  50487. nV1 = vertices[index + 1].clone();
  50488. nV2 = clipVertices(nV1, vertices[index + 2]);
  50489. nV3 = clipVertices(nV1, vertices[index]);
  50490. result.push(nV1);
  50491. result.push(nV2);
  50492. result.push(nV3);
  50493. }
  50494. if (!v3Out) {
  50495. nV1 = vertices[index + 2].clone();
  50496. nV2 = clipVertices(nV1, vertices[index]);
  50497. nV3 = clipVertices(nV1, vertices[index + 1]);
  50498. result.push(nV1);
  50499. result.push(nV2);
  50500. result.push(nV3);
  50501. }
  50502. break;
  50503. case 3:
  50504. break;
  50505. }
  50506. }
  50507. return result;
  50508. };
  50509. for (var index = 0; index < indices.length; index += 3) {
  50510. var faceVertices = new Array();
  50511. faceVertices.push(extractDecalVector3(index));
  50512. faceVertices.push(extractDecalVector3(index + 1));
  50513. faceVertices.push(extractDecalVector3(index + 2));
  50514. // Clip
  50515. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50516. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50517. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50518. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50519. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50520. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50521. if (faceVertices.length === 0) {
  50522. continue;
  50523. }
  50524. // Add UVs and get back to world
  50525. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50526. var vertex = faceVertices[vIndex];
  50527. //TODO check for Int32Array | Uint32Array | Uint16Array
  50528. vertexData.indices.push(currentVertexDataIndex);
  50529. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50530. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50531. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50532. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50533. currentVertexDataIndex++;
  50534. }
  50535. }
  50536. // Return mesh
  50537. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50538. vertexData.applyToMesh(decal);
  50539. decal.position = position.clone();
  50540. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50541. return decal;
  50542. };
  50543. // Privates
  50544. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50545. // extrusion geometry
  50546. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50547. var tangents = path3D.getTangents();
  50548. var normals = path3D.getNormals();
  50549. var binormals = path3D.getBinormals();
  50550. var distances = path3D.getDistances();
  50551. var angle = 0;
  50552. var returnScale = function () { return scale !== null ? scale : 1; };
  50553. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50554. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50555. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50556. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50557. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50558. for (var i = 0; i < curve.length; i++) {
  50559. var shapePath = new Array();
  50560. var angleStep = rotate(i, distances[i]);
  50561. var scaleRatio = scl(i, distances[i]);
  50562. for (var p = 0; p < shape.length; p++) {
  50563. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50564. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50565. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50566. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50567. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50568. shapePath[p] = rotated;
  50569. }
  50570. shapePaths[index] = shapePath;
  50571. angle += angleStep;
  50572. index++;
  50573. }
  50574. // cap
  50575. var capPath = function (shapePath) {
  50576. var pointCap = Array();
  50577. var barycenter = BABYLON.Vector3.Zero();
  50578. var i;
  50579. for (i = 0; i < shapePath.length; i++) {
  50580. barycenter.addInPlace(shapePath[i]);
  50581. }
  50582. barycenter.scaleInPlace(1.0 / shapePath.length);
  50583. for (i = 0; i < shapePath.length; i++) {
  50584. pointCap.push(barycenter);
  50585. }
  50586. return pointCap;
  50587. };
  50588. switch (cap) {
  50589. case BABYLON.Mesh.NO_CAP:
  50590. break;
  50591. case BABYLON.Mesh.CAP_START:
  50592. shapePaths[0] = capPath(shapePaths[2]);
  50593. shapePaths[1] = shapePaths[2];
  50594. break;
  50595. case BABYLON.Mesh.CAP_END:
  50596. shapePaths[index] = shapePaths[index - 1];
  50597. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50598. break;
  50599. case BABYLON.Mesh.CAP_ALL:
  50600. shapePaths[0] = capPath(shapePaths[2]);
  50601. shapePaths[1] = shapePaths[2];
  50602. shapePaths[index] = shapePaths[index - 1];
  50603. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50604. break;
  50605. default:
  50606. break;
  50607. }
  50608. return shapePaths;
  50609. };
  50610. var path3D;
  50611. var pathArray;
  50612. if (instance) {
  50613. path3D = (instance.path3D).update(curve);
  50614. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50615. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50616. return instance;
  50617. }
  50618. // extruded shape creation
  50619. path3D = new BABYLON.Path3D(curve);
  50620. var newShapePaths = new Array();
  50621. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50622. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50623. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50624. extrudedGeneric.pathArray = pathArray;
  50625. extrudedGeneric.path3D = path3D;
  50626. extrudedGeneric.cap = cap;
  50627. return extrudedGeneric;
  50628. };
  50629. return MeshBuilder;
  50630. }());
  50631. BABYLON.MeshBuilder = MeshBuilder;
  50632. })(BABYLON || (BABYLON = {}));
  50633. //# sourceMappingURL=babylon.meshBuilder.js.map
  50634. var BABYLON;
  50635. (function (BABYLON) {
  50636. var AudioEngine = /** @class */ (function () {
  50637. function AudioEngine() {
  50638. this._audioContext = null;
  50639. this._audioContextInitialized = false;
  50640. this.canUseWebAudio = false;
  50641. this.WarnedWebAudioUnsupported = false;
  50642. this.unlocked = false;
  50643. this.isMP3supported = false;
  50644. this.isOGGsupported = false;
  50645. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50646. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50647. this.canUseWebAudio = true;
  50648. }
  50649. var audioElem = document.createElement('audio');
  50650. try {
  50651. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50652. this.isMP3supported = true;
  50653. }
  50654. }
  50655. catch (e) {
  50656. // protect error during capability check.
  50657. }
  50658. try {
  50659. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50660. this.isOGGsupported = true;
  50661. }
  50662. }
  50663. catch (e) {
  50664. // protect error during capability check.
  50665. }
  50666. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50667. this._unlockiOSaudio();
  50668. }
  50669. else {
  50670. this.unlocked = true;
  50671. }
  50672. }
  50673. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50674. get: function () {
  50675. if (!this._audioContextInitialized) {
  50676. this._initializeAudioContext();
  50677. }
  50678. return this._audioContext;
  50679. },
  50680. enumerable: true,
  50681. configurable: true
  50682. });
  50683. AudioEngine.prototype._unlockiOSaudio = function () {
  50684. var _this = this;
  50685. var unlockaudio = function () {
  50686. if (!_this.audioContext) {
  50687. return;
  50688. }
  50689. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50690. var source = _this.audioContext.createBufferSource();
  50691. source.buffer = buffer;
  50692. source.connect(_this.audioContext.destination);
  50693. source.start(0);
  50694. setTimeout(function () {
  50695. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50696. _this.unlocked = true;
  50697. window.removeEventListener('touchend', unlockaudio, false);
  50698. if (_this.onAudioUnlocked) {
  50699. _this.onAudioUnlocked();
  50700. }
  50701. }
  50702. }, 0);
  50703. };
  50704. window.addEventListener('touchend', unlockaudio, false);
  50705. };
  50706. AudioEngine.prototype._initializeAudioContext = function () {
  50707. try {
  50708. if (this.canUseWebAudio) {
  50709. this._audioContext = new AudioContext();
  50710. // create a global volume gain node
  50711. this.masterGain = this._audioContext.createGain();
  50712. this.masterGain.gain.value = 1;
  50713. this.masterGain.connect(this._audioContext.destination);
  50714. this._audioContextInitialized = true;
  50715. }
  50716. }
  50717. catch (e) {
  50718. this.canUseWebAudio = false;
  50719. BABYLON.Tools.Error("Web Audio: " + e.message);
  50720. }
  50721. };
  50722. AudioEngine.prototype.dispose = function () {
  50723. if (this.canUseWebAudio && this._audioContextInitialized) {
  50724. if (this._connectedAnalyser && this._audioContext) {
  50725. this._connectedAnalyser.stopDebugCanvas();
  50726. this._connectedAnalyser.dispose();
  50727. this.masterGain.disconnect();
  50728. this.masterGain.connect(this._audioContext.destination);
  50729. this._connectedAnalyser = null;
  50730. }
  50731. this.masterGain.gain.value = 1;
  50732. }
  50733. this.WarnedWebAudioUnsupported = false;
  50734. };
  50735. AudioEngine.prototype.getGlobalVolume = function () {
  50736. if (this.canUseWebAudio && this._audioContextInitialized) {
  50737. return this.masterGain.gain.value;
  50738. }
  50739. else {
  50740. return -1;
  50741. }
  50742. };
  50743. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50744. if (this.canUseWebAudio && this._audioContextInitialized) {
  50745. this.masterGain.gain.value = newVolume;
  50746. }
  50747. };
  50748. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50749. if (this._connectedAnalyser) {
  50750. this._connectedAnalyser.stopDebugCanvas();
  50751. }
  50752. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50753. this._connectedAnalyser = analyser;
  50754. this.masterGain.disconnect();
  50755. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50756. }
  50757. };
  50758. return AudioEngine;
  50759. }());
  50760. BABYLON.AudioEngine = AudioEngine;
  50761. })(BABYLON || (BABYLON = {}));
  50762. //# sourceMappingURL=babylon.audioEngine.js.map
  50763. var BABYLON;
  50764. (function (BABYLON) {
  50765. var Sound = /** @class */ (function () {
  50766. /**
  50767. * Create a sound and attach it to a scene
  50768. * @param name Name of your sound
  50769. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50770. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50771. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50772. */
  50773. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50774. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50775. var _this = this;
  50776. this.autoplay = false;
  50777. this.loop = false;
  50778. this.useCustomAttenuation = false;
  50779. this.spatialSound = false;
  50780. this.refDistance = 1;
  50781. this.rolloffFactor = 1;
  50782. this.maxDistance = 100;
  50783. this.distanceModel = "linear";
  50784. this._panningModel = "equalpower";
  50785. this._playbackRate = 1;
  50786. this._streaming = false;
  50787. this._startTime = 0;
  50788. this._startOffset = 0;
  50789. this._position = BABYLON.Vector3.Zero();
  50790. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50791. this._volume = 1;
  50792. this._isReadyToPlay = false;
  50793. this.isPlaying = false;
  50794. this.isPaused = false;
  50795. this._isDirectional = false;
  50796. // Used if you'd like to create a directional sound.
  50797. // If not set, the sound will be omnidirectional
  50798. this._coneInnerAngle = 360;
  50799. this._coneOuterAngle = 360;
  50800. this._coneOuterGain = 0;
  50801. this._isOutputConnected = false;
  50802. this._urlType = "Unknown";
  50803. this.name = name;
  50804. this._scene = scene;
  50805. this._readyToPlayCallback = readyToPlayCallback;
  50806. // Default custom attenuation function is a linear attenuation
  50807. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50808. if (currentDistance < maxDistance) {
  50809. return currentVolume * (1 - currentDistance / maxDistance);
  50810. }
  50811. else {
  50812. return 0;
  50813. }
  50814. };
  50815. if (options) {
  50816. this.autoplay = options.autoplay || false;
  50817. this.loop = options.loop || false;
  50818. // if volume === 0, we need another way to check this option
  50819. if (options.volume !== undefined) {
  50820. this._volume = options.volume;
  50821. }
  50822. this.spatialSound = options.spatialSound || false;
  50823. this.maxDistance = options.maxDistance || 100;
  50824. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50825. this.rolloffFactor = options.rolloffFactor || 1;
  50826. this.refDistance = options.refDistance || 1;
  50827. this.distanceModel = options.distanceModel || "linear";
  50828. this._playbackRate = options.playbackRate || 1;
  50829. this._streaming = options.streaming || false;
  50830. }
  50831. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50832. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50833. this._soundGain.gain.value = this._volume;
  50834. this._inputAudioNode = this._soundGain;
  50835. this._ouputAudioNode = this._soundGain;
  50836. if (this.spatialSound) {
  50837. this._createSpatialParameters();
  50838. }
  50839. this._scene.mainSoundTrack.AddSound(this);
  50840. var validParameter = true;
  50841. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50842. if (urlOrArrayBuffer) {
  50843. if (typeof (urlOrArrayBuffer) === "string")
  50844. this._urlType = "String";
  50845. if (Array.isArray(urlOrArrayBuffer))
  50846. this._urlType = "Array";
  50847. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50848. this._urlType = "ArrayBuffer";
  50849. var urls = [];
  50850. var codecSupportedFound = false;
  50851. switch (this._urlType) {
  50852. case "ArrayBuffer":
  50853. if (urlOrArrayBuffer.byteLength > 0) {
  50854. codecSupportedFound = true;
  50855. this._soundLoaded(urlOrArrayBuffer);
  50856. }
  50857. break;
  50858. case "String":
  50859. urls.push(urlOrArrayBuffer);
  50860. case "Array":
  50861. if (urls.length === 0)
  50862. urls = urlOrArrayBuffer;
  50863. // If we found a supported format, we load it immediately and stop the loop
  50864. for (var i = 0; i < urls.length; i++) {
  50865. var url = urls[i];
  50866. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50867. codecSupportedFound = true;
  50868. }
  50869. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50870. codecSupportedFound = true;
  50871. }
  50872. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50873. codecSupportedFound = true;
  50874. }
  50875. if (url.indexOf("blob:") !== -1) {
  50876. codecSupportedFound = true;
  50877. }
  50878. if (codecSupportedFound) {
  50879. // Loading sound using XHR2
  50880. if (!this._streaming) {
  50881. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50882. }
  50883. else {
  50884. this._htmlAudioElement = new Audio(url);
  50885. this._htmlAudioElement.controls = false;
  50886. this._htmlAudioElement.loop = this.loop;
  50887. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50888. this._htmlAudioElement.preload = "auto";
  50889. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50890. _this._isReadyToPlay = true;
  50891. if (_this.autoplay) {
  50892. _this.play();
  50893. }
  50894. if (_this._readyToPlayCallback) {
  50895. _this._readyToPlayCallback();
  50896. }
  50897. });
  50898. document.body.appendChild(this._htmlAudioElement);
  50899. }
  50900. break;
  50901. }
  50902. }
  50903. break;
  50904. default:
  50905. validParameter = false;
  50906. break;
  50907. }
  50908. if (!validParameter) {
  50909. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50910. }
  50911. else {
  50912. if (!codecSupportedFound) {
  50913. this._isReadyToPlay = true;
  50914. // Simulating a ready to play event to avoid breaking code path
  50915. if (this._readyToPlayCallback) {
  50916. window.setTimeout(function () {
  50917. if (_this._readyToPlayCallback) {
  50918. _this._readyToPlayCallback();
  50919. }
  50920. }, 1000);
  50921. }
  50922. }
  50923. }
  50924. }
  50925. }
  50926. else {
  50927. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50928. this._scene.mainSoundTrack.AddSound(this);
  50929. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50930. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50931. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50932. }
  50933. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50934. if (this._readyToPlayCallback) {
  50935. window.setTimeout(function () {
  50936. if (_this._readyToPlayCallback) {
  50937. _this._readyToPlayCallback();
  50938. }
  50939. }, 1000);
  50940. }
  50941. }
  50942. }
  50943. Sound.prototype.dispose = function () {
  50944. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50945. if (this.isPlaying) {
  50946. this.stop();
  50947. }
  50948. this._isReadyToPlay = false;
  50949. if (this.soundTrackId === -1) {
  50950. this._scene.mainSoundTrack.RemoveSound(this);
  50951. }
  50952. else {
  50953. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50954. }
  50955. if (this._soundGain) {
  50956. this._soundGain.disconnect();
  50957. this._soundGain = null;
  50958. }
  50959. if (this._soundPanner) {
  50960. this._soundPanner.disconnect();
  50961. this._soundPanner = null;
  50962. }
  50963. if (this._soundSource) {
  50964. this._soundSource.disconnect();
  50965. this._soundSource = null;
  50966. }
  50967. this._audioBuffer = null;
  50968. if (this._htmlAudioElement) {
  50969. this._htmlAudioElement.pause();
  50970. this._htmlAudioElement.src = "";
  50971. document.body.removeChild(this._htmlAudioElement);
  50972. }
  50973. if (this._connectedMesh && this._registerFunc) {
  50974. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50975. this._connectedMesh = null;
  50976. }
  50977. }
  50978. };
  50979. Sound.prototype.isReady = function () {
  50980. return this._isReadyToPlay;
  50981. };
  50982. Sound.prototype._soundLoaded = function (audioData) {
  50983. var _this = this;
  50984. if (!BABYLON.Engine.audioEngine.audioContext) {
  50985. return;
  50986. }
  50987. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50988. _this._audioBuffer = buffer;
  50989. _this._isReadyToPlay = true;
  50990. if (_this.autoplay) {
  50991. _this.play();
  50992. }
  50993. if (_this._readyToPlayCallback) {
  50994. _this._readyToPlayCallback();
  50995. }
  50996. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50997. };
  50998. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50999. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51000. this._audioBuffer = audioBuffer;
  51001. this._isReadyToPlay = true;
  51002. }
  51003. };
  51004. Sound.prototype.updateOptions = function (options) {
  51005. if (options) {
  51006. this.loop = options.loop || this.loop;
  51007. this.maxDistance = options.maxDistance || this.maxDistance;
  51008. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  51009. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  51010. this.refDistance = options.refDistance || this.refDistance;
  51011. this.distanceModel = options.distanceModel || this.distanceModel;
  51012. this._playbackRate = options.playbackRate || this._playbackRate;
  51013. this._updateSpatialParameters();
  51014. if (this.isPlaying) {
  51015. if (this._streaming) {
  51016. this._htmlAudioElement.playbackRate = this._playbackRate;
  51017. }
  51018. else {
  51019. if (this._soundSource) {
  51020. this._soundSource.playbackRate.value = this._playbackRate;
  51021. }
  51022. }
  51023. }
  51024. }
  51025. };
  51026. Sound.prototype._createSpatialParameters = function () {
  51027. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51028. if (this._scene.headphone) {
  51029. this._panningModel = "HRTF";
  51030. }
  51031. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  51032. this._updateSpatialParameters();
  51033. this._soundPanner.connect(this._ouputAudioNode);
  51034. this._inputAudioNode = this._soundPanner;
  51035. }
  51036. };
  51037. Sound.prototype._updateSpatialParameters = function () {
  51038. if (this.spatialSound && this._soundPanner) {
  51039. if (this.useCustomAttenuation) {
  51040. // Tricks to disable in a way embedded Web Audio attenuation
  51041. this._soundPanner.distanceModel = "linear";
  51042. this._soundPanner.maxDistance = Number.MAX_VALUE;
  51043. this._soundPanner.refDistance = 1;
  51044. this._soundPanner.rolloffFactor = 1;
  51045. this._soundPanner.panningModel = this._panningModel;
  51046. }
  51047. else {
  51048. this._soundPanner.distanceModel = this.distanceModel;
  51049. this._soundPanner.maxDistance = this.maxDistance;
  51050. this._soundPanner.refDistance = this.refDistance;
  51051. this._soundPanner.rolloffFactor = this.rolloffFactor;
  51052. this._soundPanner.panningModel = this._panningModel;
  51053. }
  51054. }
  51055. };
  51056. Sound.prototype.switchPanningModelToHRTF = function () {
  51057. this._panningModel = "HRTF";
  51058. this._switchPanningModel();
  51059. };
  51060. Sound.prototype.switchPanningModelToEqualPower = function () {
  51061. this._panningModel = "equalpower";
  51062. this._switchPanningModel();
  51063. };
  51064. Sound.prototype._switchPanningModel = function () {
  51065. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  51066. this._soundPanner.panningModel = this._panningModel;
  51067. }
  51068. };
  51069. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  51070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51071. if (this._isOutputConnected) {
  51072. this._ouputAudioNode.disconnect();
  51073. }
  51074. this._ouputAudioNode.connect(soundTrackAudioNode);
  51075. this._isOutputConnected = true;
  51076. }
  51077. };
  51078. /**
  51079. * Transform this sound into a directional source
  51080. * @param coneInnerAngle Size of the inner cone in degree
  51081. * @param coneOuterAngle Size of the outer cone in degree
  51082. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  51083. */
  51084. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  51085. if (coneOuterAngle < coneInnerAngle) {
  51086. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  51087. return;
  51088. }
  51089. this._coneInnerAngle = coneInnerAngle;
  51090. this._coneOuterAngle = coneOuterAngle;
  51091. this._coneOuterGain = coneOuterGain;
  51092. this._isDirectional = true;
  51093. if (this.isPlaying && this.loop) {
  51094. this.stop();
  51095. this.play();
  51096. }
  51097. };
  51098. Sound.prototype.setPosition = function (newPosition) {
  51099. this._position = newPosition;
  51100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  51101. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51102. }
  51103. };
  51104. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  51105. this._localDirection = newLocalDirection;
  51106. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  51107. this._updateDirection();
  51108. }
  51109. };
  51110. Sound.prototype._updateDirection = function () {
  51111. if (!this._connectedMesh || !this._soundPanner) {
  51112. return;
  51113. }
  51114. var mat = this._connectedMesh.getWorldMatrix();
  51115. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  51116. direction.normalize();
  51117. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  51118. };
  51119. Sound.prototype.updateDistanceFromListener = function () {
  51120. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  51121. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  51122. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  51123. }
  51124. };
  51125. Sound.prototype.setAttenuationFunction = function (callback) {
  51126. this._customAttenuationFunction = callback;
  51127. };
  51128. /**
  51129. * Play the sound
  51130. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  51131. * @param offset (optional) Start the sound setting it at a specific time
  51132. */
  51133. Sound.prototype.play = function (time, offset) {
  51134. var _this = this;
  51135. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  51136. try {
  51137. if (this._startOffset < 0) {
  51138. time = -this._startOffset;
  51139. this._startOffset = 0;
  51140. }
  51141. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51142. if (!this._soundSource || !this._streamingSource) {
  51143. if (this.spatialSound && this._soundPanner) {
  51144. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51145. if (this._isDirectional) {
  51146. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  51147. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  51148. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51149. if (this._connectedMesh) {
  51150. this._updateDirection();
  51151. }
  51152. else {
  51153. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51154. }
  51155. }
  51156. }
  51157. }
  51158. if (this._streaming) {
  51159. if (!this._streamingSource) {
  51160. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51161. this._htmlAudioElement.onended = function () { _this._onended(); };
  51162. this._htmlAudioElement.playbackRate = this._playbackRate;
  51163. }
  51164. this._streamingSource.disconnect();
  51165. this._streamingSource.connect(this._inputAudioNode);
  51166. this._htmlAudioElement.play();
  51167. }
  51168. else {
  51169. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51170. this._soundSource.buffer = this._audioBuffer;
  51171. this._soundSource.connect(this._inputAudioNode);
  51172. this._soundSource.loop = this.loop;
  51173. this._soundSource.playbackRate.value = this._playbackRate;
  51174. this._soundSource.onended = function () { _this._onended(); };
  51175. if (this._soundSource.buffer) {
  51176. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51177. }
  51178. }
  51179. this._startTime = startTime;
  51180. this.isPlaying = true;
  51181. this.isPaused = false;
  51182. }
  51183. catch (ex) {
  51184. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51185. }
  51186. }
  51187. };
  51188. Sound.prototype._onended = function () {
  51189. this.isPlaying = false;
  51190. if (this.onended) {
  51191. this.onended();
  51192. }
  51193. };
  51194. /**
  51195. * Stop the sound
  51196. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51197. */
  51198. Sound.prototype.stop = function (time) {
  51199. if (this.isPlaying) {
  51200. if (this._streaming) {
  51201. this._htmlAudioElement.pause();
  51202. // Test needed for Firefox or it will generate an Invalid State Error
  51203. if (this._htmlAudioElement.currentTime > 0) {
  51204. this._htmlAudioElement.currentTime = 0;
  51205. }
  51206. }
  51207. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51208. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51209. this._soundSource.stop(stopTime);
  51210. this._soundSource.onended = function () { };
  51211. if (!this.isPaused) {
  51212. this._startOffset = 0;
  51213. }
  51214. }
  51215. this.isPlaying = false;
  51216. }
  51217. };
  51218. Sound.prototype.pause = function () {
  51219. if (this.isPlaying) {
  51220. this.isPaused = true;
  51221. if (this._streaming) {
  51222. this._htmlAudioElement.pause();
  51223. }
  51224. else if (BABYLON.Engine.audioEngine.audioContext) {
  51225. this.stop(0);
  51226. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51227. }
  51228. }
  51229. };
  51230. Sound.prototype.setVolume = function (newVolume, time) {
  51231. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51232. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51233. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51234. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51235. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51236. }
  51237. else {
  51238. this._soundGain.gain.value = newVolume;
  51239. }
  51240. }
  51241. this._volume = newVolume;
  51242. };
  51243. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51244. this._playbackRate = newPlaybackRate;
  51245. if (this.isPlaying) {
  51246. if (this._streaming) {
  51247. this._htmlAudioElement.playbackRate = this._playbackRate;
  51248. }
  51249. else if (this._soundSource) {
  51250. this._soundSource.playbackRate.value = this._playbackRate;
  51251. }
  51252. }
  51253. };
  51254. Sound.prototype.getVolume = function () {
  51255. return this._volume;
  51256. };
  51257. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51258. var _this = this;
  51259. if (this._connectedMesh && this._registerFunc) {
  51260. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51261. this._registerFunc = null;
  51262. }
  51263. this._connectedMesh = meshToConnectTo;
  51264. if (!this.spatialSound) {
  51265. this.spatialSound = true;
  51266. this._createSpatialParameters();
  51267. if (this.isPlaying && this.loop) {
  51268. this.stop();
  51269. this.play();
  51270. }
  51271. }
  51272. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51273. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51274. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51275. };
  51276. Sound.prototype.detachFromMesh = function () {
  51277. if (this._connectedMesh && this._registerFunc) {
  51278. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51279. this._registerFunc = null;
  51280. this._connectedMesh = null;
  51281. }
  51282. };
  51283. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51284. if (!node.getBoundingInfo) {
  51285. return;
  51286. }
  51287. var mesh = node;
  51288. var boundingInfo = mesh.getBoundingInfo();
  51289. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51291. this._updateDirection();
  51292. }
  51293. };
  51294. Sound.prototype.clone = function () {
  51295. var _this = this;
  51296. if (!this._streaming) {
  51297. var setBufferAndRun = function () {
  51298. if (_this._isReadyToPlay) {
  51299. clonedSound._audioBuffer = _this.getAudioBuffer();
  51300. clonedSound._isReadyToPlay = true;
  51301. if (clonedSound.autoplay) {
  51302. clonedSound.play();
  51303. }
  51304. }
  51305. else {
  51306. window.setTimeout(setBufferAndRun, 300);
  51307. }
  51308. };
  51309. var currentOptions = {
  51310. autoplay: this.autoplay, loop: this.loop,
  51311. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51312. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51313. refDistance: this.refDistance, distanceModel: this.distanceModel
  51314. };
  51315. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51316. if (this.useCustomAttenuation) {
  51317. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51318. }
  51319. clonedSound.setPosition(this._position);
  51320. clonedSound.setPlaybackRate(this._playbackRate);
  51321. setBufferAndRun();
  51322. return clonedSound;
  51323. }
  51324. else {
  51325. return null;
  51326. }
  51327. };
  51328. Sound.prototype.getAudioBuffer = function () {
  51329. return this._audioBuffer;
  51330. };
  51331. Sound.prototype.serialize = function () {
  51332. var serializationObject = {
  51333. name: this.name,
  51334. url: this.name,
  51335. autoplay: this.autoplay,
  51336. loop: this.loop,
  51337. volume: this._volume,
  51338. spatialSound: this.spatialSound,
  51339. maxDistance: this.maxDistance,
  51340. rolloffFactor: this.rolloffFactor,
  51341. refDistance: this.refDistance,
  51342. distanceModel: this.distanceModel,
  51343. playbackRate: this._playbackRate,
  51344. panningModel: this._panningModel,
  51345. soundTrackId: this.soundTrackId
  51346. };
  51347. if (this.spatialSound) {
  51348. if (this._connectedMesh)
  51349. serializationObject.connectedMeshId = this._connectedMesh.id;
  51350. serializationObject.position = this._position.asArray();
  51351. serializationObject.refDistance = this.refDistance;
  51352. serializationObject.distanceModel = this.distanceModel;
  51353. serializationObject.isDirectional = this._isDirectional;
  51354. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51355. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51356. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51357. serializationObject.coneOuterGain = this._coneOuterGain;
  51358. }
  51359. return serializationObject;
  51360. };
  51361. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51362. var soundName = parsedSound.name;
  51363. var soundUrl;
  51364. if (parsedSound.url) {
  51365. soundUrl = rootUrl + parsedSound.url;
  51366. }
  51367. else {
  51368. soundUrl = rootUrl + soundName;
  51369. }
  51370. var options = {
  51371. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51372. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51373. rolloffFactor: parsedSound.rolloffFactor,
  51374. refDistance: parsedSound.refDistance,
  51375. distanceModel: parsedSound.distanceModel,
  51376. playbackRate: parsedSound.playbackRate
  51377. };
  51378. var newSound;
  51379. if (!sourceSound) {
  51380. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51381. scene._addPendingData(newSound);
  51382. }
  51383. else {
  51384. var setBufferAndRun = function () {
  51385. if (sourceSound._isReadyToPlay) {
  51386. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51387. newSound._isReadyToPlay = true;
  51388. if (newSound.autoplay) {
  51389. newSound.play();
  51390. }
  51391. }
  51392. else {
  51393. window.setTimeout(setBufferAndRun, 300);
  51394. }
  51395. };
  51396. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51397. setBufferAndRun();
  51398. }
  51399. if (parsedSound.position) {
  51400. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51401. newSound.setPosition(soundPosition);
  51402. }
  51403. if (parsedSound.isDirectional) {
  51404. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51405. if (parsedSound.localDirectionToMesh) {
  51406. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51407. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51408. }
  51409. }
  51410. if (parsedSound.connectedMeshId) {
  51411. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51412. if (connectedMesh) {
  51413. newSound.attachToMesh(connectedMesh);
  51414. }
  51415. }
  51416. return newSound;
  51417. };
  51418. return Sound;
  51419. }());
  51420. BABYLON.Sound = Sound;
  51421. })(BABYLON || (BABYLON = {}));
  51422. //# sourceMappingURL=babylon.sound.js.map
  51423. var BABYLON;
  51424. (function (BABYLON) {
  51425. var SoundTrack = /** @class */ (function () {
  51426. function SoundTrack(scene, options) {
  51427. this.id = -1;
  51428. this._isMainTrack = false;
  51429. this._isInitialized = false;
  51430. this._scene = scene;
  51431. this.soundCollection = new Array();
  51432. this._options = options;
  51433. if (!this._isMainTrack) {
  51434. this._scene.soundTracks.push(this);
  51435. this.id = this._scene.soundTracks.length - 1;
  51436. }
  51437. }
  51438. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51439. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51440. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51441. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51442. if (this._options) {
  51443. if (this._options.volume) {
  51444. this._outputAudioNode.gain.value = this._options.volume;
  51445. }
  51446. if (this._options.mainTrack) {
  51447. this._isMainTrack = this._options.mainTrack;
  51448. }
  51449. }
  51450. this._isInitialized = true;
  51451. }
  51452. };
  51453. SoundTrack.prototype.dispose = function () {
  51454. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51455. if (this._connectedAnalyser) {
  51456. this._connectedAnalyser.stopDebugCanvas();
  51457. }
  51458. while (this.soundCollection.length) {
  51459. this.soundCollection[0].dispose();
  51460. }
  51461. if (this._outputAudioNode) {
  51462. this._outputAudioNode.disconnect();
  51463. }
  51464. this._outputAudioNode = null;
  51465. }
  51466. };
  51467. SoundTrack.prototype.AddSound = function (sound) {
  51468. if (!this._isInitialized) {
  51469. this._initializeSoundTrackAudioGraph();
  51470. }
  51471. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51472. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51473. }
  51474. if (sound.soundTrackId) {
  51475. if (sound.soundTrackId === -1) {
  51476. this._scene.mainSoundTrack.RemoveSound(sound);
  51477. }
  51478. else {
  51479. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51480. }
  51481. }
  51482. this.soundCollection.push(sound);
  51483. sound.soundTrackId = this.id;
  51484. };
  51485. SoundTrack.prototype.RemoveSound = function (sound) {
  51486. var index = this.soundCollection.indexOf(sound);
  51487. if (index !== -1) {
  51488. this.soundCollection.splice(index, 1);
  51489. }
  51490. };
  51491. SoundTrack.prototype.setVolume = function (newVolume) {
  51492. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51493. this._outputAudioNode.gain.value = newVolume;
  51494. }
  51495. };
  51496. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51497. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51498. for (var i = 0; i < this.soundCollection.length; i++) {
  51499. this.soundCollection[i].switchPanningModelToHRTF();
  51500. }
  51501. }
  51502. };
  51503. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51504. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51505. for (var i = 0; i < this.soundCollection.length; i++) {
  51506. this.soundCollection[i].switchPanningModelToEqualPower();
  51507. }
  51508. }
  51509. };
  51510. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51511. if (this._connectedAnalyser) {
  51512. this._connectedAnalyser.stopDebugCanvas();
  51513. }
  51514. this._connectedAnalyser = analyser;
  51515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51516. this._outputAudioNode.disconnect();
  51517. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51518. }
  51519. };
  51520. return SoundTrack;
  51521. }());
  51522. BABYLON.SoundTrack = SoundTrack;
  51523. })(BABYLON || (BABYLON = {}));
  51524. //# sourceMappingURL=babylon.soundtrack.js.map
  51525. var BABYLON;
  51526. (function (BABYLON) {
  51527. var Analyser = /** @class */ (function () {
  51528. function Analyser(scene) {
  51529. this.SMOOTHING = 0.75;
  51530. this.FFT_SIZE = 512;
  51531. this.BARGRAPHAMPLITUDE = 256;
  51532. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51533. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51534. this._scene = scene;
  51535. this._audioEngine = BABYLON.Engine.audioEngine;
  51536. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51537. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51538. this._webAudioAnalyser.minDecibels = -140;
  51539. this._webAudioAnalyser.maxDecibels = 0;
  51540. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51541. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51542. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51543. }
  51544. }
  51545. Analyser.prototype.getFrequencyBinCount = function () {
  51546. if (this._audioEngine.canUseWebAudio) {
  51547. return this._webAudioAnalyser.frequencyBinCount;
  51548. }
  51549. else {
  51550. return 0;
  51551. }
  51552. };
  51553. Analyser.prototype.getByteFrequencyData = function () {
  51554. if (this._audioEngine.canUseWebAudio) {
  51555. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51556. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51557. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51558. }
  51559. return this._byteFreqs;
  51560. };
  51561. Analyser.prototype.getByteTimeDomainData = function () {
  51562. if (this._audioEngine.canUseWebAudio) {
  51563. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51564. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51565. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51566. }
  51567. return this._byteTime;
  51568. };
  51569. Analyser.prototype.getFloatFrequencyData = function () {
  51570. if (this._audioEngine.canUseWebAudio) {
  51571. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51572. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51573. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51574. }
  51575. return this._floatFreqs;
  51576. };
  51577. Analyser.prototype.drawDebugCanvas = function () {
  51578. var _this = this;
  51579. if (this._audioEngine.canUseWebAudio) {
  51580. if (!this._debugCanvas) {
  51581. this._debugCanvas = document.createElement("canvas");
  51582. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51583. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51584. this._debugCanvas.style.position = "absolute";
  51585. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51586. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51587. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51588. document.body.appendChild(this._debugCanvas);
  51589. this._registerFunc = function () {
  51590. _this.drawDebugCanvas();
  51591. };
  51592. this._scene.registerBeforeRender(this._registerFunc);
  51593. }
  51594. if (this._registerFunc && this._debugCanvasContext) {
  51595. var workingArray = this.getByteFrequencyData();
  51596. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51597. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51598. // Draw the frequency domain chart.
  51599. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51600. var value = workingArray[i];
  51601. var percent = value / this.BARGRAPHAMPLITUDE;
  51602. var height = this.DEBUGCANVASSIZE.height * percent;
  51603. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51604. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51605. var hue = i / this.getFrequencyBinCount() * 360;
  51606. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51607. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51608. }
  51609. }
  51610. }
  51611. };
  51612. Analyser.prototype.stopDebugCanvas = function () {
  51613. if (this._debugCanvas) {
  51614. if (this._registerFunc) {
  51615. this._scene.unregisterBeforeRender(this._registerFunc);
  51616. this._registerFunc = null;
  51617. }
  51618. document.body.removeChild(this._debugCanvas);
  51619. this._debugCanvas = null;
  51620. this._debugCanvasContext = null;
  51621. }
  51622. };
  51623. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51624. if (this._audioEngine.canUseWebAudio) {
  51625. inputAudioNode.connect(this._webAudioAnalyser);
  51626. this._webAudioAnalyser.connect(outputAudioNode);
  51627. }
  51628. };
  51629. Analyser.prototype.dispose = function () {
  51630. if (this._audioEngine.canUseWebAudio) {
  51631. this._webAudioAnalyser.disconnect();
  51632. }
  51633. };
  51634. return Analyser;
  51635. }());
  51636. BABYLON.Analyser = Analyser;
  51637. })(BABYLON || (BABYLON = {}));
  51638. //# sourceMappingURL=babylon.analyser.js.map
  51639. var BABYLON;
  51640. (function (BABYLON) {
  51641. var CubeTexture = /** @class */ (function (_super) {
  51642. __extends(CubeTexture, _super);
  51643. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51644. if (extensions === void 0) { extensions = null; }
  51645. if (noMipmap === void 0) { noMipmap = false; }
  51646. if (files === void 0) { files = null; }
  51647. if (onLoad === void 0) { onLoad = null; }
  51648. if (onError === void 0) { onError = null; }
  51649. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51650. if (prefiltered === void 0) { prefiltered = false; }
  51651. if (forcedExtension === void 0) { forcedExtension = null; }
  51652. var _this = _super.call(this, scene) || this;
  51653. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51654. _this.name = rootUrl;
  51655. _this.url = rootUrl;
  51656. _this._noMipmap = noMipmap;
  51657. _this.hasAlpha = false;
  51658. _this._format = format;
  51659. _this._prefiltered = prefiltered;
  51660. _this.isCube = true;
  51661. _this._textureMatrix = BABYLON.Matrix.Identity();
  51662. if (prefiltered) {
  51663. _this.gammaSpace = false;
  51664. }
  51665. if (!rootUrl && !files) {
  51666. return _this;
  51667. }
  51668. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51669. var lastDot = rootUrl.lastIndexOf(".");
  51670. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51671. var isDDS = (extension === ".dds");
  51672. if (!files) {
  51673. if (!isDDS && !extensions) {
  51674. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51675. }
  51676. files = [];
  51677. if (extensions) {
  51678. for (var index = 0; index < extensions.length; index++) {
  51679. files.push(rootUrl + extensions[index]);
  51680. }
  51681. }
  51682. }
  51683. _this._files = files;
  51684. if (!_this._texture) {
  51685. if (!scene.useDelayedTextureLoading) {
  51686. if (prefiltered) {
  51687. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51688. }
  51689. else {
  51690. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51691. }
  51692. }
  51693. else {
  51694. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51695. }
  51696. }
  51697. else if (onLoad) {
  51698. if (_this._texture.isReady) {
  51699. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51700. }
  51701. else {
  51702. _this._texture.onLoadedObservable.add(onLoad);
  51703. }
  51704. }
  51705. return _this;
  51706. }
  51707. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51708. return new CubeTexture("", scene, null, noMipmap, files);
  51709. };
  51710. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51711. if (forcedExtension === void 0) { forcedExtension = null; }
  51712. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51713. };
  51714. // Methods
  51715. CubeTexture.prototype.delayLoad = function () {
  51716. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51717. return;
  51718. }
  51719. var scene = this.getScene();
  51720. if (!scene) {
  51721. return;
  51722. }
  51723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51724. this._texture = this._getFromCache(this.url, this._noMipmap);
  51725. if (!this._texture) {
  51726. if (this._prefiltered) {
  51727. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51728. }
  51729. else {
  51730. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51731. }
  51732. }
  51733. };
  51734. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51735. return this._textureMatrix;
  51736. };
  51737. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51738. this._textureMatrix = value;
  51739. };
  51740. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51741. var texture = BABYLON.SerializationHelper.Parse(function () {
  51742. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51743. }, parsedTexture, scene);
  51744. // Animations
  51745. if (parsedTexture.animations) {
  51746. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51747. var parsedAnimation = parsedTexture.animations[animationIndex];
  51748. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51749. }
  51750. }
  51751. return texture;
  51752. };
  51753. CubeTexture.prototype.clone = function () {
  51754. var _this = this;
  51755. return BABYLON.SerializationHelper.Clone(function () {
  51756. var scene = _this.getScene();
  51757. if (!scene) {
  51758. return _this;
  51759. }
  51760. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51761. }, this);
  51762. };
  51763. return CubeTexture;
  51764. }(BABYLON.BaseTexture));
  51765. BABYLON.CubeTexture = CubeTexture;
  51766. })(BABYLON || (BABYLON = {}));
  51767. //# sourceMappingURL=babylon.cubeTexture.js.map
  51768. var BABYLON;
  51769. (function (BABYLON) {
  51770. var RenderTargetTexture = /** @class */ (function (_super) {
  51771. __extends(RenderTargetTexture, _super);
  51772. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51773. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51774. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51775. if (isCube === void 0) { isCube = false; }
  51776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51777. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51778. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51779. if (isMulti === void 0) { isMulti = false; }
  51780. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51781. _this.isCube = isCube;
  51782. /**
  51783. * Use this list to define the list of mesh you want to render.
  51784. */
  51785. _this.renderList = new Array();
  51786. _this.renderParticles = true;
  51787. _this.renderSprites = false;
  51788. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51789. _this.ignoreCameraViewport = false;
  51790. // Events
  51791. /**
  51792. * An event triggered when the texture is unbind.
  51793. * @type {BABYLON.Observable}
  51794. */
  51795. _this.onBeforeBindObservable = new BABYLON.Observable();
  51796. /**
  51797. * An event triggered when the texture is unbind.
  51798. * @type {BABYLON.Observable}
  51799. */
  51800. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51801. /**
  51802. * An event triggered before rendering the texture
  51803. * @type {BABYLON.Observable}
  51804. */
  51805. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51806. /**
  51807. * An event triggered after rendering the texture
  51808. * @type {BABYLON.Observable}
  51809. */
  51810. _this.onAfterRenderObservable = new BABYLON.Observable();
  51811. /**
  51812. * An event triggered after the texture clear
  51813. * @type {BABYLON.Observable}
  51814. */
  51815. _this.onClearObservable = new BABYLON.Observable();
  51816. _this._currentRefreshId = -1;
  51817. _this._refreshRate = 1;
  51818. _this._samples = 1;
  51819. scene = _this.getScene();
  51820. if (!scene) {
  51821. return _this;
  51822. }
  51823. _this._engine = scene.getEngine();
  51824. _this.name = name;
  51825. _this.isRenderTarget = true;
  51826. _this._initialSizeParameter = size;
  51827. _this._processSizeParameter(size);
  51828. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51829. });
  51830. _this._generateMipMaps = generateMipMaps ? true : false;
  51831. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51832. // Rendering groups
  51833. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51834. if (isMulti) {
  51835. return _this;
  51836. }
  51837. _this._renderTargetOptions = {
  51838. generateMipMaps: generateMipMaps,
  51839. type: type,
  51840. samplingMode: samplingMode,
  51841. generateDepthBuffer: generateDepthBuffer,
  51842. generateStencilBuffer: generateStencilBuffer
  51843. };
  51844. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51845. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51846. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51847. }
  51848. if (isCube) {
  51849. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51850. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51851. _this._textureMatrix = BABYLON.Matrix.Identity();
  51852. }
  51853. else {
  51854. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51855. }
  51856. return _this;
  51857. }
  51858. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51859. get: function () {
  51860. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51861. },
  51862. enumerable: true,
  51863. configurable: true
  51864. });
  51865. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51866. get: function () {
  51867. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51868. },
  51869. enumerable: true,
  51870. configurable: true
  51871. });
  51872. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51873. get: function () {
  51874. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51875. },
  51876. enumerable: true,
  51877. configurable: true
  51878. });
  51879. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51880. set: function (callback) {
  51881. if (this._onAfterUnbindObserver) {
  51882. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51883. }
  51884. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51885. },
  51886. enumerable: true,
  51887. configurable: true
  51888. });
  51889. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51890. set: function (callback) {
  51891. if (this._onBeforeRenderObserver) {
  51892. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51893. }
  51894. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51895. },
  51896. enumerable: true,
  51897. configurable: true
  51898. });
  51899. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51900. set: function (callback) {
  51901. if (this._onAfterRenderObserver) {
  51902. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51903. }
  51904. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51905. },
  51906. enumerable: true,
  51907. configurable: true
  51908. });
  51909. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51910. set: function (callback) {
  51911. if (this._onClearObserver) {
  51912. this.onClearObservable.remove(this._onClearObserver);
  51913. }
  51914. this._onClearObserver = this.onClearObservable.add(callback);
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51920. get: function () {
  51921. return this._renderTargetOptions;
  51922. },
  51923. enumerable: true,
  51924. configurable: true
  51925. });
  51926. RenderTargetTexture.prototype._onRatioRescale = function () {
  51927. if (this._sizeRatio) {
  51928. this.resize(this._initialSizeParameter);
  51929. }
  51930. };
  51931. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51932. if (size.ratio) {
  51933. this._sizeRatio = size.ratio;
  51934. this._size = {
  51935. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51936. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51937. };
  51938. }
  51939. else {
  51940. this._size = size;
  51941. }
  51942. };
  51943. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51944. get: function () {
  51945. return this._samples;
  51946. },
  51947. set: function (value) {
  51948. if (this._samples === value) {
  51949. return;
  51950. }
  51951. var scene = this.getScene();
  51952. if (!scene) {
  51953. return;
  51954. }
  51955. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51956. },
  51957. enumerable: true,
  51958. configurable: true
  51959. });
  51960. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51961. this._currentRefreshId = -1;
  51962. };
  51963. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51964. get: function () {
  51965. return this._refreshRate;
  51966. },
  51967. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51968. set: function (value) {
  51969. this._refreshRate = value;
  51970. this.resetRefreshCounter();
  51971. },
  51972. enumerable: true,
  51973. configurable: true
  51974. });
  51975. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51976. if (!this._postProcessManager) {
  51977. var scene = this.getScene();
  51978. if (!scene) {
  51979. return;
  51980. }
  51981. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51982. this._postProcesses = new Array();
  51983. }
  51984. this._postProcesses.push(postProcess);
  51985. this._postProcesses[0].autoClear = false;
  51986. };
  51987. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51988. if (!this._postProcesses) {
  51989. return;
  51990. }
  51991. if (dispose) {
  51992. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51993. var postProcess = _a[_i];
  51994. postProcess.dispose();
  51995. }
  51996. }
  51997. this._postProcesses = [];
  51998. };
  51999. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  52000. if (!this._postProcesses) {
  52001. return;
  52002. }
  52003. var index = this._postProcesses.indexOf(postProcess);
  52004. if (index === -1) {
  52005. return;
  52006. }
  52007. this._postProcesses.splice(index, 1);
  52008. if (this._postProcesses.length > 0) {
  52009. this._postProcesses[0].autoClear = false;
  52010. }
  52011. };
  52012. RenderTargetTexture.prototype._shouldRender = function () {
  52013. if (this._currentRefreshId === -1) {
  52014. this._currentRefreshId = 1;
  52015. return true;
  52016. }
  52017. if (this.refreshRate === this._currentRefreshId) {
  52018. this._currentRefreshId = 1;
  52019. return true;
  52020. }
  52021. this._currentRefreshId++;
  52022. return false;
  52023. };
  52024. RenderTargetTexture.prototype.getRenderSize = function () {
  52025. if (this._size.width) {
  52026. return this._size.width;
  52027. }
  52028. return this._size;
  52029. };
  52030. RenderTargetTexture.prototype.getRenderWidth = function () {
  52031. if (this._size.width) {
  52032. return this._size.width;
  52033. }
  52034. return this._size;
  52035. };
  52036. RenderTargetTexture.prototype.getRenderHeight = function () {
  52037. if (this._size.width) {
  52038. return this._size.height;
  52039. }
  52040. return this._size;
  52041. };
  52042. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  52043. get: function () {
  52044. return true;
  52045. },
  52046. enumerable: true,
  52047. configurable: true
  52048. });
  52049. RenderTargetTexture.prototype.scale = function (ratio) {
  52050. var newSize = this.getRenderSize() * ratio;
  52051. this.resize(newSize);
  52052. };
  52053. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  52054. if (this.isCube) {
  52055. return this._textureMatrix;
  52056. }
  52057. return _super.prototype.getReflectionTextureMatrix.call(this);
  52058. };
  52059. RenderTargetTexture.prototype.resize = function (size) {
  52060. this.releaseInternalTexture();
  52061. var scene = this.getScene();
  52062. if (!scene) {
  52063. return;
  52064. }
  52065. this._processSizeParameter(size);
  52066. if (this.isCube) {
  52067. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  52068. }
  52069. else {
  52070. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  52071. }
  52072. };
  52073. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  52074. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  52075. if (dumpForDebug === void 0) { dumpForDebug = false; }
  52076. var scene = this.getScene();
  52077. if (!scene) {
  52078. return;
  52079. }
  52080. var engine = scene.getEngine();
  52081. if (this.useCameraPostProcesses !== undefined) {
  52082. useCameraPostProcess = this.useCameraPostProcesses;
  52083. }
  52084. if (this._waitingRenderList) {
  52085. this.renderList = [];
  52086. for (var index = 0; index < this._waitingRenderList.length; index++) {
  52087. var id = this._waitingRenderList[index];
  52088. var mesh_1 = scene.getMeshByID(id);
  52089. if (mesh_1) {
  52090. this.renderList.push(mesh_1);
  52091. }
  52092. }
  52093. delete this._waitingRenderList;
  52094. }
  52095. // Is predicate defined?
  52096. if (this.renderListPredicate) {
  52097. if (this.renderList) {
  52098. this.renderList.splice(0); // Clear previous renderList
  52099. }
  52100. else {
  52101. this.renderList = [];
  52102. }
  52103. var scene = this.getScene();
  52104. if (!scene) {
  52105. return;
  52106. }
  52107. var sceneMeshes = scene.meshes;
  52108. for (var index = 0; index < sceneMeshes.length; index++) {
  52109. var mesh = sceneMeshes[index];
  52110. if (this.renderListPredicate(mesh)) {
  52111. this.renderList.push(mesh);
  52112. }
  52113. }
  52114. }
  52115. this.onBeforeBindObservable.notifyObservers(this);
  52116. // Set custom projection.
  52117. // Needs to be before binding to prevent changing the aspect ratio.
  52118. var camera;
  52119. if (this.activeCamera) {
  52120. camera = this.activeCamera;
  52121. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52122. if (this.activeCamera !== scene.activeCamera) {
  52123. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  52124. }
  52125. }
  52126. else {
  52127. camera = scene.activeCamera;
  52128. if (camera) {
  52129. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52130. }
  52131. }
  52132. // Prepare renderingManager
  52133. this._renderingManager.reset();
  52134. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  52135. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  52136. var sceneRenderId = scene.getRenderId();
  52137. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  52138. var mesh = currentRenderList[meshIndex];
  52139. if (mesh) {
  52140. if (!mesh.isReady()) {
  52141. // Reset _currentRefreshId
  52142. this.resetRefreshCounter();
  52143. continue;
  52144. }
  52145. mesh._preActivateForIntermediateRendering(sceneRenderId);
  52146. var isMasked = void 0;
  52147. if (!this.renderList && camera) {
  52148. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52149. }
  52150. else {
  52151. isMasked = false;
  52152. }
  52153. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52154. mesh._activate(sceneRenderId);
  52155. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52156. var subMesh = mesh.subMeshes[subIndex];
  52157. scene._activeIndices.addCount(subMesh.indexCount, false);
  52158. this._renderingManager.dispatch(subMesh, mesh);
  52159. }
  52160. }
  52161. }
  52162. }
  52163. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52164. var particleSystem = scene.particleSystems[particleIndex];
  52165. var emitter = particleSystem.emitter;
  52166. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52167. continue;
  52168. }
  52169. if (currentRenderList.indexOf(emitter) >= 0) {
  52170. this._renderingManager.dispatchParticles(particleSystem);
  52171. }
  52172. }
  52173. if (this.isCube) {
  52174. for (var face = 0; face < 6; face++) {
  52175. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52176. scene.incrementRenderId();
  52177. scene.resetCachedMaterial();
  52178. }
  52179. }
  52180. else {
  52181. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52182. }
  52183. this.onAfterUnbindObservable.notifyObservers(this);
  52184. if (scene.activeCamera) {
  52185. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52186. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52187. }
  52188. engine.setViewport(scene.activeCamera.viewport);
  52189. }
  52190. scene.resetCachedMaterial();
  52191. };
  52192. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52193. var minimum = 128;
  52194. var x = renderDimension * scale;
  52195. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52196. // Ensure we don't exceed the render dimension (while staying POT)
  52197. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52198. };
  52199. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52200. var _this = this;
  52201. if (!this._texture) {
  52202. return;
  52203. }
  52204. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52205. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52206. });
  52207. };
  52208. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52209. var scene = this.getScene();
  52210. if (!scene) {
  52211. return;
  52212. }
  52213. var engine = scene.getEngine();
  52214. if (!this._texture) {
  52215. return;
  52216. }
  52217. // Bind
  52218. if (this._postProcessManager) {
  52219. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52220. }
  52221. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52222. if (this._texture) {
  52223. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52224. }
  52225. }
  52226. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52227. // Clear
  52228. if (this.onClearObservable.hasObservers()) {
  52229. this.onClearObservable.notifyObservers(engine);
  52230. }
  52231. else {
  52232. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52233. }
  52234. if (!this._doNotChangeAspectRatio) {
  52235. scene.updateTransformMatrix(true);
  52236. }
  52237. // Render
  52238. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52239. if (this._postProcessManager) {
  52240. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52241. }
  52242. else if (useCameraPostProcess) {
  52243. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52244. }
  52245. if (!this._doNotChangeAspectRatio) {
  52246. scene.updateTransformMatrix(true);
  52247. }
  52248. // Dump ?
  52249. if (dumpForDebug) {
  52250. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52251. }
  52252. // Unbind
  52253. if (!this.isCube || faceIndex === 5) {
  52254. if (this.isCube) {
  52255. if (faceIndex === 5) {
  52256. engine.generateMipMapsForCubemap(this._texture);
  52257. }
  52258. }
  52259. this.unbindFrameBuffer(engine, faceIndex);
  52260. }
  52261. else {
  52262. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52263. }
  52264. };
  52265. /**
  52266. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52267. * This allowed control for front to back rendering or reversly depending of the special needs.
  52268. *
  52269. * @param renderingGroupId The rendering group id corresponding to its index
  52270. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52271. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52272. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52273. */
  52274. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52275. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52276. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52277. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52278. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52279. };
  52280. /**
  52281. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52282. *
  52283. * @param renderingGroupId The rendering group id corresponding to its index
  52284. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52285. */
  52286. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52287. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52288. };
  52289. RenderTargetTexture.prototype.clone = function () {
  52290. var textureSize = this.getSize();
  52291. 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);
  52292. // Base texture
  52293. newTexture.hasAlpha = this.hasAlpha;
  52294. newTexture.level = this.level;
  52295. // RenderTarget Texture
  52296. newTexture.coordinatesMode = this.coordinatesMode;
  52297. if (this.renderList) {
  52298. newTexture.renderList = this.renderList.slice(0);
  52299. }
  52300. return newTexture;
  52301. };
  52302. RenderTargetTexture.prototype.serialize = function () {
  52303. if (!this.name) {
  52304. return null;
  52305. }
  52306. var serializationObject = _super.prototype.serialize.call(this);
  52307. serializationObject.renderTargetSize = this.getRenderSize();
  52308. serializationObject.renderList = [];
  52309. if (this.renderList) {
  52310. for (var index = 0; index < this.renderList.length; index++) {
  52311. serializationObject.renderList.push(this.renderList[index].id);
  52312. }
  52313. }
  52314. return serializationObject;
  52315. };
  52316. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52317. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52318. var objBuffer = this.getInternalTexture();
  52319. var scene = this.getScene();
  52320. if (objBuffer && scene) {
  52321. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52322. }
  52323. };
  52324. RenderTargetTexture.prototype.dispose = function () {
  52325. if (this._postProcessManager) {
  52326. this._postProcessManager.dispose();
  52327. this._postProcessManager = null;
  52328. }
  52329. this.clearPostProcesses(true);
  52330. if (this._resizeObserver) {
  52331. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52332. this._resizeObserver = null;
  52333. }
  52334. this.renderList = null;
  52335. // Remove from custom render targets
  52336. var scene = this.getScene();
  52337. if (!scene) {
  52338. return;
  52339. }
  52340. var index = scene.customRenderTargets.indexOf(this);
  52341. if (index >= 0) {
  52342. scene.customRenderTargets.splice(index, 1);
  52343. }
  52344. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52345. var camera = _a[_i];
  52346. index = camera.customRenderTargets.indexOf(this);
  52347. if (index >= 0) {
  52348. camera.customRenderTargets.splice(index, 1);
  52349. }
  52350. }
  52351. _super.prototype.dispose.call(this);
  52352. };
  52353. RenderTargetTexture.prototype._rebuild = function () {
  52354. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52355. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52356. }
  52357. if (this._postProcessManager) {
  52358. this._postProcessManager._rebuild();
  52359. }
  52360. };
  52361. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52362. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52363. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52364. return RenderTargetTexture;
  52365. }(BABYLON.Texture));
  52366. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52367. })(BABYLON || (BABYLON = {}));
  52368. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52369. var BABYLON;
  52370. (function (BABYLON) {
  52371. ;
  52372. var MultiRenderTarget = /** @class */ (function (_super) {
  52373. __extends(MultiRenderTarget, _super);
  52374. function MultiRenderTarget(name, size, count, scene, options) {
  52375. var _this = this;
  52376. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52377. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52378. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52379. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52380. _this._engine = scene.getEngine();
  52381. if (!_this.isSupported) {
  52382. _this.dispose();
  52383. return;
  52384. }
  52385. var types = [];
  52386. var samplingModes = [];
  52387. for (var i = 0; i < count; i++) {
  52388. if (options && options.types && options.types[i] !== undefined) {
  52389. types.push(options.types[i]);
  52390. }
  52391. else {
  52392. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52393. }
  52394. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52395. samplingModes.push(options.samplingModes[i]);
  52396. }
  52397. else {
  52398. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52399. }
  52400. }
  52401. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52402. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52403. _this._size = size;
  52404. _this._multiRenderTargetOptions = {
  52405. samplingModes: samplingModes,
  52406. generateMipMaps: generateMipMaps,
  52407. generateDepthBuffer: generateDepthBuffer,
  52408. generateStencilBuffer: generateStencilBuffer,
  52409. generateDepthTexture: generateDepthTexture,
  52410. types: types,
  52411. textureCount: count
  52412. };
  52413. _this._createInternalTextures();
  52414. _this._createTextures();
  52415. return _this;
  52416. }
  52417. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52418. get: function () {
  52419. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52420. },
  52421. enumerable: true,
  52422. configurable: true
  52423. });
  52424. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52425. get: function () {
  52426. return this._textures;
  52427. },
  52428. enumerable: true,
  52429. configurable: true
  52430. });
  52431. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52432. get: function () {
  52433. return this._textures[this._textures.length - 1];
  52434. },
  52435. enumerable: true,
  52436. configurable: true
  52437. });
  52438. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52439. set: function (wrap) {
  52440. if (this._textures) {
  52441. for (var i = 0; i < this._textures.length; i++) {
  52442. this._textures[i].wrapU = wrap;
  52443. }
  52444. }
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52450. set: function (wrap) {
  52451. if (this._textures) {
  52452. for (var i = 0; i < this._textures.length; i++) {
  52453. this._textures[i].wrapV = wrap;
  52454. }
  52455. }
  52456. },
  52457. enumerable: true,
  52458. configurable: true
  52459. });
  52460. MultiRenderTarget.prototype._rebuild = function () {
  52461. this.releaseInternalTextures();
  52462. this._createInternalTextures();
  52463. for (var i = 0; i < this._internalTextures.length; i++) {
  52464. var texture = this._textures[i];
  52465. texture._texture = this._internalTextures[i];
  52466. }
  52467. // Keeps references to frame buffer and stencil/depth buffer
  52468. this._texture = this._internalTextures[0];
  52469. };
  52470. MultiRenderTarget.prototype._createInternalTextures = function () {
  52471. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52472. };
  52473. MultiRenderTarget.prototype._createTextures = function () {
  52474. this._textures = [];
  52475. for (var i = 0; i < this._internalTextures.length; i++) {
  52476. var texture = new BABYLON.Texture(null, this.getScene());
  52477. texture._texture = this._internalTextures[i];
  52478. this._textures.push(texture);
  52479. }
  52480. // Keeps references to frame buffer and stencil/depth buffer
  52481. this._texture = this._internalTextures[0];
  52482. };
  52483. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52484. get: function () {
  52485. return this._samples;
  52486. },
  52487. set: function (value) {
  52488. if (this._samples === value) {
  52489. return;
  52490. }
  52491. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. MultiRenderTarget.prototype.resize = function (size) {
  52497. this.releaseInternalTextures();
  52498. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52499. this._createInternalTextures();
  52500. };
  52501. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52502. var _this = this;
  52503. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52504. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52505. });
  52506. };
  52507. MultiRenderTarget.prototype.dispose = function () {
  52508. this.releaseInternalTextures();
  52509. _super.prototype.dispose.call(this);
  52510. };
  52511. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52512. if (!this._internalTextures) {
  52513. return;
  52514. }
  52515. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52516. if (this._internalTextures[i] !== undefined) {
  52517. this._internalTextures[i].dispose();
  52518. this._internalTextures.splice(i, 1);
  52519. }
  52520. }
  52521. };
  52522. return MultiRenderTarget;
  52523. }(BABYLON.RenderTargetTexture));
  52524. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52525. })(BABYLON || (BABYLON = {}));
  52526. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52527. var BABYLON;
  52528. (function (BABYLON) {
  52529. var MirrorTexture = /** @class */ (function (_super) {
  52530. __extends(MirrorTexture, _super);
  52531. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52532. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52534. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52535. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52536. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52537. _this._transformMatrix = BABYLON.Matrix.Zero();
  52538. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52539. _this._adaptiveBlurKernel = 0;
  52540. _this._blurKernelX = 0;
  52541. _this._blurKernelY = 0;
  52542. _this._blurRatio = 1.0;
  52543. _this.ignoreCameraViewport = true;
  52544. _this.onBeforeRenderObservable.add(function () {
  52545. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52546. _this._savedViewMatrix = scene.getViewMatrix();
  52547. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52548. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52549. scene.clipPlane = _this.mirrorPlane;
  52550. scene.getEngine().cullBackFaces = false;
  52551. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52552. });
  52553. _this.onAfterRenderObservable.add(function () {
  52554. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52555. scene.getEngine().cullBackFaces = true;
  52556. scene._mirroredCameraPosition = null;
  52557. delete scene.clipPlane;
  52558. });
  52559. return _this;
  52560. }
  52561. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52562. get: function () {
  52563. return this._blurRatio;
  52564. },
  52565. set: function (value) {
  52566. if (this._blurRatio === value) {
  52567. return;
  52568. }
  52569. this._blurRatio = value;
  52570. this._preparePostProcesses();
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52576. set: function (value) {
  52577. this._adaptiveBlurKernel = value;
  52578. this._autoComputeBlurKernel();
  52579. },
  52580. enumerable: true,
  52581. configurable: true
  52582. });
  52583. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52584. set: function (value) {
  52585. this.blurKernelX = value;
  52586. this.blurKernelY = value;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52592. get: function () {
  52593. return this._blurKernelX;
  52594. },
  52595. set: function (value) {
  52596. if (this._blurKernelX === value) {
  52597. return;
  52598. }
  52599. this._blurKernelX = value;
  52600. this._preparePostProcesses();
  52601. },
  52602. enumerable: true,
  52603. configurable: true
  52604. });
  52605. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52606. get: function () {
  52607. return this._blurKernelY;
  52608. },
  52609. set: function (value) {
  52610. if (this._blurKernelY === value) {
  52611. return;
  52612. }
  52613. this._blurKernelY = value;
  52614. this._preparePostProcesses();
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52620. var engine = this.getScene().getEngine();
  52621. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52622. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52623. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52624. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52625. };
  52626. MirrorTexture.prototype._onRatioRescale = function () {
  52627. if (this._sizeRatio) {
  52628. this.resize(this._initialSizeParameter);
  52629. if (!this._adaptiveBlurKernel) {
  52630. this._preparePostProcesses();
  52631. }
  52632. }
  52633. if (this._adaptiveBlurKernel) {
  52634. this._autoComputeBlurKernel();
  52635. }
  52636. };
  52637. MirrorTexture.prototype._preparePostProcesses = function () {
  52638. this.clearPostProcesses(true);
  52639. if (this._blurKernelX && this._blurKernelY) {
  52640. var engine = this.getScene().getEngine();
  52641. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52642. 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);
  52643. this._blurX.autoClear = false;
  52644. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52645. this._blurX.outputTexture = this._texture;
  52646. }
  52647. else {
  52648. this._blurX.alwaysForcePOT = true;
  52649. }
  52650. 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);
  52651. this._blurY.autoClear = false;
  52652. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52653. this.addPostProcess(this._blurX);
  52654. this.addPostProcess(this._blurY);
  52655. }
  52656. else {
  52657. if (this._blurY) {
  52658. this.removePostProcess(this._blurY);
  52659. this._blurY.dispose();
  52660. this._blurY = null;
  52661. }
  52662. if (this._blurX) {
  52663. this.removePostProcess(this._blurX);
  52664. this._blurX.dispose();
  52665. this._blurX = null;
  52666. }
  52667. }
  52668. };
  52669. MirrorTexture.prototype.clone = function () {
  52670. var scene = this.getScene();
  52671. if (!scene) {
  52672. return this;
  52673. }
  52674. var textureSize = this.getSize();
  52675. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52676. // Base texture
  52677. newTexture.hasAlpha = this.hasAlpha;
  52678. newTexture.level = this.level;
  52679. // Mirror Texture
  52680. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52681. if (this.renderList) {
  52682. newTexture.renderList = this.renderList.slice(0);
  52683. }
  52684. return newTexture;
  52685. };
  52686. MirrorTexture.prototype.serialize = function () {
  52687. if (!this.name) {
  52688. return null;
  52689. }
  52690. var serializationObject = _super.prototype.serialize.call(this);
  52691. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52692. return serializationObject;
  52693. };
  52694. return MirrorTexture;
  52695. }(BABYLON.RenderTargetTexture));
  52696. BABYLON.MirrorTexture = MirrorTexture;
  52697. })(BABYLON || (BABYLON = {}));
  52698. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52699. var BABYLON;
  52700. (function (BABYLON) {
  52701. /**
  52702. * Creates a refraction texture used by refraction channel of the standard material.
  52703. * @param name the texture name
  52704. * @param size size of the underlying texture
  52705. * @param scene root scene
  52706. */
  52707. var RefractionTexture = /** @class */ (function (_super) {
  52708. __extends(RefractionTexture, _super);
  52709. function RefractionTexture(name, size, scene, generateMipMaps) {
  52710. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52711. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52712. _this.depth = 2.0;
  52713. _this.onBeforeRenderObservable.add(function () {
  52714. scene.clipPlane = _this.refractionPlane;
  52715. });
  52716. _this.onAfterRenderObservable.add(function () {
  52717. delete scene.clipPlane;
  52718. });
  52719. return _this;
  52720. }
  52721. RefractionTexture.prototype.clone = function () {
  52722. var scene = this.getScene();
  52723. if (!scene) {
  52724. return this;
  52725. }
  52726. var textureSize = this.getSize();
  52727. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52728. // Base texture
  52729. newTexture.hasAlpha = this.hasAlpha;
  52730. newTexture.level = this.level;
  52731. // Refraction Texture
  52732. newTexture.refractionPlane = this.refractionPlane.clone();
  52733. if (this.renderList) {
  52734. newTexture.renderList = this.renderList.slice(0);
  52735. }
  52736. newTexture.depth = this.depth;
  52737. return newTexture;
  52738. };
  52739. RefractionTexture.prototype.serialize = function () {
  52740. if (!this.name) {
  52741. return null;
  52742. }
  52743. var serializationObject = _super.prototype.serialize.call(this);
  52744. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52745. serializationObject.depth = this.depth;
  52746. return serializationObject;
  52747. };
  52748. return RefractionTexture;
  52749. }(BABYLON.RenderTargetTexture));
  52750. BABYLON.RefractionTexture = RefractionTexture;
  52751. })(BABYLON || (BABYLON = {}));
  52752. //# sourceMappingURL=babylon.refractionTexture.js.map
  52753. var BABYLON;
  52754. (function (BABYLON) {
  52755. var DynamicTexture = /** @class */ (function (_super) {
  52756. __extends(DynamicTexture, _super);
  52757. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52758. if (scene === void 0) { scene = null; }
  52759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52760. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52761. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52762. _this.name = name;
  52763. _this._engine = _this.getScene().getEngine();
  52764. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52765. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52766. _this._generateMipMaps = generateMipMaps;
  52767. if (options.getContext) {
  52768. _this._canvas = options;
  52769. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52770. }
  52771. else {
  52772. _this._canvas = document.createElement("canvas");
  52773. if (options.width) {
  52774. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52775. }
  52776. else {
  52777. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52778. }
  52779. }
  52780. var textureSize = _this.getSize();
  52781. _this._canvas.width = textureSize.width;
  52782. _this._canvas.height = textureSize.height;
  52783. _this._context = _this._canvas.getContext("2d");
  52784. return _this;
  52785. }
  52786. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52787. get: function () {
  52788. return true;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. DynamicTexture.prototype._recreate = function (textureSize) {
  52794. this._canvas.width = textureSize.width;
  52795. this._canvas.height = textureSize.height;
  52796. this.releaseInternalTexture();
  52797. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52798. };
  52799. DynamicTexture.prototype.scale = function (ratio) {
  52800. var textureSize = this.getSize();
  52801. textureSize.width *= ratio;
  52802. textureSize.height *= ratio;
  52803. this._recreate(textureSize);
  52804. };
  52805. DynamicTexture.prototype.scaleTo = function (width, height) {
  52806. var textureSize = this.getSize();
  52807. textureSize.width = width;
  52808. textureSize.height = height;
  52809. this._recreate(textureSize);
  52810. };
  52811. DynamicTexture.prototype.getContext = function () {
  52812. return this._context;
  52813. };
  52814. DynamicTexture.prototype.clear = function () {
  52815. var size = this.getSize();
  52816. this._context.fillRect(0, 0, size.width, size.height);
  52817. };
  52818. DynamicTexture.prototype.update = function (invertY) {
  52819. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52820. };
  52821. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52822. if (update === void 0) { update = true; }
  52823. var size = this.getSize();
  52824. if (clearColor) {
  52825. this._context.fillStyle = clearColor;
  52826. this._context.fillRect(0, 0, size.width, size.height);
  52827. }
  52828. this._context.font = font;
  52829. if (x === null || x === undefined) {
  52830. var textSize = this._context.measureText(text);
  52831. x = (size.width - textSize.width) / 2;
  52832. }
  52833. if (y === null || y === undefined) {
  52834. var fontSize = parseInt((font.replace(/\D/g, '')));
  52835. ;
  52836. y = (size.height / 2) + (fontSize / 3.65);
  52837. }
  52838. this._context.fillStyle = color;
  52839. this._context.fillText(text, x, y);
  52840. if (update) {
  52841. this.update(invertY);
  52842. }
  52843. };
  52844. DynamicTexture.prototype.clone = function () {
  52845. var scene = this.getScene();
  52846. if (!scene) {
  52847. return this;
  52848. }
  52849. var textureSize = this.getSize();
  52850. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52851. // Base texture
  52852. newTexture.hasAlpha = this.hasAlpha;
  52853. newTexture.level = this.level;
  52854. // Dynamic Texture
  52855. newTexture.wrapU = this.wrapU;
  52856. newTexture.wrapV = this.wrapV;
  52857. return newTexture;
  52858. };
  52859. DynamicTexture.prototype._rebuild = function () {
  52860. this.update();
  52861. };
  52862. return DynamicTexture;
  52863. }(BABYLON.Texture));
  52864. BABYLON.DynamicTexture = DynamicTexture;
  52865. })(BABYLON || (BABYLON = {}));
  52866. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52867. var BABYLON;
  52868. (function (BABYLON) {
  52869. var VideoTexture = /** @class */ (function (_super) {
  52870. __extends(VideoTexture, _super);
  52871. /**
  52872. * Creates a video texture.
  52873. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52874. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52875. * @param {BABYLON.Scene} scene is obviously the current scene.
  52876. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52877. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52878. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52879. */
  52880. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52881. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52882. if (invertY === void 0) { invertY = false; }
  52883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52884. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52885. _this._autoLaunch = true;
  52886. var urls = null;
  52887. _this.name = name;
  52888. if (urlsOrVideo instanceof HTMLVideoElement) {
  52889. _this.video = urlsOrVideo;
  52890. }
  52891. else {
  52892. urls = urlsOrVideo;
  52893. _this.video = document.createElement("video");
  52894. _this.video.autoplay = false;
  52895. _this.video.loop = true;
  52896. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52897. }
  52898. _this._engine = _this.getScene().getEngine();
  52899. _this._generateMipMaps = generateMipMaps;
  52900. _this._samplingMode = samplingMode;
  52901. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52902. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52903. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52904. }
  52905. else {
  52906. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52907. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52908. _this._generateMipMaps = false;
  52909. }
  52910. if (urls) {
  52911. _this.video.addEventListener("canplay", function () {
  52912. if (_this._texture === undefined) {
  52913. _this._createTexture();
  52914. }
  52915. });
  52916. urls.forEach(function (url) {
  52917. var source = document.createElement("source");
  52918. source.src = url;
  52919. _this.video.appendChild(source);
  52920. });
  52921. }
  52922. else {
  52923. _this._createTexture();
  52924. }
  52925. _this._lastUpdate = BABYLON.Tools.Now;
  52926. return _this;
  52927. }
  52928. VideoTexture.prototype.__setTextureReady = function () {
  52929. if (this._texture) {
  52930. this._texture.isReady = true;
  52931. }
  52932. };
  52933. VideoTexture.prototype._createTexture = function () {
  52934. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52935. if (this._autoLaunch) {
  52936. this._autoLaunch = false;
  52937. this.video.play();
  52938. }
  52939. this._setTextureReady = this.__setTextureReady.bind(this);
  52940. this.video.addEventListener("playing", this._setTextureReady);
  52941. };
  52942. VideoTexture.prototype._rebuild = function () {
  52943. this.update();
  52944. };
  52945. VideoTexture.prototype.update = function () {
  52946. var now = BABYLON.Tools.Now;
  52947. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52948. return false;
  52949. }
  52950. this._lastUpdate = now;
  52951. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52952. return true;
  52953. };
  52954. VideoTexture.prototype.dispose = function () {
  52955. _super.prototype.dispose.call(this);
  52956. this.video.removeEventListener("playing", this._setTextureReady);
  52957. };
  52958. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52959. var video = document.createElement("video");
  52960. var constraintsDeviceId;
  52961. if (constraints && constraints.deviceId) {
  52962. constraintsDeviceId = {
  52963. exact: constraints.deviceId
  52964. };
  52965. }
  52966. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52967. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52968. if (navigator.getUserMedia) {
  52969. navigator.getUserMedia({
  52970. video: {
  52971. deviceId: constraintsDeviceId,
  52972. width: {
  52973. min: (constraints && constraints.minWidth) || 256,
  52974. max: (constraints && constraints.maxWidth) || 640
  52975. },
  52976. height: {
  52977. min: (constraints && constraints.minHeight) || 256,
  52978. max: (constraints && constraints.maxHeight) || 480
  52979. }
  52980. }
  52981. }, function (stream) {
  52982. if (video.mozSrcObject !== undefined) {
  52983. video.mozSrcObject = stream;
  52984. }
  52985. else {
  52986. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52987. }
  52988. video.play();
  52989. if (onReady) {
  52990. onReady(new VideoTexture("video", video, scene, true, true));
  52991. }
  52992. }, function (e) {
  52993. BABYLON.Tools.Error(e.name);
  52994. });
  52995. }
  52996. };
  52997. return VideoTexture;
  52998. }(BABYLON.Texture));
  52999. BABYLON.VideoTexture = VideoTexture;
  53000. })(BABYLON || (BABYLON = {}));
  53001. //# sourceMappingURL=babylon.videoTexture.js.map
  53002. var BABYLON;
  53003. (function (BABYLON) {
  53004. var RawTexture = /** @class */ (function (_super) {
  53005. __extends(RawTexture, _super);
  53006. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  53007. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53008. if (invertY === void 0) { invertY = false; }
  53009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53010. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53011. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  53012. _this.format = format;
  53013. _this._engine = scene.getEngine();
  53014. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  53015. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53016. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53017. return _this;
  53018. }
  53019. RawTexture.prototype.update = function (data) {
  53020. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  53021. };
  53022. // Statics
  53023. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53024. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53025. if (invertY === void 0) { invertY = false; }
  53026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53027. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53028. };
  53029. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53030. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53031. if (invertY === void 0) { invertY = false; }
  53032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53033. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53034. };
  53035. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53036. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53037. if (invertY === void 0) { invertY = false; }
  53038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53040. };
  53041. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  53042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53043. if (invertY === void 0) { invertY = false; }
  53044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53045. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53046. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  53047. };
  53048. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  53049. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53050. if (invertY === void 0) { invertY = false; }
  53051. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53052. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53053. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  53054. };
  53055. return RawTexture;
  53056. }(BABYLON.Texture));
  53057. BABYLON.RawTexture = RawTexture;
  53058. })(BABYLON || (BABYLON = {}));
  53059. //# sourceMappingURL=babylon.rawTexture.js.map
  53060. var BABYLON;
  53061. (function (BABYLON) {
  53062. var PostProcess = /** @class */ (function () {
  53063. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  53064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  53065. if (defines === void 0) { defines = null; }
  53066. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53067. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  53068. if (blockCompilation === void 0) { blockCompilation = false; }
  53069. this.name = name;
  53070. this.width = -1;
  53071. this.height = -1;
  53072. this.autoClear = true;
  53073. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  53074. this.animations = new Array();
  53075. /*
  53076. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  53077. Can only be used on a single postprocess or on the last one of a chain.
  53078. */
  53079. this.enablePixelPerfectMode = false;
  53080. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  53081. this.alwaysForcePOT = false;
  53082. this.samples = 1;
  53083. this.adaptScaleToCurrentViewport = false;
  53084. this._reusable = false;
  53085. this._textures = new BABYLON.SmartArray(2);
  53086. this._currentRenderTextureInd = 0;
  53087. this._scaleRatio = new BABYLON.Vector2(1, 1);
  53088. this._texelSize = BABYLON.Vector2.Zero();
  53089. // Events
  53090. /**
  53091. * An event triggered when the postprocess is activated.
  53092. * @type {BABYLON.Observable}
  53093. */
  53094. this.onActivateObservable = new BABYLON.Observable();
  53095. /**
  53096. * An event triggered when the postprocess changes its size.
  53097. * @type {BABYLON.Observable}
  53098. */
  53099. this.onSizeChangedObservable = new BABYLON.Observable();
  53100. /**
  53101. * An event triggered when the postprocess applies its effect.
  53102. * @type {BABYLON.Observable}
  53103. */
  53104. this.onApplyObservable = new BABYLON.Observable();
  53105. /**
  53106. * An event triggered before rendering the postprocess
  53107. * @type {BABYLON.Observable}
  53108. */
  53109. this.onBeforeRenderObservable = new BABYLON.Observable();
  53110. /**
  53111. * An event triggered after rendering the postprocess
  53112. * @type {BABYLON.Observable}
  53113. */
  53114. this.onAfterRenderObservable = new BABYLON.Observable();
  53115. if (camera != null) {
  53116. this._camera = camera;
  53117. this._scene = camera.getScene();
  53118. camera.attachPostProcess(this);
  53119. this._engine = this._scene.getEngine();
  53120. this._scene.postProcesses.push(this);
  53121. }
  53122. else if (engine) {
  53123. this._engine = engine;
  53124. this._engine.postProcesses.push(this);
  53125. }
  53126. this._options = options;
  53127. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53128. this._reusable = reusable || false;
  53129. this._textureType = textureType;
  53130. this._samplers = samplers || [];
  53131. this._samplers.push("textureSampler");
  53132. this._fragmentUrl = fragmentUrl;
  53133. this._vertexUrl = vertexUrl;
  53134. this._parameters = parameters || [];
  53135. this._parameters.push("scale");
  53136. this._indexParameters = indexParameters;
  53137. if (!blockCompilation) {
  53138. this.updateEffect(defines);
  53139. }
  53140. }
  53141. Object.defineProperty(PostProcess.prototype, "onActivate", {
  53142. set: function (callback) {
  53143. if (this._onActivateObserver) {
  53144. this.onActivateObservable.remove(this._onActivateObserver);
  53145. }
  53146. if (callback) {
  53147. this._onActivateObserver = this.onActivateObservable.add(callback);
  53148. }
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53154. set: function (callback) {
  53155. if (this._onSizeChangedObserver) {
  53156. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53157. }
  53158. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53159. },
  53160. enumerable: true,
  53161. configurable: true
  53162. });
  53163. Object.defineProperty(PostProcess.prototype, "onApply", {
  53164. set: function (callback) {
  53165. if (this._onApplyObserver) {
  53166. this.onApplyObservable.remove(this._onApplyObserver);
  53167. }
  53168. this._onApplyObserver = this.onApplyObservable.add(callback);
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53174. set: function (callback) {
  53175. if (this._onBeforeRenderObserver) {
  53176. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53177. }
  53178. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53179. },
  53180. enumerable: true,
  53181. configurable: true
  53182. });
  53183. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53184. set: function (callback) {
  53185. if (this._onAfterRenderObserver) {
  53186. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53187. }
  53188. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53189. },
  53190. enumerable: true,
  53191. configurable: true
  53192. });
  53193. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53194. get: function () {
  53195. return this._textures.data[this._currentRenderTextureInd];
  53196. },
  53197. set: function (value) {
  53198. this._forcedOutputTexture = value;
  53199. },
  53200. enumerable: true,
  53201. configurable: true
  53202. });
  53203. PostProcess.prototype.getCamera = function () {
  53204. return this._camera;
  53205. };
  53206. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53207. get: function () {
  53208. if (this._shareOutputWithPostProcess) {
  53209. return this._shareOutputWithPostProcess.texelSize;
  53210. }
  53211. if (this._forcedOutputTexture) {
  53212. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53213. }
  53214. return this._texelSize;
  53215. },
  53216. enumerable: true,
  53217. configurable: true
  53218. });
  53219. PostProcess.prototype.getEngine = function () {
  53220. return this._engine;
  53221. };
  53222. PostProcess.prototype.getEffect = function () {
  53223. return this._effect;
  53224. };
  53225. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53226. this._disposeTextures();
  53227. this._shareOutputWithPostProcess = postProcess;
  53228. return this;
  53229. };
  53230. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53231. if (defines === void 0) { defines = null; }
  53232. if (uniforms === void 0) { uniforms = null; }
  53233. if (samplers === void 0) { samplers = null; }
  53234. 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);
  53235. };
  53236. PostProcess.prototype.isReusable = function () {
  53237. return this._reusable;
  53238. };
  53239. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53240. PostProcess.prototype.markTextureDirty = function () {
  53241. this.width = -1;
  53242. };
  53243. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53244. var _this = this;
  53245. if (sourceTexture === void 0) { sourceTexture = null; }
  53246. camera = camera || this._camera;
  53247. var scene = camera.getScene();
  53248. var engine = scene.getEngine();
  53249. var maxSize = engine.getCaps().maxTextureSize;
  53250. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53251. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53252. var desiredWidth = (this._options.width || requiredWidth);
  53253. var desiredHeight = this._options.height || requiredHeight;
  53254. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53255. if (this.adaptScaleToCurrentViewport) {
  53256. var currentViewport = engine.currentViewport;
  53257. if (currentViewport) {
  53258. desiredWidth *= currentViewport.width;
  53259. desiredHeight *= currentViewport.height;
  53260. }
  53261. }
  53262. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53263. if (!this._options.width) {
  53264. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53265. }
  53266. if (!this._options.height) {
  53267. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53268. }
  53269. }
  53270. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53271. if (this._textures.length > 0) {
  53272. for (var i = 0; i < this._textures.length; i++) {
  53273. this._engine._releaseTexture(this._textures.data[i]);
  53274. }
  53275. this._textures.reset();
  53276. }
  53277. this.width = desiredWidth;
  53278. this.height = desiredHeight;
  53279. var textureSize = { width: this.width, height: this.height };
  53280. var textureOptions = {
  53281. generateMipMaps: false,
  53282. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53283. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53284. samplingMode: this.renderTargetSamplingMode,
  53285. type: this._textureType
  53286. };
  53287. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53288. if (this._reusable) {
  53289. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53290. }
  53291. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53292. this.onSizeChangedObservable.notifyObservers(this);
  53293. }
  53294. this._textures.forEach(function (texture) {
  53295. if (texture.samples !== _this.samples) {
  53296. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53297. }
  53298. });
  53299. }
  53300. var target;
  53301. if (this._shareOutputWithPostProcess) {
  53302. target = this._shareOutputWithPostProcess.outputTexture;
  53303. }
  53304. else if (this._forcedOutputTexture) {
  53305. target = this._forcedOutputTexture;
  53306. this.width = this._forcedOutputTexture.width;
  53307. this.height = this._forcedOutputTexture.height;
  53308. }
  53309. else {
  53310. target = this.outputTexture;
  53311. }
  53312. if (this.enablePixelPerfectMode) {
  53313. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53314. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53315. }
  53316. else {
  53317. this._scaleRatio.copyFromFloats(1, 1);
  53318. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53319. }
  53320. this.onActivateObservable.notifyObservers(camera);
  53321. // Clear
  53322. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53323. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53324. }
  53325. if (this._reusable) {
  53326. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53327. }
  53328. };
  53329. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53330. get: function () {
  53331. return this._effect.isSupported;
  53332. },
  53333. enumerable: true,
  53334. configurable: true
  53335. });
  53336. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53337. get: function () {
  53338. if (this._shareOutputWithPostProcess) {
  53339. return this._shareOutputWithPostProcess.aspectRatio;
  53340. }
  53341. if (this._forcedOutputTexture) {
  53342. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53343. }
  53344. return this.width / this.height;
  53345. },
  53346. enumerable: true,
  53347. configurable: true
  53348. });
  53349. /**
  53350. * Get a value indicating if the post-process is ready to be used
  53351. * @returns true if the post-process is ready (shader is compiled)
  53352. */
  53353. PostProcess.prototype.isReady = function () {
  53354. return this._effect && this._effect.isReady();
  53355. };
  53356. PostProcess.prototype.apply = function () {
  53357. // Check
  53358. if (!this._effect || !this._effect.isReady())
  53359. return null;
  53360. // States
  53361. this._engine.enableEffect(this._effect);
  53362. this._engine.setState(false);
  53363. this._engine.setDepthBuffer(false);
  53364. this._engine.setDepthWrite(false);
  53365. // Alpha
  53366. this._engine.setAlphaMode(this.alphaMode);
  53367. if (this.alphaConstants) {
  53368. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53369. }
  53370. // Texture
  53371. var source;
  53372. if (this._shareOutputWithPostProcess) {
  53373. source = this._shareOutputWithPostProcess.outputTexture;
  53374. }
  53375. else if (this._forcedOutputTexture) {
  53376. source = this._forcedOutputTexture;
  53377. }
  53378. else {
  53379. source = this.outputTexture;
  53380. }
  53381. this._effect._bindTexture("textureSampler", source);
  53382. // Parameters
  53383. this._effect.setVector2("scale", this._scaleRatio);
  53384. this.onApplyObservable.notifyObservers(this._effect);
  53385. return this._effect;
  53386. };
  53387. PostProcess.prototype._disposeTextures = function () {
  53388. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53389. return;
  53390. }
  53391. if (this._textures.length > 0) {
  53392. for (var i = 0; i < this._textures.length; i++) {
  53393. this._engine._releaseTexture(this._textures.data[i]);
  53394. }
  53395. }
  53396. this._textures.dispose();
  53397. };
  53398. PostProcess.prototype.dispose = function (camera) {
  53399. camera = camera || this._camera;
  53400. this._disposeTextures();
  53401. if (this._scene) {
  53402. var index_1 = this._scene.postProcesses.indexOf(this);
  53403. if (index_1 !== -1) {
  53404. this._scene.postProcesses.splice(index_1, 1);
  53405. }
  53406. }
  53407. else {
  53408. var index_2 = this._engine.postProcesses.indexOf(this);
  53409. if (index_2 !== -1) {
  53410. this._engine.postProcesses.splice(index_2, 1);
  53411. }
  53412. }
  53413. if (!camera) {
  53414. return;
  53415. }
  53416. camera.detachPostProcess(this);
  53417. var index = camera._postProcesses.indexOf(this);
  53418. if (index === 0 && camera._postProcesses.length > 0) {
  53419. this._camera._postProcesses[0].markTextureDirty();
  53420. }
  53421. this.onActivateObservable.clear();
  53422. this.onAfterRenderObservable.clear();
  53423. this.onApplyObservable.clear();
  53424. this.onBeforeRenderObservable.clear();
  53425. this.onSizeChangedObservable.clear();
  53426. };
  53427. return PostProcess;
  53428. }());
  53429. BABYLON.PostProcess = PostProcess;
  53430. })(BABYLON || (BABYLON = {}));
  53431. //# sourceMappingURL=babylon.postProcess.js.map
  53432. var BABYLON;
  53433. (function (BABYLON) {
  53434. var PassPostProcess = /** @class */ (function (_super) {
  53435. __extends(PassPostProcess, _super);
  53436. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53437. if (camera === void 0) { camera = null; }
  53438. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53439. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53440. }
  53441. return PassPostProcess;
  53442. }(BABYLON.PostProcess));
  53443. BABYLON.PassPostProcess = PassPostProcess;
  53444. })(BABYLON || (BABYLON = {}));
  53445. //# sourceMappingURL=babylon.passPostProcess.js.map
  53446. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53447. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53448. s = arguments[i];
  53449. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53450. t[p] = s[p];
  53451. }
  53452. return t;
  53453. };
  53454. var BABYLON;
  53455. (function (BABYLON) {
  53456. var ShadowGenerator = /** @class */ (function () {
  53457. /**
  53458. * Creates a ShadowGenerator object.
  53459. * A ShadowGenerator is the required tool to use the shadows.
  53460. * Each light casting shadows needs to use its own ShadowGenerator.
  53461. * Required parameters :
  53462. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53463. * - `light`: the light object generating the shadows.
  53464. * - `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.
  53465. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53466. */
  53467. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53468. // Members
  53469. this._bias = 0.00005;
  53470. this._blurBoxOffset = 1;
  53471. this._blurScale = 2;
  53472. this._blurKernel = 1;
  53473. this._useKernelBlur = false;
  53474. this._filter = ShadowGenerator.FILTER_NONE;
  53475. this._darkness = 0;
  53476. this._transparencyShadow = false;
  53477. /**
  53478. * Controls the extent to which the shadows fade out at the edge of the frustum
  53479. * Used only by directionals and spots
  53480. */
  53481. this.frustumEdgeFalloff = 0;
  53482. this.forceBackFacesOnly = false;
  53483. this._lightDirection = BABYLON.Vector3.Zero();
  53484. this._viewMatrix = BABYLON.Matrix.Zero();
  53485. this._projectionMatrix = BABYLON.Matrix.Zero();
  53486. this._transformMatrix = BABYLON.Matrix.Zero();
  53487. this._currentFaceIndex = 0;
  53488. this._currentFaceIndexCache = 0;
  53489. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53490. this._mapSize = mapSize;
  53491. this._light = light;
  53492. this._scene = light.getScene();
  53493. light._shadowGenerator = this;
  53494. // Texture type fallback from float to int if not supported.
  53495. var caps = this._scene.getEngine().getCaps();
  53496. if (!useFullFloatFirst) {
  53497. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53498. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53499. }
  53500. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53501. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53502. }
  53503. else {
  53504. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53505. }
  53506. }
  53507. else {
  53508. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53509. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53510. }
  53511. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53512. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53513. }
  53514. else {
  53515. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53516. }
  53517. }
  53518. this._initializeGenerator();
  53519. }
  53520. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53521. // Static
  53522. get: function () {
  53523. return ShadowGenerator._FILTER_NONE;
  53524. },
  53525. enumerable: true,
  53526. configurable: true
  53527. });
  53528. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53529. get: function () {
  53530. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53536. get: function () {
  53537. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53538. },
  53539. enumerable: true,
  53540. configurable: true
  53541. });
  53542. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53543. get: function () {
  53544. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53545. },
  53546. enumerable: true,
  53547. configurable: true
  53548. });
  53549. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53550. get: function () {
  53551. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53552. },
  53553. enumerable: true,
  53554. configurable: true
  53555. });
  53556. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53557. get: function () {
  53558. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53559. },
  53560. enumerable: true,
  53561. configurable: true
  53562. });
  53563. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53564. get: function () {
  53565. return this._bias;
  53566. },
  53567. set: function (bias) {
  53568. this._bias = bias;
  53569. },
  53570. enumerable: true,
  53571. configurable: true
  53572. });
  53573. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53574. get: function () {
  53575. return this._blurBoxOffset;
  53576. },
  53577. set: function (value) {
  53578. if (this._blurBoxOffset === value) {
  53579. return;
  53580. }
  53581. this._blurBoxOffset = value;
  53582. this._disposeBlurPostProcesses();
  53583. },
  53584. enumerable: true,
  53585. configurable: true
  53586. });
  53587. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53588. get: function () {
  53589. return this._blurScale;
  53590. },
  53591. set: function (value) {
  53592. if (this._blurScale === value) {
  53593. return;
  53594. }
  53595. this._blurScale = value;
  53596. this._disposeBlurPostProcesses();
  53597. },
  53598. enumerable: true,
  53599. configurable: true
  53600. });
  53601. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53602. get: function () {
  53603. return this._blurKernel;
  53604. },
  53605. set: function (value) {
  53606. if (this._blurKernel === value) {
  53607. return;
  53608. }
  53609. this._blurKernel = value;
  53610. this._disposeBlurPostProcesses();
  53611. },
  53612. enumerable: true,
  53613. configurable: true
  53614. });
  53615. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53616. get: function () {
  53617. return this._useKernelBlur;
  53618. },
  53619. set: function (value) {
  53620. if (this._useKernelBlur === value) {
  53621. return;
  53622. }
  53623. this._useKernelBlur = value;
  53624. this._disposeBlurPostProcesses();
  53625. },
  53626. enumerable: true,
  53627. configurable: true
  53628. });
  53629. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53630. get: function () {
  53631. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53632. },
  53633. set: function (value) {
  53634. this._depthScale = value;
  53635. },
  53636. enumerable: true,
  53637. configurable: true
  53638. });
  53639. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53640. get: function () {
  53641. return this._filter;
  53642. },
  53643. set: function (value) {
  53644. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53645. if (this._light.needCube()) {
  53646. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53647. this.useExponentialShadowMap = true;
  53648. return;
  53649. }
  53650. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53651. this.useCloseExponentialShadowMap = true;
  53652. return;
  53653. }
  53654. }
  53655. if (this._filter === value) {
  53656. return;
  53657. }
  53658. this._filter = value;
  53659. this._disposeBlurPostProcesses();
  53660. this._applyFilterValues();
  53661. this._light._markMeshesAsLightDirty();
  53662. },
  53663. enumerable: true,
  53664. configurable: true
  53665. });
  53666. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53667. get: function () {
  53668. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53669. },
  53670. set: function (value) {
  53671. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53672. return;
  53673. }
  53674. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53675. },
  53676. enumerable: true,
  53677. configurable: true
  53678. });
  53679. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53680. get: function () {
  53681. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53682. return this.useExponentialShadowMap;
  53683. },
  53684. set: function (value) {
  53685. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53686. this.useExponentialShadowMap = value;
  53687. },
  53688. enumerable: true,
  53689. configurable: true
  53690. });
  53691. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53692. get: function () {
  53693. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53694. return this.useBlurExponentialShadowMap;
  53695. },
  53696. set: function (value) {
  53697. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53698. this.useBlurExponentialShadowMap = value;
  53699. },
  53700. enumerable: true,
  53701. configurable: true
  53702. });
  53703. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53704. get: function () {
  53705. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53706. },
  53707. set: function (value) {
  53708. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53709. return;
  53710. }
  53711. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53712. },
  53713. enumerable: true,
  53714. configurable: true
  53715. });
  53716. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53717. get: function () {
  53718. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53719. },
  53720. set: function (value) {
  53721. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53722. return;
  53723. }
  53724. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53725. },
  53726. enumerable: true,
  53727. configurable: true
  53728. });
  53729. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53730. get: function () {
  53731. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53732. },
  53733. set: function (value) {
  53734. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53735. return;
  53736. }
  53737. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53738. },
  53739. enumerable: true,
  53740. configurable: true
  53741. });
  53742. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53743. get: function () {
  53744. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53745. },
  53746. set: function (value) {
  53747. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53748. return;
  53749. }
  53750. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53751. },
  53752. enumerable: true,
  53753. configurable: true
  53754. });
  53755. /**
  53756. * Returns the darkness value (float).
  53757. */
  53758. ShadowGenerator.prototype.getDarkness = function () {
  53759. return this._darkness;
  53760. };
  53761. /**
  53762. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53763. * Returns the ShadowGenerator.
  53764. */
  53765. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53766. if (darkness >= 1.0)
  53767. this._darkness = 1.0;
  53768. else if (darkness <= 0.0)
  53769. this._darkness = 0.0;
  53770. else
  53771. this._darkness = darkness;
  53772. return this;
  53773. };
  53774. /**
  53775. * Sets the ability to have transparent shadow (boolean).
  53776. * Returns the ShadowGenerator.
  53777. */
  53778. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53779. this._transparencyShadow = hasShadow;
  53780. return this;
  53781. };
  53782. /**
  53783. * Returns a RenderTargetTexture object : the shadow map texture.
  53784. */
  53785. ShadowGenerator.prototype.getShadowMap = function () {
  53786. return this._shadowMap;
  53787. };
  53788. /**
  53789. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53790. */
  53791. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53792. if (this._shadowMap2) {
  53793. return this._shadowMap2;
  53794. }
  53795. return this._shadowMap;
  53796. };
  53797. /**
  53798. * Helper function to add a mesh and its descendants to the list of shadow casters
  53799. * @param mesh Mesh to add
  53800. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53801. */
  53802. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53803. if (includeDescendants === void 0) { includeDescendants = true; }
  53804. if (!this._shadowMap) {
  53805. return this;
  53806. }
  53807. if (!this._shadowMap.renderList) {
  53808. this._shadowMap.renderList = [];
  53809. }
  53810. this._shadowMap.renderList.push(mesh);
  53811. if (includeDescendants) {
  53812. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53813. }
  53814. return this;
  53815. var _a;
  53816. };
  53817. /**
  53818. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53819. * @param mesh Mesh to remove
  53820. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53821. */
  53822. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53823. if (includeDescendants === void 0) { includeDescendants = true; }
  53824. if (!this._shadowMap || !this._shadowMap.renderList) {
  53825. return this;
  53826. }
  53827. var index = this._shadowMap.renderList.indexOf(mesh);
  53828. if (index !== -1) {
  53829. this._shadowMap.renderList.splice(index, 1);
  53830. }
  53831. if (includeDescendants) {
  53832. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53833. var child = _a[_i];
  53834. this.removeShadowCaster(child);
  53835. }
  53836. }
  53837. return this;
  53838. };
  53839. /**
  53840. * Returns the associated light object.
  53841. */
  53842. ShadowGenerator.prototype.getLight = function () {
  53843. return this._light;
  53844. };
  53845. ShadowGenerator.prototype._initializeGenerator = function () {
  53846. this._light._markMeshesAsLightDirty();
  53847. this._initializeShadowMap();
  53848. };
  53849. ShadowGenerator.prototype._initializeShadowMap = function () {
  53850. var _this = this;
  53851. // Render target
  53852. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53853. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53854. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53855. this._shadowMap.anisotropicFilteringLevel = 1;
  53856. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53857. this._shadowMap.renderParticles = false;
  53858. this._shadowMap.ignoreCameraViewport = true;
  53859. // Record Face Index before render.
  53860. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53861. _this._currentFaceIndex = faceIndex;
  53862. });
  53863. // Custom render function.
  53864. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53865. // Blur if required afer render.
  53866. this._shadowMap.onAfterUnbindObservable.add(function () {
  53867. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53868. return;
  53869. }
  53870. var shadowMap = _this.getShadowMapForRendering();
  53871. if (shadowMap) {
  53872. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53873. }
  53874. });
  53875. // Clear according to the chosen filter.
  53876. this._shadowMap.onClearObservable.add(function (engine) {
  53877. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53878. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53879. }
  53880. else {
  53881. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53882. }
  53883. });
  53884. };
  53885. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53886. var _this = this;
  53887. var engine = this._scene.getEngine();
  53888. var targetSize = this._mapSize / this.blurScale;
  53889. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53890. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53891. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53892. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53893. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53894. }
  53895. if (this.useKernelBlur) {
  53896. 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);
  53897. this._kernelBlurXPostprocess.width = targetSize;
  53898. this._kernelBlurXPostprocess.height = targetSize;
  53899. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53900. effect.setTexture("textureSampler", _this._shadowMap);
  53901. });
  53902. 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);
  53903. this._kernelBlurXPostprocess.autoClear = false;
  53904. this._kernelBlurYPostprocess.autoClear = false;
  53905. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53906. this._kernelBlurXPostprocess.packedFloat = true;
  53907. this._kernelBlurYPostprocess.packedFloat = true;
  53908. }
  53909. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53910. }
  53911. else {
  53912. 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);
  53913. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53914. effect.setFloat2("screenSize", targetSize, targetSize);
  53915. effect.setTexture("textureSampler", _this._shadowMap);
  53916. });
  53917. this._boxBlurPostprocess.autoClear = false;
  53918. this._blurPostProcesses = [this._boxBlurPostprocess];
  53919. }
  53920. };
  53921. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53922. var index;
  53923. var engine = this._scene.getEngine();
  53924. if (depthOnlySubMeshes.length) {
  53925. engine.setColorWrite(false);
  53926. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53927. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53928. }
  53929. engine.setColorWrite(true);
  53930. }
  53931. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53932. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53933. }
  53934. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53935. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53936. }
  53937. if (this._transparencyShadow) {
  53938. for (index = 0; index < transparentSubMeshes.length; index++) {
  53939. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53940. }
  53941. }
  53942. };
  53943. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53944. var _this = this;
  53945. var mesh = subMesh.getRenderingMesh();
  53946. var scene = this._scene;
  53947. var engine = scene.getEngine();
  53948. var material = subMesh.getMaterial();
  53949. if (!material) {
  53950. return;
  53951. }
  53952. // Culling
  53953. engine.setState(material.backFaceCulling);
  53954. // Managing instances
  53955. var batch = mesh._getInstancesRenderList(subMesh._id);
  53956. if (batch.mustReturn) {
  53957. return;
  53958. }
  53959. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53960. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53961. engine.enableEffect(this._effect);
  53962. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53963. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53964. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53965. this._effect.setVector3("lightPosition", this.getLight().position);
  53966. if (scene.activeCamera) {
  53967. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53968. }
  53969. // Alpha test
  53970. if (material && material.needAlphaTesting()) {
  53971. var alphaTexture = material.getAlphaTestTexture();
  53972. if (alphaTexture) {
  53973. this._effect.setTexture("diffuseSampler", alphaTexture);
  53974. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53975. }
  53976. }
  53977. // Bones
  53978. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53979. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53980. }
  53981. if (this.forceBackFacesOnly) {
  53982. engine.setState(true, 0, false, true);
  53983. }
  53984. // Draw
  53985. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53986. if (this.forceBackFacesOnly) {
  53987. engine.setState(true, 0, false, false);
  53988. }
  53989. }
  53990. else {
  53991. // Need to reset refresh rate of the shadowMap
  53992. if (this._shadowMap) {
  53993. this._shadowMap.resetRefreshCounter();
  53994. }
  53995. }
  53996. };
  53997. ShadowGenerator.prototype._applyFilterValues = function () {
  53998. if (!this._shadowMap) {
  53999. return;
  54000. }
  54001. if (this.filter === ShadowGenerator.FILTER_NONE) {
  54002. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  54003. }
  54004. else {
  54005. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54006. }
  54007. };
  54008. /**
  54009. * Force shader compilation including textures ready check
  54010. */
  54011. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  54012. var _this = this;
  54013. var localOptions = __assign({ useInstances: false }, options);
  54014. var shadowMap = this.getShadowMap();
  54015. if (!shadowMap) {
  54016. if (onCompiled) {
  54017. onCompiled(this);
  54018. }
  54019. return;
  54020. }
  54021. var renderList = shadowMap.renderList;
  54022. if (!renderList) {
  54023. if (onCompiled) {
  54024. onCompiled(this);
  54025. }
  54026. return;
  54027. }
  54028. var subMeshes = new Array();
  54029. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  54030. var mesh = renderList_1[_i];
  54031. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  54032. }
  54033. if (subMeshes.length === 0) {
  54034. if (onCompiled) {
  54035. onCompiled(this);
  54036. }
  54037. return;
  54038. }
  54039. var currentIndex = 0;
  54040. var checkReady = function () {
  54041. if (!_this._scene || !_this._scene.getEngine()) {
  54042. return;
  54043. }
  54044. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  54045. currentIndex++;
  54046. if (currentIndex >= subMeshes.length) {
  54047. if (onCompiled) {
  54048. onCompiled(_this);
  54049. }
  54050. return;
  54051. }
  54052. }
  54053. setTimeout(checkReady, 16);
  54054. };
  54055. checkReady();
  54056. };
  54057. /**
  54058. * Boolean : true when the ShadowGenerator is finally computed.
  54059. */
  54060. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  54061. var defines = [];
  54062. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  54063. defines.push("#define FLOAT");
  54064. }
  54065. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54066. defines.push("#define ESM");
  54067. }
  54068. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54069. var mesh = subMesh.getMesh();
  54070. var material = subMesh.getMaterial();
  54071. // Alpha test
  54072. if (material && material.needAlphaTesting()) {
  54073. var alphaTexture = material.getAlphaTestTexture();
  54074. if (alphaTexture) {
  54075. defines.push("#define ALPHATEST");
  54076. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54077. attribs.push(BABYLON.VertexBuffer.UVKind);
  54078. defines.push("#define UV1");
  54079. }
  54080. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54081. if (alphaTexture.coordinatesIndex === 1) {
  54082. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54083. defines.push("#define UV2");
  54084. }
  54085. }
  54086. }
  54087. }
  54088. // Bones
  54089. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54090. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54091. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54092. if (mesh.numBoneInfluencers > 4) {
  54093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54095. }
  54096. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54097. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54098. }
  54099. else {
  54100. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54101. }
  54102. // Instances
  54103. if (useInstances) {
  54104. defines.push("#define INSTANCES");
  54105. attribs.push("world0");
  54106. attribs.push("world1");
  54107. attribs.push("world2");
  54108. attribs.push("world3");
  54109. }
  54110. // Get correct effect
  54111. var join = defines.join("\n");
  54112. if (this._cachedDefines !== join) {
  54113. this._cachedDefines = join;
  54114. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  54115. }
  54116. if (!this._effect.isReady()) {
  54117. return false;
  54118. }
  54119. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54120. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  54121. this._initializeBlurRTTAndPostProcesses();
  54122. }
  54123. }
  54124. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  54125. return false;
  54126. }
  54127. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  54128. return false;
  54129. }
  54130. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  54131. return false;
  54132. }
  54133. return true;
  54134. };
  54135. /**
  54136. * This creates the defines related to the standard BJS materials.
  54137. */
  54138. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  54139. var scene = this._scene;
  54140. var light = this._light;
  54141. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54142. return;
  54143. }
  54144. defines["SHADOW" + lightIndex] = true;
  54145. if (this.usePoissonSampling) {
  54146. defines["SHADOWPCF" + lightIndex] = true;
  54147. }
  54148. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54149. defines["SHADOWESM" + lightIndex] = true;
  54150. }
  54151. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54152. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54153. }
  54154. if (light.needCube()) {
  54155. defines["SHADOWCUBE" + lightIndex] = true;
  54156. }
  54157. };
  54158. /**
  54159. * This binds shadow lights related to the standard BJS materials.
  54160. * It implies the unifroms available on the materials are the standard BJS ones.
  54161. */
  54162. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54163. var light = this._light;
  54164. var scene = this._scene;
  54165. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54166. return;
  54167. }
  54168. var camera = scene.activeCamera;
  54169. if (!camera) {
  54170. return;
  54171. }
  54172. var shadowMap = this.getShadowMap();
  54173. if (!shadowMap) {
  54174. return;
  54175. }
  54176. if (!light.needCube()) {
  54177. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54178. }
  54179. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54180. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54181. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54182. };
  54183. // Methods
  54184. /**
  54185. * Returns a Matrix object : the updated transformation matrix.
  54186. */
  54187. ShadowGenerator.prototype.getTransformMatrix = function () {
  54188. var scene = this._scene;
  54189. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54190. return this._transformMatrix;
  54191. }
  54192. this._currentRenderID = scene.getRenderId();
  54193. this._currentFaceIndexCache = this._currentFaceIndex;
  54194. var lightPosition = this._light.position;
  54195. if (this._light.computeTransformedInformation()) {
  54196. lightPosition = this._light.transformedPosition;
  54197. }
  54198. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54199. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54200. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54201. }
  54202. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54203. this._cachedPosition = lightPosition.clone();
  54204. this._cachedDirection = this._lightDirection.clone();
  54205. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54206. var shadowMap = this.getShadowMap();
  54207. if (shadowMap) {
  54208. var renderList = shadowMap.renderList;
  54209. if (renderList) {
  54210. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54211. }
  54212. }
  54213. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54214. }
  54215. return this._transformMatrix;
  54216. };
  54217. ShadowGenerator.prototype.recreateShadowMap = function () {
  54218. var shadowMap = this._shadowMap;
  54219. if (!shadowMap) {
  54220. return;
  54221. }
  54222. // Track render list.
  54223. var renderList = shadowMap.renderList;
  54224. // Clean up existing data.
  54225. this._disposeRTTandPostProcesses();
  54226. // Reinitializes.
  54227. this._initializeGenerator();
  54228. // Reaffect the filter to ensure a correct fallback if necessary.
  54229. this.filter = this.filter;
  54230. // Reaffect the filter.
  54231. this._applyFilterValues();
  54232. // Reaffect Render List.
  54233. this._shadowMap.renderList = renderList;
  54234. };
  54235. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54236. if (this._shadowMap2) {
  54237. this._shadowMap2.dispose();
  54238. this._shadowMap2 = null;
  54239. }
  54240. if (this._boxBlurPostprocess) {
  54241. this._boxBlurPostprocess.dispose();
  54242. this._boxBlurPostprocess = null;
  54243. }
  54244. if (this._kernelBlurXPostprocess) {
  54245. this._kernelBlurXPostprocess.dispose();
  54246. this._kernelBlurXPostprocess = null;
  54247. }
  54248. if (this._kernelBlurYPostprocess) {
  54249. this._kernelBlurYPostprocess.dispose();
  54250. this._kernelBlurYPostprocess = null;
  54251. }
  54252. this._blurPostProcesses = [];
  54253. };
  54254. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54255. if (this._shadowMap) {
  54256. this._shadowMap.dispose();
  54257. this._shadowMap = null;
  54258. }
  54259. this._disposeBlurPostProcesses();
  54260. };
  54261. /**
  54262. * Disposes the ShadowGenerator.
  54263. * Returns nothing.
  54264. */
  54265. ShadowGenerator.prototype.dispose = function () {
  54266. this._disposeRTTandPostProcesses();
  54267. if (this._light) {
  54268. this._light._shadowGenerator = null;
  54269. this._light._markMeshesAsLightDirty();
  54270. }
  54271. };
  54272. /**
  54273. * Serializes the ShadowGenerator and returns a serializationObject.
  54274. */
  54275. ShadowGenerator.prototype.serialize = function () {
  54276. var serializationObject = {};
  54277. var shadowMap = this.getShadowMap();
  54278. if (!shadowMap) {
  54279. return serializationObject;
  54280. }
  54281. serializationObject.lightId = this._light.id;
  54282. serializationObject.mapSize = shadowMap.getRenderSize();
  54283. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54284. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54285. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54286. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54287. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54288. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54289. serializationObject.depthScale = this.depthScale;
  54290. serializationObject.darkness = this.getDarkness();
  54291. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54292. serializationObject.blurKernel = this.blurKernel;
  54293. serializationObject.blurScale = this.blurScale;
  54294. serializationObject.useKernelBlur = this.useKernelBlur;
  54295. serializationObject.transparencyShadow = this._transparencyShadow;
  54296. serializationObject.renderList = [];
  54297. if (shadowMap.renderList) {
  54298. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54299. var mesh = shadowMap.renderList[meshIndex];
  54300. serializationObject.renderList.push(mesh.id);
  54301. }
  54302. }
  54303. return serializationObject;
  54304. };
  54305. /**
  54306. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54307. */
  54308. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54309. //casting to point light, as light is missing the position attr and typescript complains.
  54310. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54311. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54312. var shadowMap = shadowGenerator.getShadowMap();
  54313. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54314. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54315. meshes.forEach(function (mesh) {
  54316. if (!shadowMap) {
  54317. return;
  54318. }
  54319. if (!shadowMap.renderList) {
  54320. shadowMap.renderList = [];
  54321. }
  54322. shadowMap.renderList.push(mesh);
  54323. });
  54324. }
  54325. if (parsedShadowGenerator.usePoissonSampling) {
  54326. shadowGenerator.usePoissonSampling = true;
  54327. }
  54328. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54329. shadowGenerator.useExponentialShadowMap = true;
  54330. }
  54331. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54332. shadowGenerator.useBlurExponentialShadowMap = true;
  54333. }
  54334. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54335. shadowGenerator.useCloseExponentialShadowMap = true;
  54336. }
  54337. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54338. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54339. }
  54340. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54341. shadowGenerator.useExponentialShadowMap = true;
  54342. }
  54343. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54344. shadowGenerator.useBlurExponentialShadowMap = true;
  54345. }
  54346. if (parsedShadowGenerator.depthScale) {
  54347. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54348. }
  54349. if (parsedShadowGenerator.blurScale) {
  54350. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54351. }
  54352. if (parsedShadowGenerator.blurBoxOffset) {
  54353. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54354. }
  54355. if (parsedShadowGenerator.useKernelBlur) {
  54356. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54357. }
  54358. if (parsedShadowGenerator.blurKernel) {
  54359. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54360. }
  54361. if (parsedShadowGenerator.bias !== undefined) {
  54362. shadowGenerator.bias = parsedShadowGenerator.bias;
  54363. }
  54364. if (parsedShadowGenerator.darkness) {
  54365. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54366. }
  54367. if (parsedShadowGenerator.transparencyShadow) {
  54368. shadowGenerator.setTransparencyShadow(true);
  54369. }
  54370. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54371. return shadowGenerator;
  54372. };
  54373. ShadowGenerator._FILTER_NONE = 0;
  54374. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54375. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54376. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54377. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54378. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54379. return ShadowGenerator;
  54380. }());
  54381. BABYLON.ShadowGenerator = ShadowGenerator;
  54382. })(BABYLON || (BABYLON = {}));
  54383. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54384. var BABYLON;
  54385. (function (BABYLON) {
  54386. var DefaultLoadingScreen = /** @class */ (function () {
  54387. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54388. if (_loadingText === void 0) { _loadingText = ""; }
  54389. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54390. var _this = this;
  54391. this._renderingCanvas = _renderingCanvas;
  54392. this._loadingText = _loadingText;
  54393. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54394. // Resize
  54395. this._resizeLoadingUI = function () {
  54396. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54397. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54398. if (!_this._loadingDiv) {
  54399. return;
  54400. }
  54401. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54402. _this._loadingDiv.style.left = canvasRect.left + "px";
  54403. _this._loadingDiv.style.top = canvasRect.top + "px";
  54404. _this._loadingDiv.style.width = canvasRect.width + "px";
  54405. _this._loadingDiv.style.height = canvasRect.height + "px";
  54406. };
  54407. }
  54408. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54409. if (this._loadingDiv) {
  54410. // Do not add a loading screen if there is already one
  54411. return;
  54412. }
  54413. this._loadingDiv = document.createElement("div");
  54414. this._loadingDiv.id = "babylonjsLoadingDiv";
  54415. this._loadingDiv.style.opacity = "0";
  54416. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54417. this._loadingDiv.style.pointerEvents = "none";
  54418. // Loading text
  54419. this._loadingTextDiv = document.createElement("div");
  54420. this._loadingTextDiv.style.position = "absolute";
  54421. this._loadingTextDiv.style.left = "0";
  54422. this._loadingTextDiv.style.top = "50%";
  54423. this._loadingTextDiv.style.marginTop = "80px";
  54424. this._loadingTextDiv.style.width = "100%";
  54425. this._loadingTextDiv.style.height = "20px";
  54426. this._loadingTextDiv.style.fontFamily = "Arial";
  54427. this._loadingTextDiv.style.fontSize = "14px";
  54428. this._loadingTextDiv.style.color = "white";
  54429. this._loadingTextDiv.style.textAlign = "center";
  54430. this._loadingTextDiv.innerHTML = "Loading";
  54431. this._loadingDiv.appendChild(this._loadingTextDiv);
  54432. //set the predefined text
  54433. this._loadingTextDiv.innerHTML = this._loadingText;
  54434. // Generating keyframes
  54435. var style = document.createElement('style');
  54436. style.type = 'text/css';
  54437. 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 }";
  54438. style.innerHTML = keyFrames;
  54439. document.getElementsByTagName('head')[0].appendChild(style);
  54440. // Loading img
  54441. var imgBack = new Image();
  54442. 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";
  54443. imgBack.style.position = "absolute";
  54444. imgBack.style.left = "50%";
  54445. imgBack.style.top = "50%";
  54446. imgBack.style.marginLeft = "-60px";
  54447. imgBack.style.marginTop = "-60px";
  54448. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54449. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54450. imgBack.style.transformOrigin = "50% 50%";
  54451. imgBack.style.webkitTransformOrigin = "50% 50%";
  54452. this._loadingDiv.appendChild(imgBack);
  54453. this._resizeLoadingUI();
  54454. window.addEventListener("resize", this._resizeLoadingUI);
  54455. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54456. document.body.appendChild(this._loadingDiv);
  54457. this._loadingDiv.style.opacity = "1";
  54458. };
  54459. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54460. var _this = this;
  54461. if (!this._loadingDiv) {
  54462. return;
  54463. }
  54464. var onTransitionEnd = function () {
  54465. if (!_this._loadingDiv) {
  54466. return;
  54467. }
  54468. document.body.removeChild(_this._loadingDiv);
  54469. window.removeEventListener("resize", _this._resizeLoadingUI);
  54470. _this._loadingDiv = null;
  54471. };
  54472. this._loadingDiv.style.opacity = "0";
  54473. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54474. };
  54475. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54476. set: function (text) {
  54477. this._loadingText = text;
  54478. if (this._loadingTextDiv) {
  54479. this._loadingTextDiv.innerHTML = this._loadingText;
  54480. }
  54481. },
  54482. enumerable: true,
  54483. configurable: true
  54484. });
  54485. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54486. get: function () {
  54487. return this._loadingDivBackgroundColor;
  54488. },
  54489. set: function (color) {
  54490. this._loadingDivBackgroundColor = color;
  54491. if (!this._loadingDiv) {
  54492. return;
  54493. }
  54494. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54495. },
  54496. enumerable: true,
  54497. configurable: true
  54498. });
  54499. return DefaultLoadingScreen;
  54500. }());
  54501. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54502. })(BABYLON || (BABYLON = {}));
  54503. //# sourceMappingURL=babylon.loadingScreen.js.map
  54504. var BABYLON;
  54505. (function (BABYLON) {
  54506. var SceneLoaderProgressEvent = /** @class */ (function () {
  54507. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54508. this.lengthComputable = lengthComputable;
  54509. this.loaded = loaded;
  54510. this.total = total;
  54511. }
  54512. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54513. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54514. };
  54515. return SceneLoaderProgressEvent;
  54516. }());
  54517. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54518. var SceneLoader = /** @class */ (function () {
  54519. function SceneLoader() {
  54520. }
  54521. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54522. get: function () {
  54523. return 0;
  54524. },
  54525. enumerable: true,
  54526. configurable: true
  54527. });
  54528. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54529. get: function () {
  54530. return 1;
  54531. },
  54532. enumerable: true,
  54533. configurable: true
  54534. });
  54535. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54536. get: function () {
  54537. return 2;
  54538. },
  54539. enumerable: true,
  54540. configurable: true
  54541. });
  54542. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54543. get: function () {
  54544. return 3;
  54545. },
  54546. enumerable: true,
  54547. configurable: true
  54548. });
  54549. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54550. get: function () {
  54551. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54552. },
  54553. set: function (value) {
  54554. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54555. },
  54556. enumerable: true,
  54557. configurable: true
  54558. });
  54559. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54560. get: function () {
  54561. return SceneLoader._ShowLoadingScreen;
  54562. },
  54563. set: function (value) {
  54564. SceneLoader._ShowLoadingScreen = value;
  54565. },
  54566. enumerable: true,
  54567. configurable: true
  54568. });
  54569. Object.defineProperty(SceneLoader, "loggingLevel", {
  54570. get: function () {
  54571. return SceneLoader._loggingLevel;
  54572. },
  54573. set: function (value) {
  54574. SceneLoader._loggingLevel = value;
  54575. },
  54576. enumerable: true,
  54577. configurable: true
  54578. });
  54579. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54580. get: function () {
  54581. return SceneLoader._CleanBoneMatrixWeights;
  54582. },
  54583. set: function (value) {
  54584. SceneLoader._CleanBoneMatrixWeights = value;
  54585. },
  54586. enumerable: true,
  54587. configurable: true
  54588. });
  54589. SceneLoader._getDefaultPlugin = function () {
  54590. return SceneLoader._registeredPlugins[".babylon"];
  54591. };
  54592. SceneLoader._getPluginForExtension = function (extension) {
  54593. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54594. if (registeredPlugin) {
  54595. return registeredPlugin;
  54596. }
  54597. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54598. return SceneLoader._getDefaultPlugin();
  54599. };
  54600. SceneLoader._getPluginForDirectLoad = function (data) {
  54601. for (var extension in SceneLoader._registeredPlugins) {
  54602. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54603. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54604. return SceneLoader._registeredPlugins[extension];
  54605. }
  54606. }
  54607. return SceneLoader._getDefaultPlugin();
  54608. };
  54609. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54610. if (sceneFilename.name) {
  54611. sceneFilename = sceneFilename.name;
  54612. }
  54613. var queryStringPosition = sceneFilename.indexOf("?");
  54614. if (queryStringPosition !== -1) {
  54615. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54616. }
  54617. var dotPosition = sceneFilename.lastIndexOf(".");
  54618. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54619. return SceneLoader._getPluginForExtension(extension);
  54620. };
  54621. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54622. SceneLoader._getDirectLoad = function (sceneFilename) {
  54623. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54624. return sceneFilename.substr(5);
  54625. }
  54626. return null;
  54627. };
  54628. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54629. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54630. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54631. var plugin;
  54632. if (registeredPlugin.plugin.createPlugin) {
  54633. plugin = registeredPlugin.plugin.createPlugin();
  54634. }
  54635. else {
  54636. plugin = registeredPlugin.plugin;
  54637. }
  54638. var useArrayBuffer = registeredPlugin.isBinary;
  54639. var database;
  54640. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54641. var dataCallback = function (data, responseURL) {
  54642. if (scene.isDisposed) {
  54643. onError("Scene has been disposed");
  54644. return;
  54645. }
  54646. scene.database = database;
  54647. onSuccess(plugin, data, responseURL);
  54648. };
  54649. var request = null;
  54650. var pluginDisposed = false;
  54651. var onDisposeObservable = plugin.onDisposeObservable;
  54652. if (onDisposeObservable) {
  54653. onDisposeObservable.add(function () {
  54654. pluginDisposed = true;
  54655. if (request) {
  54656. request.abort();
  54657. request = null;
  54658. }
  54659. onDispose();
  54660. });
  54661. }
  54662. var manifestChecked = function () {
  54663. if (pluginDisposed) {
  54664. return;
  54665. }
  54666. var url = rootUrl + sceneFilename;
  54667. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54668. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54669. } : undefined, database, useArrayBuffer, function (request, exception) {
  54670. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54671. });
  54672. };
  54673. if (directLoad) {
  54674. dataCallback(directLoad);
  54675. return plugin;
  54676. }
  54677. if (rootUrl.indexOf("file:") === -1) {
  54678. if (scene.getEngine().enableOfflineSupport) {
  54679. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54680. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54681. }
  54682. else {
  54683. manifestChecked();
  54684. }
  54685. }
  54686. else {
  54687. var fileOrString = sceneFilename;
  54688. if (fileOrString.name) {
  54689. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54690. }
  54691. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54692. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54693. }
  54694. else {
  54695. onError("Unable to find file named " + sceneFilename);
  54696. }
  54697. }
  54698. return plugin;
  54699. };
  54700. // Public functions
  54701. SceneLoader.GetPluginForExtension = function (extension) {
  54702. return SceneLoader._getPluginForExtension(extension).plugin;
  54703. };
  54704. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54705. return !!SceneLoader._registeredPlugins[extension];
  54706. };
  54707. SceneLoader.RegisterPlugin = function (plugin) {
  54708. if (typeof plugin.extensions === "string") {
  54709. var extension = plugin.extensions;
  54710. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54711. plugin: plugin,
  54712. isBinary: false
  54713. };
  54714. }
  54715. else {
  54716. var extensions = plugin.extensions;
  54717. Object.keys(extensions).forEach(function (extension) {
  54718. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54719. plugin: plugin,
  54720. isBinary: extensions[extension].isBinary
  54721. };
  54722. });
  54723. }
  54724. };
  54725. /**
  54726. * Import meshes into a scene
  54727. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54728. * @param rootUrl a string that defines the root url for scene and resources
  54729. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54730. * @param scene the instance of BABYLON.Scene to append to
  54731. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54732. * @param onProgress a callback with a progress event for each file being loaded
  54733. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54734. */
  54735. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54736. if (onSuccess === void 0) { onSuccess = null; }
  54737. if (onProgress === void 0) { onProgress = null; }
  54738. if (onError === void 0) { onError = null; }
  54739. if (pluginExtension === void 0) { pluginExtension = null; }
  54740. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54741. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54742. return null;
  54743. }
  54744. var loadingToken = {};
  54745. scene._addPendingData(loadingToken);
  54746. var disposeHandler = function () {
  54747. scene._removePendingData(loadingToken);
  54748. };
  54749. var errorHandler = function (message, exception) {
  54750. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54751. if (onError) {
  54752. onError(scene, errorMessage, exception);
  54753. }
  54754. else {
  54755. BABYLON.Tools.Error(errorMessage);
  54756. // should the exception be thrown?
  54757. }
  54758. disposeHandler();
  54759. };
  54760. var progressHandler = onProgress ? function (event) {
  54761. try {
  54762. onProgress(event);
  54763. }
  54764. catch (e) {
  54765. errorHandler("Error in onProgress callback", e);
  54766. }
  54767. } : undefined;
  54768. var successHandler = function (meshes, particleSystems, skeletons) {
  54769. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54770. if (onSuccess) {
  54771. try {
  54772. onSuccess(meshes, particleSystems, skeletons);
  54773. }
  54774. catch (e) {
  54775. errorHandler("Error in onSuccess callback", e);
  54776. }
  54777. }
  54778. scene._removePendingData(loadingToken);
  54779. };
  54780. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54781. if (plugin.rewriteRootURL) {
  54782. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54783. }
  54784. if (plugin.importMesh) {
  54785. var syncedPlugin = plugin;
  54786. var meshes = new Array();
  54787. var particleSystems = new Array();
  54788. var skeletons = new Array();
  54789. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54790. return;
  54791. }
  54792. scene.loadingPluginName = plugin.name;
  54793. successHandler(meshes, particleSystems, skeletons);
  54794. }
  54795. else {
  54796. var asyncedPlugin = plugin;
  54797. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54798. scene.loadingPluginName = plugin.name;
  54799. successHandler(meshes, particleSystems, skeletons);
  54800. }, progressHandler, errorHandler);
  54801. }
  54802. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54803. };
  54804. /**
  54805. * Load a scene
  54806. * @param rootUrl a string that defines the root url for scene and resources
  54807. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54808. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54809. * @param onSuccess a callback with the scene when import succeeds
  54810. * @param onProgress a callback with a progress event for each file being loaded
  54811. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54812. */
  54813. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54814. if (onSuccess === void 0) { onSuccess = null; }
  54815. if (onProgress === void 0) { onProgress = null; }
  54816. if (onError === void 0) { onError = null; }
  54817. if (pluginExtension === void 0) { pluginExtension = null; }
  54818. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54819. };
  54820. /**
  54821. * Append a scene
  54822. * @param rootUrl a string that defines the root url for scene and resources
  54823. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54824. * @param scene is the instance of BABYLON.Scene to append to
  54825. * @param onSuccess a callback with the scene when import succeeds
  54826. * @param onProgress a callback with a progress event for each file being loaded
  54827. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54828. */
  54829. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54830. if (onSuccess === void 0) { onSuccess = null; }
  54831. if (onProgress === void 0) { onProgress = null; }
  54832. if (onError === void 0) { onError = null; }
  54833. if (pluginExtension === void 0) { pluginExtension = null; }
  54834. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54835. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54836. return null;
  54837. }
  54838. if (SceneLoader.ShowLoadingScreen) {
  54839. scene.getEngine().displayLoadingUI();
  54840. }
  54841. var loadingToken = {};
  54842. scene._addPendingData(loadingToken);
  54843. var disposeHandler = function () {
  54844. scene._removePendingData(loadingToken);
  54845. scene.getEngine().hideLoadingUI();
  54846. };
  54847. var errorHandler = function (message, exception) {
  54848. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54849. if (onError) {
  54850. onError(scene, errorMessage, exception);
  54851. }
  54852. else {
  54853. BABYLON.Tools.Error(errorMessage);
  54854. // should the exception be thrown?
  54855. }
  54856. disposeHandler();
  54857. };
  54858. var progressHandler = onProgress ? function (event) {
  54859. try {
  54860. onProgress(event);
  54861. }
  54862. catch (e) {
  54863. errorHandler("Error in onProgress callback", e);
  54864. }
  54865. } : undefined;
  54866. var successHandler = function () {
  54867. if (onSuccess) {
  54868. try {
  54869. onSuccess(scene);
  54870. }
  54871. catch (e) {
  54872. errorHandler("Error in onSuccess callback", e);
  54873. }
  54874. }
  54875. scene._removePendingData(loadingToken);
  54876. };
  54877. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54878. if (plugin.load) {
  54879. var syncedPlugin = plugin;
  54880. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54881. return;
  54882. }
  54883. scene.loadingPluginName = plugin.name;
  54884. successHandler();
  54885. }
  54886. else {
  54887. var asyncedPlugin = plugin;
  54888. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54889. scene.loadingPluginName = plugin.name;
  54890. successHandler();
  54891. }, progressHandler, errorHandler);
  54892. }
  54893. if (SceneLoader.ShowLoadingScreen) {
  54894. scene.executeWhenReady(function () {
  54895. scene.getEngine().hideLoadingUI();
  54896. });
  54897. }
  54898. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54899. };
  54900. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54901. if (onSuccess === void 0) { onSuccess = null; }
  54902. if (onProgress === void 0) { onProgress = null; }
  54903. if (onError === void 0) { onError = null; }
  54904. if (pluginExtension === void 0) { pluginExtension = null; }
  54905. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54906. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54907. return null;
  54908. }
  54909. var loadingToken = {};
  54910. scene._addPendingData(loadingToken);
  54911. var disposeHandler = function () {
  54912. scene._removePendingData(loadingToken);
  54913. };
  54914. var errorHandler = function (message, exception) {
  54915. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54916. if (onError) {
  54917. onError(scene, errorMessage, exception);
  54918. }
  54919. else {
  54920. BABYLON.Tools.Error(errorMessage);
  54921. // should the exception be thrown?
  54922. }
  54923. disposeHandler();
  54924. };
  54925. var progressHandler = onProgress ? function (event) {
  54926. try {
  54927. onProgress(event);
  54928. }
  54929. catch (e) {
  54930. errorHandler("Error in onProgress callback", e);
  54931. }
  54932. } : undefined;
  54933. var successHandler = function (assets) {
  54934. if (onSuccess) {
  54935. try {
  54936. onSuccess(assets);
  54937. }
  54938. catch (e) {
  54939. errorHandler("Error in onSuccess callback", e);
  54940. }
  54941. }
  54942. scene._removePendingData(loadingToken);
  54943. };
  54944. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54945. if (plugin.loadAssets) {
  54946. var syncedPlugin = plugin;
  54947. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54948. if (!assetContainer) {
  54949. return;
  54950. }
  54951. scene.loadingPluginName = plugin.name;
  54952. successHandler(assetContainer);
  54953. }
  54954. else if (plugin.loadAssetsAsync) {
  54955. var asyncedPlugin = plugin;
  54956. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54957. if (assetContainer) {
  54958. scene.loadingPluginName = plugin.name;
  54959. successHandler(assetContainer);
  54960. }
  54961. }, progressHandler, errorHandler);
  54962. }
  54963. else {
  54964. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54965. }
  54966. if (SceneLoader.ShowLoadingScreen) {
  54967. scene.executeWhenReady(function () {
  54968. scene.getEngine().hideLoadingUI();
  54969. });
  54970. }
  54971. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54972. };
  54973. // Flags
  54974. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54975. SceneLoader._ShowLoadingScreen = true;
  54976. SceneLoader._CleanBoneMatrixWeights = false;
  54977. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54978. // Members
  54979. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54980. SceneLoader._registeredPlugins = {};
  54981. return SceneLoader;
  54982. }());
  54983. BABYLON.SceneLoader = SceneLoader;
  54984. ;
  54985. })(BABYLON || (BABYLON = {}));
  54986. //# sourceMappingURL=babylon.sceneLoader.js.map
  54987. var BABYLON;
  54988. (function (BABYLON) {
  54989. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54990. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54991. var parsedMaterial = parsedData.materials[index];
  54992. if (parsedMaterial.id === id) {
  54993. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54994. }
  54995. }
  54996. return null;
  54997. };
  54998. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54999. for (var i in names) {
  55000. if (mesh.name === names[i]) {
  55001. hierarchyIds.push(mesh.id);
  55002. return true;
  55003. }
  55004. }
  55005. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  55006. hierarchyIds.push(mesh.id);
  55007. return true;
  55008. }
  55009. return false;
  55010. };
  55011. var logOperation = function (operation, producer) {
  55012. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  55013. };
  55014. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  55015. if (addToScene === void 0) { addToScene = false; }
  55016. var container = new BABYLON.AssetContainer(scene);
  55017. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55018. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55019. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55020. // and avoid problems with multiple concurrent .babylon loads.
  55021. var log = "importScene has failed JSON parse";
  55022. try {
  55023. var parsedData = JSON.parse(data);
  55024. log = "";
  55025. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55026. var index;
  55027. var cache;
  55028. // Lights
  55029. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  55030. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  55031. var parsedLight = parsedData.lights[index];
  55032. var light = BABYLON.Light.Parse(parsedLight, scene);
  55033. if (light) {
  55034. container.lights.push(light);
  55035. log += (index === 0 ? "\n\tLights:" : "");
  55036. log += "\n\t\t" + light.toString(fullDetails);
  55037. }
  55038. }
  55039. }
  55040. // Animations
  55041. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  55042. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  55043. var parsedAnimation = parsedData.animations[index];
  55044. var animation = BABYLON.Animation.Parse(parsedAnimation);
  55045. scene.animations.push(animation);
  55046. container.animations.push(animation);
  55047. log += (index === 0 ? "\n\tAnimations:" : "");
  55048. log += "\n\t\t" + animation.toString(fullDetails);
  55049. }
  55050. }
  55051. // Materials
  55052. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  55053. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  55054. var parsedMaterial = parsedData.materials[index];
  55055. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  55056. container.materials.push(mat);
  55057. log += (index === 0 ? "\n\tMaterials:" : "");
  55058. log += "\n\t\t" + mat.toString(fullDetails);
  55059. }
  55060. }
  55061. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55062. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  55063. var parsedMultiMaterial = parsedData.multiMaterials[index];
  55064. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55065. container.multiMaterials.push(mmat);
  55066. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  55067. log += "\n\t\t" + mmat.toString(fullDetails);
  55068. }
  55069. }
  55070. // Morph targets
  55071. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  55072. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  55073. var managerData = _a[_i];
  55074. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  55075. }
  55076. }
  55077. // Skeletons
  55078. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55079. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  55080. var parsedSkeleton = parsedData.skeletons[index];
  55081. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55082. container.skeletons.push(skeleton);
  55083. log += (index === 0 ? "\n\tSkeletons:" : "");
  55084. log += "\n\t\t" + skeleton.toString(fullDetails);
  55085. }
  55086. }
  55087. // Geometries
  55088. var geometries = parsedData.geometries;
  55089. if (geometries !== undefined && geometries !== null) {
  55090. var addedGeometry = new Array();
  55091. // Boxes
  55092. var boxes = geometries.boxes;
  55093. if (boxes !== undefined && boxes !== null) {
  55094. for (index = 0, cache = boxes.length; index < cache; index++) {
  55095. var parsedBox = boxes[index];
  55096. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  55097. }
  55098. }
  55099. // Spheres
  55100. var spheres = geometries.spheres;
  55101. if (spheres !== undefined && spheres !== null) {
  55102. for (index = 0, cache = spheres.length; index < cache; index++) {
  55103. var parsedSphere = spheres[index];
  55104. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  55105. }
  55106. }
  55107. // Cylinders
  55108. var cylinders = geometries.cylinders;
  55109. if (cylinders !== undefined && cylinders !== null) {
  55110. for (index = 0, cache = cylinders.length; index < cache; index++) {
  55111. var parsedCylinder = cylinders[index];
  55112. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  55113. }
  55114. }
  55115. // Toruses
  55116. var toruses = geometries.toruses;
  55117. if (toruses !== undefined && toruses !== null) {
  55118. for (index = 0, cache = toruses.length; index < cache; index++) {
  55119. var parsedTorus = toruses[index];
  55120. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  55121. }
  55122. }
  55123. // Grounds
  55124. var grounds = geometries.grounds;
  55125. if (grounds !== undefined && grounds !== null) {
  55126. for (index = 0, cache = grounds.length; index < cache; index++) {
  55127. var parsedGround = grounds[index];
  55128. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  55129. }
  55130. }
  55131. // Planes
  55132. var planes = geometries.planes;
  55133. if (planes !== undefined && planes !== null) {
  55134. for (index = 0, cache = planes.length; index < cache; index++) {
  55135. var parsedPlane = planes[index];
  55136. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  55137. }
  55138. }
  55139. // TorusKnots
  55140. var torusKnots = geometries.torusKnots;
  55141. if (torusKnots !== undefined && torusKnots !== null) {
  55142. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55143. var parsedTorusKnot = torusKnots[index];
  55144. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  55145. }
  55146. }
  55147. // VertexData
  55148. var vertexData = geometries.vertexData;
  55149. if (vertexData !== undefined && vertexData !== null) {
  55150. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55151. var parsedVertexData = vertexData[index];
  55152. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55153. }
  55154. }
  55155. addedGeometry.forEach(function (g) {
  55156. if (g) {
  55157. container.geometries.push(g);
  55158. }
  55159. });
  55160. }
  55161. // Transform nodes
  55162. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55163. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55164. var parsedTransformNode = parsedData.transformNodes[index];
  55165. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55166. container.transformNodes.push(node);
  55167. }
  55168. }
  55169. // Meshes
  55170. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55171. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55172. var parsedMesh = parsedData.meshes[index];
  55173. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55174. container.meshes.push(mesh);
  55175. log += (index === 0 ? "\n\tMeshes:" : "");
  55176. log += "\n\t\t" + mesh.toString(fullDetails);
  55177. }
  55178. }
  55179. // Cameras
  55180. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55181. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55182. var parsedCamera = parsedData.cameras[index];
  55183. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55184. container.cameras.push(camera);
  55185. log += (index === 0 ? "\n\tCameras:" : "");
  55186. log += "\n\t\t" + camera.toString(fullDetails);
  55187. }
  55188. }
  55189. // Browsing all the graph to connect the dots
  55190. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55191. var camera = scene.cameras[index];
  55192. if (camera._waitingParentId) {
  55193. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55194. camera._waitingParentId = null;
  55195. }
  55196. }
  55197. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55198. var light_1 = scene.lights[index];
  55199. if (light_1 && light_1._waitingParentId) {
  55200. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55201. light_1._waitingParentId = null;
  55202. }
  55203. }
  55204. // Sounds
  55205. // TODO: add sound
  55206. var loadedSounds = [];
  55207. var loadedSound;
  55208. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55209. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55210. var parsedSound = parsedData.sounds[index];
  55211. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55212. if (!parsedSound.url)
  55213. parsedSound.url = parsedSound.name;
  55214. if (!loadedSounds[parsedSound.url]) {
  55215. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55216. loadedSounds[parsedSound.url] = loadedSound;
  55217. container.sounds.push(loadedSound);
  55218. }
  55219. else {
  55220. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55221. }
  55222. }
  55223. else {
  55224. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55225. }
  55226. }
  55227. }
  55228. loadedSounds = [];
  55229. // Connect parents & children and parse actions
  55230. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55231. var transformNode = scene.transformNodes[index];
  55232. if (transformNode._waitingParentId) {
  55233. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55234. transformNode._waitingParentId = null;
  55235. }
  55236. }
  55237. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55238. var mesh = scene.meshes[index];
  55239. if (mesh._waitingParentId) {
  55240. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55241. mesh._waitingParentId = null;
  55242. }
  55243. if (mesh._waitingActions) {
  55244. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55245. mesh._waitingActions = null;
  55246. }
  55247. }
  55248. // freeze world matrix application
  55249. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55250. var currentMesh = scene.meshes[index];
  55251. if (currentMesh._waitingFreezeWorldMatrix) {
  55252. currentMesh.freezeWorldMatrix();
  55253. currentMesh._waitingFreezeWorldMatrix = null;
  55254. }
  55255. else {
  55256. currentMesh.computeWorldMatrix(true);
  55257. }
  55258. }
  55259. // Particles Systems
  55260. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55261. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55262. var parsedParticleSystem = parsedData.particleSystems[index];
  55263. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55264. container.particleSystems.push(ps);
  55265. }
  55266. }
  55267. // Lens flares
  55268. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55269. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55270. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55271. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55272. container.lensFlareSystems.push(lf);
  55273. }
  55274. }
  55275. // Shadows
  55276. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55277. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55278. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55279. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55280. container.shadowGenerators.push(sg);
  55281. }
  55282. }
  55283. // Lights exclusions / inclusions
  55284. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55285. var light_2 = scene.lights[index];
  55286. // Excluded check
  55287. if (light_2._excludedMeshesIds.length > 0) {
  55288. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55289. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55290. if (excludedMesh) {
  55291. light_2.excludedMeshes.push(excludedMesh);
  55292. }
  55293. }
  55294. light_2._excludedMeshesIds = [];
  55295. }
  55296. // Included check
  55297. if (light_2._includedOnlyMeshesIds.length > 0) {
  55298. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55299. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55300. if (includedOnlyMesh) {
  55301. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55302. }
  55303. }
  55304. light_2._includedOnlyMeshesIds = [];
  55305. }
  55306. }
  55307. // Actions (scene)
  55308. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55309. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55310. }
  55311. if (!addToScene) {
  55312. container.removeAllFromScene();
  55313. }
  55314. return container;
  55315. }
  55316. catch (err) {
  55317. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55318. if (onError) {
  55319. onError(msg, err);
  55320. }
  55321. else {
  55322. BABYLON.Tools.Log(msg);
  55323. throw err;
  55324. }
  55325. }
  55326. finally {
  55327. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55328. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55329. }
  55330. }
  55331. return null;
  55332. };
  55333. BABYLON.SceneLoader.RegisterPlugin({
  55334. name: "babylon.js",
  55335. extensions: ".babylon",
  55336. canDirectLoad: function (data) {
  55337. if (data.indexOf("babylon") !== -1) {
  55338. return true;
  55339. }
  55340. return false;
  55341. },
  55342. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55343. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55344. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55345. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55346. // and avoid problems with multiple concurrent .babylon loads.
  55347. var log = "importMesh has failed JSON parse";
  55348. try {
  55349. var parsedData = JSON.parse(data);
  55350. log = "";
  55351. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55352. if (!meshesNames) {
  55353. meshesNames = null;
  55354. }
  55355. else if (!Array.isArray(meshesNames)) {
  55356. meshesNames = [meshesNames];
  55357. }
  55358. var hierarchyIds = new Array();
  55359. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55360. var loadedSkeletonsIds = [];
  55361. var loadedMaterialsIds = [];
  55362. var index;
  55363. var cache;
  55364. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55365. var parsedMesh = parsedData.meshes[index];
  55366. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55367. if (meshesNames !== null) {
  55368. // Remove found mesh name from list.
  55369. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55370. }
  55371. //Geometry?
  55372. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55373. //does the file contain geometries?
  55374. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55375. //find the correct geometry and add it to the scene
  55376. var found = false;
  55377. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55378. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55379. return;
  55380. }
  55381. else {
  55382. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55383. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55384. switch (geometryType) {
  55385. case "boxes":
  55386. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55387. break;
  55388. case "spheres":
  55389. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55390. break;
  55391. case "cylinders":
  55392. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55393. break;
  55394. case "toruses":
  55395. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55396. break;
  55397. case "grounds":
  55398. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55399. break;
  55400. case "planes":
  55401. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55402. break;
  55403. case "torusKnots":
  55404. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55405. break;
  55406. case "vertexData":
  55407. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55408. break;
  55409. }
  55410. found = true;
  55411. }
  55412. });
  55413. }
  55414. });
  55415. if (found === false) {
  55416. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55417. }
  55418. }
  55419. }
  55420. // Material ?
  55421. if (parsedMesh.materialId) {
  55422. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55423. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55424. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55425. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55426. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55427. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55428. var subMatId = parsedMultiMaterial.materials[matIndex];
  55429. loadedMaterialsIds.push(subMatId);
  55430. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55431. log += "\n\tMaterial " + mat.toString(fullDetails);
  55432. }
  55433. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55434. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55435. materialFound = true;
  55436. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55437. break;
  55438. }
  55439. }
  55440. }
  55441. if (materialFound === false) {
  55442. loadedMaterialsIds.push(parsedMesh.materialId);
  55443. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55444. if (!mat) {
  55445. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55446. }
  55447. else {
  55448. log += "\n\tMaterial " + mat.toString(fullDetails);
  55449. }
  55450. }
  55451. }
  55452. // Skeleton ?
  55453. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55454. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55455. if (skeletonAlreadyLoaded === false) {
  55456. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55457. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55458. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55459. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55460. skeletons.push(skeleton);
  55461. loadedSkeletonsIds.push(parsedSkeleton.id);
  55462. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55463. }
  55464. }
  55465. }
  55466. }
  55467. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55468. meshes.push(mesh);
  55469. log += "\n\tMesh " + mesh.toString(fullDetails);
  55470. }
  55471. }
  55472. // Connecting parents
  55473. var currentMesh;
  55474. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55475. currentMesh = scene.meshes[index];
  55476. if (currentMesh._waitingParentId) {
  55477. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55478. currentMesh._waitingParentId = null;
  55479. }
  55480. }
  55481. // freeze and compute world matrix application
  55482. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55483. currentMesh = scene.meshes[index];
  55484. if (currentMesh._waitingFreezeWorldMatrix) {
  55485. currentMesh.freezeWorldMatrix();
  55486. currentMesh._waitingFreezeWorldMatrix = null;
  55487. }
  55488. else {
  55489. currentMesh.computeWorldMatrix(true);
  55490. }
  55491. }
  55492. }
  55493. // Particles
  55494. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55495. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55496. var parsedParticleSystem = parsedData.particleSystems[index];
  55497. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55498. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55499. }
  55500. }
  55501. }
  55502. return true;
  55503. }
  55504. catch (err) {
  55505. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55506. if (onError) {
  55507. onError(msg, err);
  55508. }
  55509. else {
  55510. BABYLON.Tools.Log(msg);
  55511. throw err;
  55512. }
  55513. }
  55514. finally {
  55515. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55516. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55517. }
  55518. }
  55519. return false;
  55520. },
  55521. load: function (scene, data, rootUrl, onError) {
  55522. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55523. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55524. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55525. // and avoid problems with multiple concurrent .babylon loads.
  55526. var log = "importScene has failed JSON parse";
  55527. try {
  55528. var parsedData = JSON.parse(data);
  55529. log = "";
  55530. // Scene
  55531. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55532. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55533. }
  55534. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55535. scene.autoClear = parsedData.autoClear;
  55536. }
  55537. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55538. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55539. }
  55540. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55541. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55542. }
  55543. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55544. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55545. }
  55546. // Fog
  55547. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55548. scene.fogMode = parsedData.fogMode;
  55549. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55550. scene.fogStart = parsedData.fogStart;
  55551. scene.fogEnd = parsedData.fogEnd;
  55552. scene.fogDensity = parsedData.fogDensity;
  55553. log += "\tFog mode for scene: ";
  55554. switch (scene.fogMode) {
  55555. // getters not compiling, so using hardcoded
  55556. case 1:
  55557. log += "exp\n";
  55558. break;
  55559. case 2:
  55560. log += "exp2\n";
  55561. break;
  55562. case 3:
  55563. log += "linear\n";
  55564. break;
  55565. }
  55566. }
  55567. //Physics
  55568. if (parsedData.physicsEnabled) {
  55569. var physicsPlugin;
  55570. if (parsedData.physicsEngine === "cannon") {
  55571. physicsPlugin = new BABYLON.CannonJSPlugin();
  55572. }
  55573. else if (parsedData.physicsEngine === "oimo") {
  55574. physicsPlugin = new BABYLON.OimoJSPlugin();
  55575. }
  55576. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55577. //else - default engine, which is currently oimo
  55578. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55579. scene.enablePhysics(physicsGravity, physicsPlugin);
  55580. }
  55581. // Metadata
  55582. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55583. scene.metadata = parsedData.metadata;
  55584. }
  55585. //collisions, if defined. otherwise, default is true
  55586. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55587. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55588. }
  55589. scene.workerCollisions = !!parsedData.workerCollisions;
  55590. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55591. if (!container) {
  55592. return false;
  55593. }
  55594. if (parsedData.autoAnimate) {
  55595. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55596. }
  55597. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55598. scene.setActiveCameraByID(parsedData.activeCameraID);
  55599. }
  55600. // Environment texture
  55601. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55602. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55603. if (parsedData.createDefaultSkybox === true) {
  55604. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55605. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55606. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55607. }
  55608. }
  55609. // Finish
  55610. return true;
  55611. }
  55612. catch (err) {
  55613. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55614. if (onError) {
  55615. onError(msg, err);
  55616. }
  55617. else {
  55618. BABYLON.Tools.Log(msg);
  55619. throw err;
  55620. }
  55621. }
  55622. finally {
  55623. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55624. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55625. }
  55626. }
  55627. return false;
  55628. },
  55629. loadAssets: function (scene, data, rootUrl, onError) {
  55630. var container = loadAssets(scene, data, rootUrl, onerror);
  55631. return container;
  55632. }
  55633. });
  55634. })(BABYLON || (BABYLON = {}));
  55635. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55636. var BABYLON;
  55637. (function (BABYLON) {
  55638. var FilesInput = /** @class */ (function () {
  55639. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55640. this.onProcessFileCallback = function () { return true; };
  55641. this._engine = engine;
  55642. this._currentScene = scene;
  55643. this._sceneLoadedCallback = sceneLoadedCallback;
  55644. this._progressCallback = progressCallback;
  55645. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55646. this._textureLoadingCallback = textureLoadingCallback;
  55647. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55648. this._onReloadCallback = onReloadCallback;
  55649. this._errorCallback = errorCallback;
  55650. }
  55651. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55652. var _this = this;
  55653. if (elementToMonitor) {
  55654. this._elementToMonitor = elementToMonitor;
  55655. this._dragEnterHandler = function (e) { _this.drag(e); };
  55656. this._dragOverHandler = function (e) { _this.drag(e); };
  55657. this._dropHandler = function (e) { _this.drop(e); };
  55658. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55659. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55660. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55661. }
  55662. };
  55663. FilesInput.prototype.dispose = function () {
  55664. if (!this._elementToMonitor) {
  55665. return;
  55666. }
  55667. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55668. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55669. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55670. };
  55671. FilesInput.prototype.renderFunction = function () {
  55672. if (this._additionalRenderLoopLogicCallback) {
  55673. this._additionalRenderLoopLogicCallback();
  55674. }
  55675. if (this._currentScene) {
  55676. if (this._textureLoadingCallback) {
  55677. var remaining = this._currentScene.getWaitingItemsCount();
  55678. if (remaining > 0) {
  55679. this._textureLoadingCallback(remaining);
  55680. }
  55681. }
  55682. this._currentScene.render();
  55683. }
  55684. };
  55685. FilesInput.prototype.drag = function (e) {
  55686. e.stopPropagation();
  55687. e.preventDefault();
  55688. };
  55689. FilesInput.prototype.drop = function (eventDrop) {
  55690. eventDrop.stopPropagation();
  55691. eventDrop.preventDefault();
  55692. this.loadFiles(eventDrop);
  55693. };
  55694. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55695. var _this = this;
  55696. var reader = folder.createReader();
  55697. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55698. reader.readEntries(function (entries) {
  55699. remaining.count += entries.length;
  55700. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55701. var entry = entries_1[_i];
  55702. if (entry.isFile) {
  55703. entry.file(function (file) {
  55704. file.correctName = relativePath + file.name;
  55705. files.push(file);
  55706. if (--remaining.count === 0) {
  55707. callback();
  55708. }
  55709. });
  55710. }
  55711. else if (entry.isDirectory) {
  55712. _this._traverseFolder(entry, files, remaining, callback);
  55713. }
  55714. }
  55715. if (--remaining.count) {
  55716. callback();
  55717. }
  55718. });
  55719. };
  55720. FilesInput.prototype._processFiles = function (files) {
  55721. for (var i = 0; i < files.length; i++) {
  55722. var name = files[i].correctName.toLowerCase();
  55723. var extension = name.split('.').pop();
  55724. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55725. continue;
  55726. }
  55727. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55728. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55729. this._sceneFileToLoad = files[i];
  55730. }
  55731. else {
  55732. FilesInput.FilesToLoad[name] = files[i];
  55733. }
  55734. }
  55735. };
  55736. FilesInput.prototype.loadFiles = function (event) {
  55737. var _this = this;
  55738. if (this._startingProcessingFilesCallback)
  55739. this._startingProcessingFilesCallback();
  55740. // Handling data transfer via drag'n'drop
  55741. if (event && event.dataTransfer && event.dataTransfer.files) {
  55742. this._filesToLoad = event.dataTransfer.files;
  55743. }
  55744. // Handling files from input files
  55745. if (event && event.target && event.target.files) {
  55746. this._filesToLoad = event.target.files;
  55747. }
  55748. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55749. var files_1 = new Array();
  55750. var folders = [];
  55751. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55752. for (var i = 0; i < this._filesToLoad.length; i++) {
  55753. var fileToLoad = this._filesToLoad[i];
  55754. var name_1 = fileToLoad.name.toLowerCase();
  55755. var entry = void 0;
  55756. fileToLoad.correctName = name_1;
  55757. if (items) {
  55758. var item = items[i];
  55759. if (item.getAsEntry) {
  55760. entry = item.getAsEntry();
  55761. }
  55762. else if (item.webkitGetAsEntry) {
  55763. entry = item.webkitGetAsEntry();
  55764. }
  55765. }
  55766. if (!entry) {
  55767. files_1.push(fileToLoad);
  55768. }
  55769. else {
  55770. if (entry.isDirectory) {
  55771. folders.push(entry);
  55772. }
  55773. else {
  55774. files_1.push(fileToLoad);
  55775. }
  55776. }
  55777. }
  55778. if (folders.length === 0) {
  55779. this._processFiles(files_1);
  55780. this._processReload();
  55781. }
  55782. else {
  55783. var remaining = { count: folders.length };
  55784. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55785. var folder = folders_1[_i];
  55786. this._traverseFolder(folder, files_1, remaining, function () {
  55787. _this._processFiles(files_1);
  55788. if (remaining.count === 0) {
  55789. _this._processReload();
  55790. }
  55791. });
  55792. }
  55793. }
  55794. }
  55795. };
  55796. FilesInput.prototype._processReload = function () {
  55797. if (this._onReloadCallback) {
  55798. this._onReloadCallback(this._sceneFileToLoad);
  55799. }
  55800. else {
  55801. this.reload();
  55802. }
  55803. };
  55804. FilesInput.prototype.reload = function () {
  55805. var _this = this;
  55806. // If a scene file has been provided
  55807. if (this._sceneFileToLoad) {
  55808. if (this._currentScene) {
  55809. if (BABYLON.Tools.errorsCount > 0) {
  55810. BABYLON.Tools.ClearLogCache();
  55811. }
  55812. this._engine.stopRenderLoop();
  55813. this._currentScene.dispose();
  55814. }
  55815. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55816. _this._currentScene = newScene;
  55817. if (_this._sceneLoadedCallback) {
  55818. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55819. }
  55820. // Wait for textures and shaders to be ready
  55821. _this._currentScene.executeWhenReady(function () {
  55822. _this._engine.runRenderLoop(function () {
  55823. _this.renderFunction();
  55824. });
  55825. });
  55826. }, function (progress) {
  55827. if (_this._progressCallback) {
  55828. _this._progressCallback(progress);
  55829. }
  55830. }, function (scene, message) {
  55831. _this._currentScene = scene;
  55832. if (_this._errorCallback) {
  55833. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55834. }
  55835. });
  55836. }
  55837. else {
  55838. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55839. }
  55840. };
  55841. FilesInput.FilesToLoad = {};
  55842. return FilesInput;
  55843. }());
  55844. BABYLON.FilesInput = FilesInput;
  55845. })(BABYLON || (BABYLON = {}));
  55846. //# sourceMappingURL=babylon.filesInput.js.map
  55847. var BABYLON;
  55848. (function (BABYLON) {
  55849. /**
  55850. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55851. * The underlying implementation relies on an associative array to ensure the best performances.
  55852. * The value can be anything including 'null' but except 'undefined'
  55853. */
  55854. var StringDictionary = /** @class */ (function () {
  55855. function StringDictionary() {
  55856. this._count = 0;
  55857. this._data = {};
  55858. }
  55859. /**
  55860. * This will clear this dictionary and copy the content from the 'source' one.
  55861. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55862. * @param source the dictionary to take the content from and copy to this dictionary
  55863. */
  55864. StringDictionary.prototype.copyFrom = function (source) {
  55865. var _this = this;
  55866. this.clear();
  55867. source.forEach(function (t, v) { return _this.add(t, v); });
  55868. };
  55869. /**
  55870. * Get a value based from its key
  55871. * @param key the given key to get the matching value from
  55872. * @return the value if found, otherwise undefined is returned
  55873. */
  55874. StringDictionary.prototype.get = function (key) {
  55875. var val = this._data[key];
  55876. if (val !== undefined) {
  55877. return val;
  55878. }
  55879. return undefined;
  55880. };
  55881. /**
  55882. * Get a value from its key or add it if it doesn't exist.
  55883. * This method will ensure you that a given key/data will be present in the dictionary.
  55884. * @param key the given key to get the matching value from
  55885. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55886. * The factory will only be invoked if there's no data for the given key.
  55887. * @return the value corresponding to the key.
  55888. */
  55889. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55890. var val = this.get(key);
  55891. if (val !== undefined) {
  55892. return val;
  55893. }
  55894. val = factory(key);
  55895. if (val) {
  55896. this.add(key, val);
  55897. }
  55898. return val;
  55899. };
  55900. /**
  55901. * Get a value from its key if present in the dictionary otherwise add it
  55902. * @param key the key to get the value from
  55903. * @param val if there's no such key/value pair in the dictionary add it with this value
  55904. * @return the value corresponding to the key
  55905. */
  55906. StringDictionary.prototype.getOrAdd = function (key, val) {
  55907. var curVal = this.get(key);
  55908. if (curVal !== undefined) {
  55909. return curVal;
  55910. }
  55911. this.add(key, val);
  55912. return val;
  55913. };
  55914. /**
  55915. * Check if there's a given key in the dictionary
  55916. * @param key the key to check for
  55917. * @return true if the key is present, false otherwise
  55918. */
  55919. StringDictionary.prototype.contains = function (key) {
  55920. return this._data[key] !== undefined;
  55921. };
  55922. /**
  55923. * Add a new key and its corresponding value
  55924. * @param key the key to add
  55925. * @param value the value corresponding to the key
  55926. * @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
  55927. */
  55928. StringDictionary.prototype.add = function (key, value) {
  55929. if (this._data[key] !== undefined) {
  55930. return false;
  55931. }
  55932. this._data[key] = value;
  55933. ++this._count;
  55934. return true;
  55935. };
  55936. StringDictionary.prototype.set = function (key, value) {
  55937. if (this._data[key] === undefined) {
  55938. return false;
  55939. }
  55940. this._data[key] = value;
  55941. return true;
  55942. };
  55943. /**
  55944. * Get the element of the given key and remove it from the dictionary
  55945. * @param key
  55946. */
  55947. StringDictionary.prototype.getAndRemove = function (key) {
  55948. var val = this.get(key);
  55949. if (val !== undefined) {
  55950. delete this._data[key];
  55951. --this._count;
  55952. return val;
  55953. }
  55954. return null;
  55955. };
  55956. /**
  55957. * Remove a key/value from the dictionary.
  55958. * @param key the key to remove
  55959. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55960. */
  55961. StringDictionary.prototype.remove = function (key) {
  55962. if (this.contains(key)) {
  55963. delete this._data[key];
  55964. --this._count;
  55965. return true;
  55966. }
  55967. return false;
  55968. };
  55969. /**
  55970. * Clear the whole content of the dictionary
  55971. */
  55972. StringDictionary.prototype.clear = function () {
  55973. this._data = {};
  55974. this._count = 0;
  55975. };
  55976. Object.defineProperty(StringDictionary.prototype, "count", {
  55977. get: function () {
  55978. return this._count;
  55979. },
  55980. enumerable: true,
  55981. configurable: true
  55982. });
  55983. /**
  55984. * Execute a callback on each key/val of the dictionary.
  55985. * Note that you can remove any element in this dictionary in the callback implementation
  55986. * @param callback the callback to execute on a given key/value pair
  55987. */
  55988. StringDictionary.prototype.forEach = function (callback) {
  55989. for (var cur in this._data) {
  55990. var val = this._data[cur];
  55991. callback(cur, val);
  55992. }
  55993. };
  55994. /**
  55995. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55996. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55997. * Note that you can remove any element in this dictionary in the callback implementation
  55998. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55999. */
  56000. StringDictionary.prototype.first = function (callback) {
  56001. for (var cur in this._data) {
  56002. var val = this._data[cur];
  56003. var res = callback(cur, val);
  56004. if (res) {
  56005. return res;
  56006. }
  56007. }
  56008. return null;
  56009. };
  56010. return StringDictionary;
  56011. }());
  56012. BABYLON.StringDictionary = StringDictionary;
  56013. })(BABYLON || (BABYLON = {}));
  56014. //# sourceMappingURL=babylon.stringDictionary.js.map
  56015. var BABYLON;
  56016. (function (BABYLON) {
  56017. var Tags = /** @class */ (function () {
  56018. function Tags() {
  56019. }
  56020. Tags.EnableFor = function (obj) {
  56021. obj._tags = obj._tags || {};
  56022. obj.hasTags = function () {
  56023. return Tags.HasTags(obj);
  56024. };
  56025. obj.addTags = function (tagsString) {
  56026. return Tags.AddTagsTo(obj, tagsString);
  56027. };
  56028. obj.removeTags = function (tagsString) {
  56029. return Tags.RemoveTagsFrom(obj, tagsString);
  56030. };
  56031. obj.matchesTagsQuery = function (tagsQuery) {
  56032. return Tags.MatchesQuery(obj, tagsQuery);
  56033. };
  56034. };
  56035. Tags.DisableFor = function (obj) {
  56036. delete obj._tags;
  56037. delete obj.hasTags;
  56038. delete obj.addTags;
  56039. delete obj.removeTags;
  56040. delete obj.matchesTagsQuery;
  56041. };
  56042. Tags.HasTags = function (obj) {
  56043. if (!obj._tags) {
  56044. return false;
  56045. }
  56046. return !BABYLON.Tools.IsEmpty(obj._tags);
  56047. };
  56048. Tags.GetTags = function (obj, asString) {
  56049. if (asString === void 0) { asString = true; }
  56050. if (!obj._tags) {
  56051. return null;
  56052. }
  56053. if (asString) {
  56054. var tagsArray = [];
  56055. for (var tag in obj._tags) {
  56056. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  56057. tagsArray.push(tag);
  56058. }
  56059. }
  56060. return tagsArray.join(" ");
  56061. }
  56062. else {
  56063. return obj._tags;
  56064. }
  56065. };
  56066. // the tags 'true' and 'false' are reserved and cannot be used as tags
  56067. // a tag cannot start with '||', '&&', and '!'
  56068. // it cannot contain whitespaces
  56069. Tags.AddTagsTo = function (obj, tagsString) {
  56070. if (!tagsString) {
  56071. return;
  56072. }
  56073. if (typeof tagsString !== "string") {
  56074. return;
  56075. }
  56076. var tags = tagsString.split(" ");
  56077. tags.forEach(function (tag, index, array) {
  56078. Tags._AddTagTo(obj, tag);
  56079. });
  56080. };
  56081. Tags._AddTagTo = function (obj, tag) {
  56082. tag = tag.trim();
  56083. if (tag === "" || tag === "true" || tag === "false") {
  56084. return;
  56085. }
  56086. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  56087. return;
  56088. }
  56089. Tags.EnableFor(obj);
  56090. obj._tags[tag] = true;
  56091. };
  56092. Tags.RemoveTagsFrom = function (obj, tagsString) {
  56093. if (!Tags.HasTags(obj)) {
  56094. return;
  56095. }
  56096. var tags = tagsString.split(" ");
  56097. for (var t in tags) {
  56098. Tags._RemoveTagFrom(obj, tags[t]);
  56099. }
  56100. };
  56101. Tags._RemoveTagFrom = function (obj, tag) {
  56102. delete obj._tags[tag];
  56103. };
  56104. Tags.MatchesQuery = function (obj, tagsQuery) {
  56105. if (tagsQuery === undefined) {
  56106. return true;
  56107. }
  56108. if (tagsQuery === "") {
  56109. return Tags.HasTags(obj);
  56110. }
  56111. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  56112. };
  56113. return Tags;
  56114. }());
  56115. BABYLON.Tags = Tags;
  56116. })(BABYLON || (BABYLON = {}));
  56117. //# sourceMappingURL=babylon.tags.js.map
  56118. var BABYLON;
  56119. (function (BABYLON) {
  56120. var AndOrNotEvaluator = /** @class */ (function () {
  56121. function AndOrNotEvaluator() {
  56122. }
  56123. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  56124. if (!query.match(/\([^\(\)]*\)/g)) {
  56125. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  56126. }
  56127. else {
  56128. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  56129. // remove parenthesis
  56130. r = r.slice(1, r.length - 1);
  56131. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  56132. });
  56133. }
  56134. if (query === "true") {
  56135. return true;
  56136. }
  56137. if (query === "false") {
  56138. return false;
  56139. }
  56140. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  56141. };
  56142. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  56143. evaluateCallback = evaluateCallback || (function (r) {
  56144. return r === "true" ? true : false;
  56145. });
  56146. var result;
  56147. var or = parenthesisContent.split("||");
  56148. for (var i in or) {
  56149. if (or.hasOwnProperty(i)) {
  56150. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56151. var and = ori.split("&&");
  56152. if (and.length > 1) {
  56153. for (var j = 0; j < and.length; ++j) {
  56154. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56155. if (andj !== "true" && andj !== "false") {
  56156. if (andj[0] === "!") {
  56157. result = !evaluateCallback(andj.substring(1));
  56158. }
  56159. else {
  56160. result = evaluateCallback(andj);
  56161. }
  56162. }
  56163. else {
  56164. result = andj === "true" ? true : false;
  56165. }
  56166. if (!result) {
  56167. ori = "false";
  56168. break;
  56169. }
  56170. }
  56171. }
  56172. if (result || ori === "true") {
  56173. result = true;
  56174. break;
  56175. }
  56176. // result equals false (or undefined)
  56177. if (ori !== "true" && ori !== "false") {
  56178. if (ori[0] === "!") {
  56179. result = !evaluateCallback(ori.substring(1));
  56180. }
  56181. else {
  56182. result = evaluateCallback(ori);
  56183. }
  56184. }
  56185. else {
  56186. result = ori === "true" ? true : false;
  56187. }
  56188. }
  56189. }
  56190. // the whole parenthesis scope is replaced by 'true' or 'false'
  56191. return result ? "true" : "false";
  56192. };
  56193. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56194. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56195. // remove whitespaces
  56196. r = r.replace(/[\s]/g, function () { return ""; });
  56197. return r.length % 2 ? "!" : "";
  56198. });
  56199. booleanString = booleanString.trim();
  56200. if (booleanString === "!true") {
  56201. booleanString = "false";
  56202. }
  56203. else if (booleanString === "!false") {
  56204. booleanString = "true";
  56205. }
  56206. return booleanString;
  56207. };
  56208. return AndOrNotEvaluator;
  56209. }());
  56210. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56211. })(BABYLON || (BABYLON = {}));
  56212. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56213. var BABYLON;
  56214. (function (BABYLON) {
  56215. var Database = /** @class */ (function () {
  56216. function Database(urlToScene, callbackManifestChecked) {
  56217. // Handling various flavors of prefixed version of IndexedDB
  56218. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56219. this.callbackManifestChecked = callbackManifestChecked;
  56220. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56221. this.db = null;
  56222. this._enableSceneOffline = false;
  56223. this._enableTexturesOffline = false;
  56224. this.manifestVersionFound = 0;
  56225. this.mustUpdateRessources = false;
  56226. this.hasReachedQuota = false;
  56227. if (!Database.IDBStorageEnabled) {
  56228. this.callbackManifestChecked(true);
  56229. }
  56230. else {
  56231. this.checkManifestFile();
  56232. }
  56233. }
  56234. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56235. get: function () {
  56236. return this._enableSceneOffline;
  56237. },
  56238. enumerable: true,
  56239. configurable: true
  56240. });
  56241. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56242. get: function () {
  56243. return this._enableTexturesOffline;
  56244. },
  56245. enumerable: true,
  56246. configurable: true
  56247. });
  56248. Database.prototype.checkManifestFile = function () {
  56249. var _this = this;
  56250. var noManifestFile = function () {
  56251. _this._enableSceneOffline = false;
  56252. _this._enableTexturesOffline = false;
  56253. _this.callbackManifestChecked(false);
  56254. };
  56255. var timeStampUsed = false;
  56256. var manifestURL = this.currentSceneUrl + ".manifest";
  56257. var xhr = new XMLHttpRequest();
  56258. if (navigator.onLine) {
  56259. // Adding a timestamp to by-pass browsers' cache
  56260. timeStampUsed = true;
  56261. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56262. }
  56263. xhr.open("GET", manifestURL, true);
  56264. xhr.addEventListener("load", function () {
  56265. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56266. try {
  56267. var manifestFile = JSON.parse(xhr.response);
  56268. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56269. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56270. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56271. _this.manifestVersionFound = manifestFile.version;
  56272. }
  56273. if (_this.callbackManifestChecked) {
  56274. _this.callbackManifestChecked(true);
  56275. }
  56276. }
  56277. catch (ex) {
  56278. noManifestFile();
  56279. }
  56280. }
  56281. else {
  56282. noManifestFile();
  56283. }
  56284. }, false);
  56285. xhr.addEventListener("error", function (event) {
  56286. if (timeStampUsed) {
  56287. timeStampUsed = false;
  56288. // Let's retry without the timeStamp
  56289. // It could fail when coupled with HTML5 Offline API
  56290. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56291. xhr.open("GET", retryManifestURL, true);
  56292. xhr.send();
  56293. }
  56294. else {
  56295. noManifestFile();
  56296. }
  56297. }, false);
  56298. try {
  56299. xhr.send();
  56300. }
  56301. catch (ex) {
  56302. BABYLON.Tools.Error("Error on XHR send request.");
  56303. this.callbackManifestChecked(false);
  56304. }
  56305. };
  56306. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56307. var _this = this;
  56308. var handleError = function () {
  56309. _this.isSupported = false;
  56310. if (errorCallback)
  56311. errorCallback();
  56312. };
  56313. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56314. // Your browser doesn't support IndexedDB
  56315. this.isSupported = false;
  56316. if (errorCallback)
  56317. errorCallback();
  56318. }
  56319. else {
  56320. // If the DB hasn't been opened or created yet
  56321. if (!this.db) {
  56322. this.hasReachedQuota = false;
  56323. this.isSupported = true;
  56324. var request = this.idbFactory.open("babylonjs", 1);
  56325. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56326. request.onerror = function (event) {
  56327. handleError();
  56328. };
  56329. // executes when a version change transaction cannot complete due to other active transactions
  56330. request.onblocked = function (event) {
  56331. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56332. handleError();
  56333. };
  56334. // DB has been opened successfully
  56335. request.onsuccess = function (event) {
  56336. _this.db = request.result;
  56337. successCallback();
  56338. };
  56339. // Initialization of the DB. Creating Scenes & Textures stores
  56340. request.onupgradeneeded = function (event) {
  56341. _this.db = (event.target).result;
  56342. if (_this.db) {
  56343. try {
  56344. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56345. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56346. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56347. }
  56348. catch (ex) {
  56349. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56350. handleError();
  56351. }
  56352. }
  56353. };
  56354. }
  56355. else {
  56356. if (successCallback)
  56357. successCallback();
  56358. }
  56359. }
  56360. };
  56361. Database.prototype.loadImageFromDB = function (url, image) {
  56362. var _this = this;
  56363. var completeURL = Database.ReturnFullUrlLocation(url);
  56364. var saveAndLoadImage = function () {
  56365. if (!_this.hasReachedQuota && _this.db !== null) {
  56366. // the texture is not yet in the DB, let's try to save it
  56367. _this._saveImageIntoDBAsync(completeURL, image);
  56368. }
  56369. else {
  56370. image.src = url;
  56371. }
  56372. };
  56373. if (!this.mustUpdateRessources) {
  56374. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56375. }
  56376. else {
  56377. saveAndLoadImage();
  56378. }
  56379. };
  56380. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56381. if (this.isSupported && this.db !== null) {
  56382. var texture;
  56383. var transaction = this.db.transaction(["textures"]);
  56384. transaction.onabort = function (event) {
  56385. image.src = url;
  56386. };
  56387. transaction.oncomplete = function (event) {
  56388. var blobTextureURL;
  56389. if (texture) {
  56390. var URL = window.URL || window.webkitURL;
  56391. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56392. image.onerror = function () {
  56393. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56394. image.src = url;
  56395. };
  56396. image.src = blobTextureURL;
  56397. }
  56398. else {
  56399. notInDBCallback();
  56400. }
  56401. };
  56402. var getRequest = transaction.objectStore("textures").get(url);
  56403. getRequest.onsuccess = function (event) {
  56404. texture = (event.target).result;
  56405. };
  56406. getRequest.onerror = function (event) {
  56407. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56408. image.src = url;
  56409. };
  56410. }
  56411. else {
  56412. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56413. image.src = url;
  56414. }
  56415. };
  56416. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56417. var _this = this;
  56418. if (this.isSupported) {
  56419. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56420. var generateBlobUrl = function () {
  56421. var blobTextureURL;
  56422. if (blob) {
  56423. var URL = window.URL || window.webkitURL;
  56424. try {
  56425. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56426. }
  56427. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56428. catch (ex) {
  56429. blobTextureURL = URL.createObjectURL(blob);
  56430. }
  56431. }
  56432. if (blobTextureURL) {
  56433. image.src = blobTextureURL;
  56434. }
  56435. };
  56436. if (Database.IsUASupportingBlobStorage) {
  56437. var xhr = new XMLHttpRequest(), blob;
  56438. xhr.open("GET", url, true);
  56439. xhr.responseType = "blob";
  56440. xhr.addEventListener("load", function () {
  56441. if (xhr.status === 200 && _this.db) {
  56442. // Blob as response (XHR2)
  56443. blob = xhr.response;
  56444. var transaction = _this.db.transaction(["textures"], "readwrite");
  56445. // the transaction could abort because of a QuotaExceededError error
  56446. transaction.onabort = function (event) {
  56447. try {
  56448. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56449. var srcElement = (event.srcElement || event.target);
  56450. var error = srcElement.error;
  56451. if (error && error.name === "QuotaExceededError") {
  56452. _this.hasReachedQuota = true;
  56453. }
  56454. }
  56455. catch (ex) { }
  56456. generateBlobUrl();
  56457. };
  56458. transaction.oncomplete = function (event) {
  56459. generateBlobUrl();
  56460. };
  56461. var newTexture = { textureUrl: url, data: blob };
  56462. try {
  56463. // Put the blob into the dabase
  56464. var addRequest = transaction.objectStore("textures").put(newTexture);
  56465. addRequest.onsuccess = function (event) {
  56466. };
  56467. addRequest.onerror = function (event) {
  56468. generateBlobUrl();
  56469. };
  56470. }
  56471. catch (ex) {
  56472. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56473. if (ex.code === 25) {
  56474. Database.IsUASupportingBlobStorage = false;
  56475. }
  56476. image.src = url;
  56477. }
  56478. }
  56479. else {
  56480. image.src = url;
  56481. }
  56482. }, false);
  56483. xhr.addEventListener("error", function (event) {
  56484. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56485. image.src = url;
  56486. }, false);
  56487. xhr.send();
  56488. }
  56489. else {
  56490. image.src = url;
  56491. }
  56492. }
  56493. else {
  56494. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56495. image.src = url;
  56496. }
  56497. };
  56498. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56499. var _this = this;
  56500. var updateVersion = function () {
  56501. // the version is not yet in the DB or we need to update it
  56502. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56503. };
  56504. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56505. };
  56506. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56507. var _this = this;
  56508. if (this.isSupported && this.db) {
  56509. var version;
  56510. try {
  56511. var transaction = this.db.transaction(["versions"]);
  56512. transaction.oncomplete = function (event) {
  56513. if (version) {
  56514. // If the version in the JSON file is > than the version in DB
  56515. if (_this.manifestVersionFound > version.data) {
  56516. _this.mustUpdateRessources = true;
  56517. updateInDBCallback();
  56518. }
  56519. else {
  56520. callback(version.data);
  56521. }
  56522. }
  56523. else {
  56524. _this.mustUpdateRessources = true;
  56525. updateInDBCallback();
  56526. }
  56527. };
  56528. transaction.onabort = function (event) {
  56529. callback(-1);
  56530. };
  56531. var getRequest = transaction.objectStore("versions").get(url);
  56532. getRequest.onsuccess = function (event) {
  56533. version = (event.target).result;
  56534. };
  56535. getRequest.onerror = function (event) {
  56536. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56537. callback(-1);
  56538. };
  56539. }
  56540. catch (ex) {
  56541. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56542. callback(-1);
  56543. }
  56544. }
  56545. else {
  56546. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56547. callback(-1);
  56548. }
  56549. };
  56550. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56551. var _this = this;
  56552. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56553. try {
  56554. // Open a transaction to the database
  56555. var transaction = this.db.transaction(["versions"], "readwrite");
  56556. // the transaction could abort because of a QuotaExceededError error
  56557. transaction.onabort = function (event) {
  56558. try {
  56559. var error = event.srcElement['error'];
  56560. if (error && error.name === "QuotaExceededError") {
  56561. _this.hasReachedQuota = true;
  56562. }
  56563. }
  56564. catch (ex) { }
  56565. callback(-1);
  56566. };
  56567. transaction.oncomplete = function (event) {
  56568. callback(_this.manifestVersionFound);
  56569. };
  56570. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56571. // Put the scene into the database
  56572. var addRequest = transaction.objectStore("versions").put(newVersion);
  56573. addRequest.onsuccess = function (event) {
  56574. };
  56575. addRequest.onerror = function (event) {
  56576. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56577. };
  56578. }
  56579. catch (ex) {
  56580. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56581. callback(-1);
  56582. }
  56583. }
  56584. else {
  56585. callback(-1);
  56586. }
  56587. };
  56588. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56589. var _this = this;
  56590. var completeUrl = Database.ReturnFullUrlLocation(url);
  56591. var saveAndLoadFile = function () {
  56592. // the scene is not yet in the DB, let's try to save it
  56593. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56594. };
  56595. this._checkVersionFromDB(completeUrl, function (version) {
  56596. if (version !== -1) {
  56597. if (!_this.mustUpdateRessources) {
  56598. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56599. }
  56600. else {
  56601. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56602. }
  56603. }
  56604. else {
  56605. if (errorCallback) {
  56606. errorCallback();
  56607. }
  56608. }
  56609. });
  56610. };
  56611. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56612. if (this.isSupported && this.db) {
  56613. var targetStore;
  56614. if (url.indexOf(".babylon") !== -1) {
  56615. targetStore = "scenes";
  56616. }
  56617. else {
  56618. targetStore = "textures";
  56619. }
  56620. var file;
  56621. var transaction = this.db.transaction([targetStore]);
  56622. transaction.oncomplete = function (event) {
  56623. if (file) {
  56624. callback(file.data);
  56625. }
  56626. else {
  56627. notInDBCallback();
  56628. }
  56629. };
  56630. transaction.onabort = function (event) {
  56631. notInDBCallback();
  56632. };
  56633. var getRequest = transaction.objectStore(targetStore).get(url);
  56634. getRequest.onsuccess = function (event) {
  56635. file = (event.target).result;
  56636. };
  56637. getRequest.onerror = function (event) {
  56638. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56639. notInDBCallback();
  56640. };
  56641. }
  56642. else {
  56643. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56644. callback();
  56645. }
  56646. };
  56647. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56648. var _this = this;
  56649. if (this.isSupported) {
  56650. var targetStore;
  56651. if (url.indexOf(".babylon") !== -1) {
  56652. targetStore = "scenes";
  56653. }
  56654. else {
  56655. targetStore = "textures";
  56656. }
  56657. // Create XHR
  56658. var xhr = new XMLHttpRequest();
  56659. var fileData;
  56660. xhr.open("GET", url, true);
  56661. if (useArrayBuffer) {
  56662. xhr.responseType = "arraybuffer";
  56663. }
  56664. if (progressCallback) {
  56665. xhr.onprogress = progressCallback;
  56666. }
  56667. xhr.addEventListener("load", function () {
  56668. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56669. // Blob as response (XHR2)
  56670. //fileData = xhr.responseText;
  56671. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56672. if (!_this.hasReachedQuota && _this.db) {
  56673. // Open a transaction to the database
  56674. var transaction = _this.db.transaction([targetStore], "readwrite");
  56675. // the transaction could abort because of a QuotaExceededError error
  56676. transaction.onabort = function (event) {
  56677. try {
  56678. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56679. var error = event.srcElement['error'];
  56680. if (error && error.name === "QuotaExceededError") {
  56681. _this.hasReachedQuota = true;
  56682. }
  56683. }
  56684. catch (ex) { }
  56685. callback(fileData);
  56686. };
  56687. transaction.oncomplete = function (event) {
  56688. callback(fileData);
  56689. };
  56690. var newFile;
  56691. if (targetStore === "scenes") {
  56692. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56693. }
  56694. else {
  56695. newFile = { textureUrl: url, data: fileData };
  56696. }
  56697. try {
  56698. // Put the scene into the database
  56699. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56700. addRequest.onsuccess = function (event) {
  56701. };
  56702. addRequest.onerror = function (event) {
  56703. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56704. };
  56705. }
  56706. catch (ex) {
  56707. callback(fileData);
  56708. }
  56709. }
  56710. else {
  56711. callback(fileData);
  56712. }
  56713. }
  56714. else {
  56715. callback();
  56716. }
  56717. }, false);
  56718. xhr.addEventListener("error", function (event) {
  56719. BABYLON.Tools.Error("error on XHR request.");
  56720. callback();
  56721. }, false);
  56722. xhr.send();
  56723. }
  56724. else {
  56725. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56726. callback();
  56727. }
  56728. };
  56729. Database.IsUASupportingBlobStorage = true;
  56730. Database.IDBStorageEnabled = true;
  56731. Database.parseURL = function (url) {
  56732. var a = document.createElement('a');
  56733. a.href = url;
  56734. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56735. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56736. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56737. return absLocation;
  56738. };
  56739. Database.ReturnFullUrlLocation = function (url) {
  56740. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56741. return (Database.parseURL(window.location.href) + url);
  56742. }
  56743. else {
  56744. return url;
  56745. }
  56746. };
  56747. return Database;
  56748. }());
  56749. BABYLON.Database = Database;
  56750. })(BABYLON || (BABYLON = {}));
  56751. //# sourceMappingURL=babylon.database.js.map
  56752. var BABYLON;
  56753. (function (BABYLON) {
  56754. var FresnelParameters = /** @class */ (function () {
  56755. function FresnelParameters() {
  56756. this._isEnabled = true;
  56757. this.leftColor = BABYLON.Color3.White();
  56758. this.rightColor = BABYLON.Color3.Black();
  56759. this.bias = 0;
  56760. this.power = 1;
  56761. }
  56762. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56763. get: function () {
  56764. return this._isEnabled;
  56765. },
  56766. set: function (value) {
  56767. if (this._isEnabled === value) {
  56768. return;
  56769. }
  56770. this._isEnabled = value;
  56771. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56772. },
  56773. enumerable: true,
  56774. configurable: true
  56775. });
  56776. FresnelParameters.prototype.clone = function () {
  56777. var newFresnelParameters = new FresnelParameters();
  56778. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56779. return newFresnelParameters;
  56780. };
  56781. FresnelParameters.prototype.serialize = function () {
  56782. var serializationObject = {};
  56783. serializationObject.isEnabled = this.isEnabled;
  56784. serializationObject.leftColor = this.leftColor;
  56785. serializationObject.rightColor = this.rightColor;
  56786. serializationObject.bias = this.bias;
  56787. serializationObject.power = this.power;
  56788. return serializationObject;
  56789. };
  56790. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56791. var fresnelParameters = new FresnelParameters();
  56792. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56793. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56794. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56795. fresnelParameters.bias = parsedFresnelParameters.bias;
  56796. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56797. return fresnelParameters;
  56798. };
  56799. return FresnelParameters;
  56800. }());
  56801. BABYLON.FresnelParameters = FresnelParameters;
  56802. })(BABYLON || (BABYLON = {}));
  56803. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56804. var BABYLON;
  56805. (function (BABYLON) {
  56806. var MultiMaterial = /** @class */ (function (_super) {
  56807. __extends(MultiMaterial, _super);
  56808. function MultiMaterial(name, scene) {
  56809. var _this = _super.call(this, name, scene, true) || this;
  56810. scene.multiMaterials.push(_this);
  56811. _this.subMaterials = new Array();
  56812. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56813. return _this;
  56814. }
  56815. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56816. get: function () {
  56817. return this._subMaterials;
  56818. },
  56819. set: function (value) {
  56820. this._subMaterials = value;
  56821. this._hookArray(value);
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. MultiMaterial.prototype._hookArray = function (array) {
  56827. var _this = this;
  56828. var oldPush = array.push;
  56829. array.push = function () {
  56830. var items = [];
  56831. for (var _i = 0; _i < arguments.length; _i++) {
  56832. items[_i] = arguments[_i];
  56833. }
  56834. var result = oldPush.apply(array, items);
  56835. _this._markAllSubMeshesAsTexturesDirty();
  56836. return result;
  56837. };
  56838. var oldSplice = array.splice;
  56839. array.splice = function (index, deleteCount) {
  56840. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56841. _this._markAllSubMeshesAsTexturesDirty();
  56842. return deleted;
  56843. };
  56844. };
  56845. // Properties
  56846. MultiMaterial.prototype.getSubMaterial = function (index) {
  56847. if (index < 0 || index >= this.subMaterials.length) {
  56848. return this.getScene().defaultMaterial;
  56849. }
  56850. return this.subMaterials[index];
  56851. };
  56852. MultiMaterial.prototype.getActiveTextures = function () {
  56853. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56854. if (subMaterial) {
  56855. return subMaterial.getActiveTextures();
  56856. }
  56857. else {
  56858. return [];
  56859. }
  56860. }));
  56861. var _a;
  56862. };
  56863. // Methods
  56864. MultiMaterial.prototype.getClassName = function () {
  56865. return "MultiMaterial";
  56866. };
  56867. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56868. for (var index = 0; index < this.subMaterials.length; index++) {
  56869. var subMaterial = this.subMaterials[index];
  56870. if (subMaterial) {
  56871. if (subMaterial.storeEffectOnSubMeshes) {
  56872. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56873. return false;
  56874. }
  56875. continue;
  56876. }
  56877. if (!subMaterial.isReady(mesh)) {
  56878. return false;
  56879. }
  56880. }
  56881. }
  56882. return true;
  56883. };
  56884. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56885. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56886. for (var index = 0; index < this.subMaterials.length; index++) {
  56887. var subMaterial = null;
  56888. var current = this.subMaterials[index];
  56889. if (cloneChildren && current) {
  56890. subMaterial = current.clone(name + "-" + current.name);
  56891. }
  56892. else {
  56893. subMaterial = this.subMaterials[index];
  56894. }
  56895. newMultiMaterial.subMaterials.push(subMaterial);
  56896. }
  56897. return newMultiMaterial;
  56898. };
  56899. MultiMaterial.prototype.serialize = function () {
  56900. var serializationObject = {};
  56901. serializationObject.name = this.name;
  56902. serializationObject.id = this.id;
  56903. if (BABYLON.Tags) {
  56904. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56905. }
  56906. serializationObject.materials = [];
  56907. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56908. var subMat = this.subMaterials[matIndex];
  56909. if (subMat) {
  56910. serializationObject.materials.push(subMat.id);
  56911. }
  56912. else {
  56913. serializationObject.materials.push(null);
  56914. }
  56915. }
  56916. return serializationObject;
  56917. };
  56918. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56919. var scene = this.getScene();
  56920. if (!scene) {
  56921. return;
  56922. }
  56923. var index = scene.multiMaterials.indexOf(this);
  56924. if (index >= 0) {
  56925. scene.multiMaterials.splice(index, 1);
  56926. }
  56927. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56928. };
  56929. return MultiMaterial;
  56930. }(BABYLON.Material));
  56931. BABYLON.MultiMaterial = MultiMaterial;
  56932. })(BABYLON || (BABYLON = {}));
  56933. //# sourceMappingURL=babylon.multiMaterial.js.map
  56934. var BABYLON;
  56935. (function (BABYLON) {
  56936. var FreeCameraTouchInput = /** @class */ (function () {
  56937. function FreeCameraTouchInput() {
  56938. this._offsetX = null;
  56939. this._offsetY = null;
  56940. this._pointerPressed = new Array();
  56941. this.touchAngularSensibility = 200000.0;
  56942. this.touchMoveSensibility = 250.0;
  56943. }
  56944. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56945. var _this = this;
  56946. var previousPosition = null;
  56947. if (this._pointerInput === undefined) {
  56948. this._onLostFocus = function (evt) {
  56949. _this._offsetX = null;
  56950. _this._offsetY = null;
  56951. };
  56952. this._pointerInput = function (p, s) {
  56953. var evt = p.event;
  56954. if (evt.pointerType === "mouse") {
  56955. return;
  56956. }
  56957. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56958. if (!noPreventDefault) {
  56959. evt.preventDefault();
  56960. }
  56961. _this._pointerPressed.push(evt.pointerId);
  56962. if (_this._pointerPressed.length !== 1) {
  56963. return;
  56964. }
  56965. previousPosition = {
  56966. x: evt.clientX,
  56967. y: evt.clientY
  56968. };
  56969. }
  56970. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56971. if (!noPreventDefault) {
  56972. evt.preventDefault();
  56973. }
  56974. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56975. if (index === -1) {
  56976. return;
  56977. }
  56978. _this._pointerPressed.splice(index, 1);
  56979. if (index != 0) {
  56980. return;
  56981. }
  56982. previousPosition = null;
  56983. _this._offsetX = null;
  56984. _this._offsetY = null;
  56985. }
  56986. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56987. if (!noPreventDefault) {
  56988. evt.preventDefault();
  56989. }
  56990. if (!previousPosition) {
  56991. return;
  56992. }
  56993. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56994. if (index != 0) {
  56995. return;
  56996. }
  56997. _this._offsetX = evt.clientX - previousPosition.x;
  56998. _this._offsetY = -(evt.clientY - previousPosition.y);
  56999. }
  57000. };
  57001. }
  57002. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  57003. if (this._onLostFocus) {
  57004. element.addEventListener("blur", this._onLostFocus);
  57005. }
  57006. };
  57007. FreeCameraTouchInput.prototype.detachControl = function (element) {
  57008. if (this._pointerInput && element) {
  57009. if (this._observer) {
  57010. this.camera.getScene().onPointerObservable.remove(this._observer);
  57011. this._observer = null;
  57012. }
  57013. if (this._onLostFocus) {
  57014. element.removeEventListener("blur", this._onLostFocus);
  57015. this._onLostFocus = null;
  57016. }
  57017. this._pointerPressed = [];
  57018. this._offsetX = null;
  57019. this._offsetY = null;
  57020. }
  57021. };
  57022. FreeCameraTouchInput.prototype.checkInputs = function () {
  57023. if (this._offsetX && this._offsetY) {
  57024. var camera = this.camera;
  57025. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  57026. if (this._pointerPressed.length > 1) {
  57027. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  57028. }
  57029. else {
  57030. var speed = camera._computeLocalCameraSpeed();
  57031. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  57032. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  57033. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  57034. }
  57035. }
  57036. };
  57037. FreeCameraTouchInput.prototype.getClassName = function () {
  57038. return "FreeCameraTouchInput";
  57039. };
  57040. FreeCameraTouchInput.prototype.getSimpleName = function () {
  57041. return "touch";
  57042. };
  57043. __decorate([
  57044. BABYLON.serialize()
  57045. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  57046. __decorate([
  57047. BABYLON.serialize()
  57048. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  57049. return FreeCameraTouchInput;
  57050. }());
  57051. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  57052. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  57053. })(BABYLON || (BABYLON = {}));
  57054. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  57055. var BABYLON;
  57056. (function (BABYLON) {
  57057. // We're mainly based on the logic defined into the FreeCamera code
  57058. var TouchCamera = /** @class */ (function (_super) {
  57059. __extends(TouchCamera, _super);
  57060. //-- end properties for backward compatibility for inputs
  57061. function TouchCamera(name, position, scene) {
  57062. var _this = _super.call(this, name, position, scene) || this;
  57063. _this.inputs.addTouch();
  57064. _this._setupInputs();
  57065. return _this;
  57066. }
  57067. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  57068. //-- Begin properties for backward compatibility for inputs
  57069. get: function () {
  57070. var touch = this.inputs.attached["touch"];
  57071. if (touch)
  57072. return touch.touchAngularSensibility;
  57073. return 0;
  57074. },
  57075. set: function (value) {
  57076. var touch = this.inputs.attached["touch"];
  57077. if (touch)
  57078. touch.touchAngularSensibility = value;
  57079. },
  57080. enumerable: true,
  57081. configurable: true
  57082. });
  57083. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  57084. get: function () {
  57085. var touch = this.inputs.attached["touch"];
  57086. if (touch)
  57087. return touch.touchMoveSensibility;
  57088. return 0;
  57089. },
  57090. set: function (value) {
  57091. var touch = this.inputs.attached["touch"];
  57092. if (touch)
  57093. touch.touchMoveSensibility = value;
  57094. },
  57095. enumerable: true,
  57096. configurable: true
  57097. });
  57098. TouchCamera.prototype.getClassName = function () {
  57099. return "TouchCamera";
  57100. };
  57101. TouchCamera.prototype._setupInputs = function () {
  57102. var mouse = this.inputs.attached["mouse"];
  57103. if (mouse) {
  57104. mouse.touchEnabled = false;
  57105. }
  57106. };
  57107. return TouchCamera;
  57108. }(BABYLON.FreeCamera));
  57109. BABYLON.TouchCamera = TouchCamera;
  57110. })(BABYLON || (BABYLON = {}));
  57111. //# sourceMappingURL=babylon.touchCamera.js.map
  57112. var BABYLON;
  57113. (function (BABYLON) {
  57114. var ProceduralTexture = /** @class */ (function (_super) {
  57115. __extends(ProceduralTexture, _super);
  57116. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  57117. if (fallbackTexture === void 0) { fallbackTexture = null; }
  57118. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57119. if (isCube === void 0) { isCube = false; }
  57120. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57121. _this.isCube = isCube;
  57122. _this.isEnabled = true;
  57123. _this._currentRefreshId = -1;
  57124. _this._refreshRate = 1;
  57125. _this._vertexBuffers = {};
  57126. _this._uniforms = new Array();
  57127. _this._samplers = new Array();
  57128. _this._textures = {};
  57129. _this._floats = {};
  57130. _this._floatsArrays = {};
  57131. _this._colors3 = {};
  57132. _this._colors4 = {};
  57133. _this._vectors2 = {};
  57134. _this._vectors3 = {};
  57135. _this._matrices = {};
  57136. _this._fallbackTextureUsed = false;
  57137. scene._proceduralTextures.push(_this);
  57138. _this._engine = scene.getEngine();
  57139. _this.name = name;
  57140. _this.isRenderTarget = true;
  57141. _this._size = size;
  57142. _this._generateMipMaps = generateMipMaps;
  57143. _this.setFragment(fragment);
  57144. _this._fallbackTexture = fallbackTexture;
  57145. if (isCube) {
  57146. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  57147. _this.setFloat("face", 0);
  57148. }
  57149. else {
  57150. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57151. }
  57152. // VBO
  57153. var vertices = [];
  57154. vertices.push(1, 1);
  57155. vertices.push(-1, 1);
  57156. vertices.push(-1, -1);
  57157. vertices.push(1, -1);
  57158. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57159. _this._createIndexBuffer();
  57160. return _this;
  57161. }
  57162. ProceduralTexture.prototype._createIndexBuffer = function () {
  57163. var engine = this._engine;
  57164. // Indices
  57165. var indices = [];
  57166. indices.push(0);
  57167. indices.push(1);
  57168. indices.push(2);
  57169. indices.push(0);
  57170. indices.push(2);
  57171. indices.push(3);
  57172. this._indexBuffer = engine.createIndexBuffer(indices);
  57173. };
  57174. ProceduralTexture.prototype._rebuild = function () {
  57175. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57176. if (vb) {
  57177. vb._rebuild();
  57178. }
  57179. this._createIndexBuffer();
  57180. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57181. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57182. }
  57183. };
  57184. ProceduralTexture.prototype.reset = function () {
  57185. if (this._effect === undefined) {
  57186. return;
  57187. }
  57188. var engine = this._engine;
  57189. engine._releaseEffect(this._effect);
  57190. };
  57191. ProceduralTexture.prototype.isReady = function () {
  57192. var _this = this;
  57193. var engine = this._engine;
  57194. var shaders;
  57195. if (!this._fragment) {
  57196. return false;
  57197. }
  57198. if (this._fallbackTextureUsed) {
  57199. return true;
  57200. }
  57201. if (this._fragment.fragmentElement !== undefined) {
  57202. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57203. }
  57204. else {
  57205. shaders = { vertex: "procedural", fragment: this._fragment };
  57206. }
  57207. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57208. _this.releaseInternalTexture();
  57209. if (_this._fallbackTexture) {
  57210. _this._texture = _this._fallbackTexture._texture;
  57211. if (_this._texture) {
  57212. _this._texture.incrementReferences();
  57213. }
  57214. }
  57215. _this._fallbackTextureUsed = true;
  57216. });
  57217. return this._effect.isReady();
  57218. };
  57219. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57220. this._currentRefreshId = -1;
  57221. };
  57222. ProceduralTexture.prototype.setFragment = function (fragment) {
  57223. this._fragment = fragment;
  57224. };
  57225. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57226. get: function () {
  57227. return this._refreshRate;
  57228. },
  57229. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57230. set: function (value) {
  57231. this._refreshRate = value;
  57232. this.resetRefreshCounter();
  57233. },
  57234. enumerable: true,
  57235. configurable: true
  57236. });
  57237. ProceduralTexture.prototype._shouldRender = function () {
  57238. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57239. return false;
  57240. }
  57241. if (this._fallbackTextureUsed) {
  57242. return false;
  57243. }
  57244. if (this._currentRefreshId === -1) {
  57245. this._currentRefreshId = 1;
  57246. return true;
  57247. }
  57248. if (this.refreshRate === this._currentRefreshId) {
  57249. this._currentRefreshId = 1;
  57250. return true;
  57251. }
  57252. this._currentRefreshId++;
  57253. return false;
  57254. };
  57255. ProceduralTexture.prototype.getRenderSize = function () {
  57256. return this._size;
  57257. };
  57258. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57259. if (this._fallbackTextureUsed) {
  57260. return;
  57261. }
  57262. this.releaseInternalTexture();
  57263. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57264. };
  57265. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57266. if (this._uniforms.indexOf(uniformName) === -1) {
  57267. this._uniforms.push(uniformName);
  57268. }
  57269. };
  57270. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57271. if (this._samplers.indexOf(name) === -1) {
  57272. this._samplers.push(name);
  57273. }
  57274. this._textures[name] = texture;
  57275. return this;
  57276. };
  57277. ProceduralTexture.prototype.setFloat = function (name, value) {
  57278. this._checkUniform(name);
  57279. this._floats[name] = value;
  57280. return this;
  57281. };
  57282. ProceduralTexture.prototype.setFloats = function (name, value) {
  57283. this._checkUniform(name);
  57284. this._floatsArrays[name] = value;
  57285. return this;
  57286. };
  57287. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57288. this._checkUniform(name);
  57289. this._colors3[name] = value;
  57290. return this;
  57291. };
  57292. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57293. this._checkUniform(name);
  57294. this._colors4[name] = value;
  57295. return this;
  57296. };
  57297. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57298. this._checkUniform(name);
  57299. this._vectors2[name] = value;
  57300. return this;
  57301. };
  57302. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57303. this._checkUniform(name);
  57304. this._vectors3[name] = value;
  57305. return this;
  57306. };
  57307. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57308. this._checkUniform(name);
  57309. this._matrices[name] = value;
  57310. return this;
  57311. };
  57312. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57313. var scene = this.getScene();
  57314. if (!scene) {
  57315. return;
  57316. }
  57317. var engine = this._engine;
  57318. // Render
  57319. engine.enableEffect(this._effect);
  57320. engine.setState(false);
  57321. // Texture
  57322. for (var name in this._textures) {
  57323. this._effect.setTexture(name, this._textures[name]);
  57324. }
  57325. // Float
  57326. for (name in this._floats) {
  57327. this._effect.setFloat(name, this._floats[name]);
  57328. }
  57329. // Floats
  57330. for (name in this._floatsArrays) {
  57331. this._effect.setArray(name, this._floatsArrays[name]);
  57332. }
  57333. // Color3
  57334. for (name in this._colors3) {
  57335. this._effect.setColor3(name, this._colors3[name]);
  57336. }
  57337. // Color4
  57338. for (name in this._colors4) {
  57339. var color = this._colors4[name];
  57340. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57341. }
  57342. // Vector2
  57343. for (name in this._vectors2) {
  57344. this._effect.setVector2(name, this._vectors2[name]);
  57345. }
  57346. // Vector3
  57347. for (name in this._vectors3) {
  57348. this._effect.setVector3(name, this._vectors3[name]);
  57349. }
  57350. // Matrix
  57351. for (name in this._matrices) {
  57352. this._effect.setMatrix(name, this._matrices[name]);
  57353. }
  57354. if (!this._texture) {
  57355. return;
  57356. }
  57357. if (this.isCube) {
  57358. for (var face = 0; face < 6; face++) {
  57359. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57360. // VBOs
  57361. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57362. this._effect.setFloat("face", face);
  57363. // Clear
  57364. engine.clear(scene.clearColor, true, true, true);
  57365. // Draw order
  57366. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57367. // Mipmaps
  57368. if (face === 5) {
  57369. engine.generateMipMapsForCubemap(this._texture);
  57370. }
  57371. }
  57372. }
  57373. else {
  57374. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57375. // VBOs
  57376. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57377. // Clear
  57378. engine.clear(scene.clearColor, true, true, true);
  57379. // Draw order
  57380. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57381. }
  57382. // Unbind
  57383. engine.unBindFramebuffer(this._texture, this.isCube);
  57384. if (this.onGenerated) {
  57385. this.onGenerated();
  57386. }
  57387. };
  57388. ProceduralTexture.prototype.clone = function () {
  57389. var textureSize = this.getSize();
  57390. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57391. // Base texture
  57392. newTexture.hasAlpha = this.hasAlpha;
  57393. newTexture.level = this.level;
  57394. // RenderTarget Texture
  57395. newTexture.coordinatesMode = this.coordinatesMode;
  57396. return newTexture;
  57397. };
  57398. ProceduralTexture.prototype.dispose = function () {
  57399. var scene = this.getScene();
  57400. if (!scene) {
  57401. return;
  57402. }
  57403. var index = scene._proceduralTextures.indexOf(this);
  57404. if (index >= 0) {
  57405. scene._proceduralTextures.splice(index, 1);
  57406. }
  57407. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57408. if (vertexBuffer) {
  57409. vertexBuffer.dispose();
  57410. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57411. }
  57412. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57413. this._indexBuffer = null;
  57414. }
  57415. _super.prototype.dispose.call(this);
  57416. };
  57417. return ProceduralTexture;
  57418. }(BABYLON.Texture));
  57419. BABYLON.ProceduralTexture = ProceduralTexture;
  57420. })(BABYLON || (BABYLON = {}));
  57421. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57422. var BABYLON;
  57423. (function (BABYLON) {
  57424. var CustomProceduralTexture = /** @class */ (function (_super) {
  57425. __extends(CustomProceduralTexture, _super);
  57426. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57427. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57428. _this._animate = true;
  57429. _this._time = 0;
  57430. _this._texturePath = texturePath;
  57431. //Try to load json
  57432. _this.loadJson(texturePath);
  57433. _this.refreshRate = 1;
  57434. return _this;
  57435. }
  57436. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57437. var _this = this;
  57438. var noConfigFile = function () {
  57439. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57440. try {
  57441. _this.setFragment(_this._texturePath);
  57442. }
  57443. catch (ex) {
  57444. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57445. }
  57446. };
  57447. var configFileUrl = jsonUrl + "/config.json";
  57448. var xhr = new XMLHttpRequest();
  57449. xhr.open("GET", configFileUrl, true);
  57450. xhr.addEventListener("load", function () {
  57451. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57452. try {
  57453. _this._config = JSON.parse(xhr.response);
  57454. _this.updateShaderUniforms();
  57455. _this.updateTextures();
  57456. _this.setFragment(_this._texturePath + "/custom");
  57457. _this._animate = _this._config.animate;
  57458. _this.refreshRate = _this._config.refreshrate;
  57459. }
  57460. catch (ex) {
  57461. noConfigFile();
  57462. }
  57463. }
  57464. else {
  57465. noConfigFile();
  57466. }
  57467. }, false);
  57468. xhr.addEventListener("error", function () {
  57469. noConfigFile();
  57470. }, false);
  57471. try {
  57472. xhr.send();
  57473. }
  57474. catch (ex) {
  57475. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57476. }
  57477. };
  57478. CustomProceduralTexture.prototype.isReady = function () {
  57479. if (!_super.prototype.isReady.call(this)) {
  57480. return false;
  57481. }
  57482. for (var name in this._textures) {
  57483. var texture = this._textures[name];
  57484. if (!texture.isReady()) {
  57485. return false;
  57486. }
  57487. }
  57488. return true;
  57489. };
  57490. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57491. var scene = this.getScene();
  57492. if (this._animate && scene) {
  57493. this._time += scene.getAnimationRatio() * 0.03;
  57494. this.updateShaderUniforms();
  57495. }
  57496. _super.prototype.render.call(this, useCameraPostProcess);
  57497. };
  57498. CustomProceduralTexture.prototype.updateTextures = function () {
  57499. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57500. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57501. }
  57502. };
  57503. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57504. if (this._config) {
  57505. for (var j = 0; j < this._config.uniforms.length; j++) {
  57506. var uniform = this._config.uniforms[j];
  57507. switch (uniform.type) {
  57508. case "float":
  57509. this.setFloat(uniform.name, uniform.value);
  57510. break;
  57511. case "color3":
  57512. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57513. break;
  57514. case "color4":
  57515. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57516. break;
  57517. case "vector2":
  57518. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57519. break;
  57520. case "vector3":
  57521. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57522. break;
  57523. }
  57524. }
  57525. }
  57526. this.setFloat("time", this._time);
  57527. };
  57528. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57529. get: function () {
  57530. return this._animate;
  57531. },
  57532. set: function (value) {
  57533. this._animate = value;
  57534. },
  57535. enumerable: true,
  57536. configurable: true
  57537. });
  57538. return CustomProceduralTexture;
  57539. }(BABYLON.ProceduralTexture));
  57540. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57541. })(BABYLON || (BABYLON = {}));
  57542. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57543. var BABYLON;
  57544. (function (BABYLON) {
  57545. var FreeCameraGamepadInput = /** @class */ (function () {
  57546. function FreeCameraGamepadInput() {
  57547. this.gamepadAngularSensibility = 200;
  57548. this.gamepadMoveSensibility = 40;
  57549. // private members
  57550. this._cameraTransform = BABYLON.Matrix.Identity();
  57551. this._deltaTransform = BABYLON.Vector3.Zero();
  57552. this._vector3 = BABYLON.Vector3.Zero();
  57553. this._vector2 = BABYLON.Vector2.Zero();
  57554. }
  57555. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57556. var _this = this;
  57557. var manager = this.camera.getScene().gamepadManager;
  57558. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57559. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57560. // prioritize XBOX gamepads.
  57561. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57562. _this.gamepad = gamepad;
  57563. }
  57564. }
  57565. });
  57566. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57567. if (_this.gamepad === gamepad) {
  57568. _this.gamepad = null;
  57569. }
  57570. });
  57571. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57572. };
  57573. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57574. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57575. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57576. this.gamepad = null;
  57577. };
  57578. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57579. if (this.gamepad && this.gamepad.leftStick) {
  57580. var camera = this.camera;
  57581. var LSValues = this.gamepad.leftStick;
  57582. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57583. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57584. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57585. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57586. var RSValues = this.gamepad.rightStick;
  57587. if (RSValues) {
  57588. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57589. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57590. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57591. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57592. }
  57593. else {
  57594. RSValues = { x: 0, y: 0 };
  57595. }
  57596. if (!camera.rotationQuaternion) {
  57597. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57598. }
  57599. else {
  57600. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57601. }
  57602. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57603. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57604. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57605. camera.cameraDirection.addInPlace(this._deltaTransform);
  57606. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57607. camera.cameraRotation.addInPlace(this._vector2);
  57608. }
  57609. };
  57610. FreeCameraGamepadInput.prototype.getClassName = function () {
  57611. return "FreeCameraGamepadInput";
  57612. };
  57613. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57614. return "gamepad";
  57615. };
  57616. __decorate([
  57617. BABYLON.serialize()
  57618. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57619. __decorate([
  57620. BABYLON.serialize()
  57621. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57622. return FreeCameraGamepadInput;
  57623. }());
  57624. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57625. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57626. })(BABYLON || (BABYLON = {}));
  57627. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57628. var BABYLON;
  57629. (function (BABYLON) {
  57630. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57631. function ArcRotateCameraGamepadInput() {
  57632. this.gamepadRotationSensibility = 80;
  57633. this.gamepadMoveSensibility = 40;
  57634. }
  57635. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57636. var _this = this;
  57637. var manager = this.camera.getScene().gamepadManager;
  57638. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57639. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57640. // prioritize XBOX gamepads.
  57641. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57642. _this.gamepad = gamepad;
  57643. }
  57644. }
  57645. });
  57646. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57647. if (_this.gamepad === gamepad) {
  57648. _this.gamepad = null;
  57649. }
  57650. });
  57651. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57652. };
  57653. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57654. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57655. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57656. this.gamepad = null;
  57657. };
  57658. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57659. if (this.gamepad) {
  57660. var camera = this.camera;
  57661. var RSValues = this.gamepad.rightStick;
  57662. if (RSValues) {
  57663. if (RSValues.x != 0) {
  57664. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57665. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57666. camera.inertialAlphaOffset += normalizedRX;
  57667. }
  57668. }
  57669. if (RSValues.y != 0) {
  57670. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57671. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57672. camera.inertialBetaOffset += normalizedRY;
  57673. }
  57674. }
  57675. }
  57676. var LSValues = this.gamepad.leftStick;
  57677. if (LSValues && LSValues.y != 0) {
  57678. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57679. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57680. this.camera.inertialRadiusOffset -= normalizedLY;
  57681. }
  57682. }
  57683. }
  57684. };
  57685. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57686. return "ArcRotateCameraGamepadInput";
  57687. };
  57688. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57689. return "gamepad";
  57690. };
  57691. __decorate([
  57692. BABYLON.serialize()
  57693. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57694. __decorate([
  57695. BABYLON.serialize()
  57696. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57697. return ArcRotateCameraGamepadInput;
  57698. }());
  57699. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57700. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57701. })(BABYLON || (BABYLON = {}));
  57702. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57703. var BABYLON;
  57704. (function (BABYLON) {
  57705. var GamepadManager = /** @class */ (function () {
  57706. function GamepadManager(_scene) {
  57707. var _this = this;
  57708. this._scene = _scene;
  57709. this._babylonGamepads = [];
  57710. this._oneGamepadConnected = false;
  57711. this._isMonitoring = false;
  57712. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57713. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57714. this._gamepadEventSupported = false;
  57715. }
  57716. else {
  57717. this._gamepadEventSupported = 'GamepadEvent' in window;
  57718. this._gamepadSupport = (navigator.getGamepads ||
  57719. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57720. }
  57721. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57722. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57723. for (var i in _this._babylonGamepads) {
  57724. var gamepad = _this._babylonGamepads[i];
  57725. if (gamepad && gamepad._isConnected) {
  57726. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57727. }
  57728. }
  57729. });
  57730. this._onGamepadConnectedEvent = function (evt) {
  57731. var gamepad = evt.gamepad;
  57732. if (gamepad.index in _this._babylonGamepads) {
  57733. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57734. return;
  57735. }
  57736. }
  57737. var newGamepad;
  57738. if (_this._babylonGamepads[gamepad.index]) {
  57739. newGamepad = _this._babylonGamepads[gamepad.index];
  57740. newGamepad.browserGamepad = gamepad;
  57741. newGamepad._isConnected = true;
  57742. }
  57743. else {
  57744. newGamepad = _this._addNewGamepad(gamepad);
  57745. }
  57746. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57747. _this._startMonitoringGamepads();
  57748. };
  57749. this._onGamepadDisconnectedEvent = function (evt) {
  57750. var gamepad = evt.gamepad;
  57751. // Remove the gamepad from the list of gamepads to monitor.
  57752. for (var i in _this._babylonGamepads) {
  57753. if (_this._babylonGamepads[i].index === gamepad.index) {
  57754. var disconnectedGamepad = _this._babylonGamepads[i];
  57755. disconnectedGamepad._isConnected = false;
  57756. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57757. break;
  57758. }
  57759. }
  57760. };
  57761. if (this._gamepadSupport) {
  57762. //first add already-connected gamepads
  57763. this._updateGamepadObjects();
  57764. if (this._babylonGamepads.length) {
  57765. this._startMonitoringGamepads();
  57766. }
  57767. // Checking if the gamepad connected event is supported (like in Firefox)
  57768. if (this._gamepadEventSupported) {
  57769. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57770. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57771. }
  57772. else {
  57773. this._startMonitoringGamepads();
  57774. }
  57775. }
  57776. }
  57777. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57778. get: function () {
  57779. return this._babylonGamepads;
  57780. },
  57781. enumerable: true,
  57782. configurable: true
  57783. });
  57784. GamepadManager.prototype.getGamepadByType = function (type) {
  57785. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57786. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57787. var gamepad = _a[_i];
  57788. if (gamepad && gamepad.type === type) {
  57789. return gamepad;
  57790. }
  57791. }
  57792. return null;
  57793. };
  57794. GamepadManager.prototype.dispose = function () {
  57795. if (this._gamepadEventSupported) {
  57796. if (this._onGamepadConnectedEvent) {
  57797. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57798. }
  57799. if (this._onGamepadDisconnectedEvent) {
  57800. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57801. }
  57802. this._onGamepadConnectedEvent = null;
  57803. this._onGamepadDisconnectedEvent = null;
  57804. }
  57805. this._babylonGamepads.forEach(function (gamepad) {
  57806. gamepad.dispose();
  57807. });
  57808. this.onGamepadConnectedObservable.clear();
  57809. this.onGamepadDisconnectedObservable.clear();
  57810. this._oneGamepadConnected = false;
  57811. this._stopMonitoringGamepads();
  57812. this._babylonGamepads = [];
  57813. };
  57814. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57815. if (!this._oneGamepadConnected) {
  57816. this._oneGamepadConnected = true;
  57817. }
  57818. var newGamepad;
  57819. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57820. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57821. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57822. }
  57823. else if (gamepad.pose) {
  57824. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57825. }
  57826. else {
  57827. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57828. }
  57829. this._babylonGamepads[newGamepad.index] = newGamepad;
  57830. return newGamepad;
  57831. };
  57832. GamepadManager.prototype._startMonitoringGamepads = function () {
  57833. if (!this._isMonitoring) {
  57834. this._isMonitoring = true;
  57835. //back-comp
  57836. if (!this._scene) {
  57837. this._checkGamepadsStatus();
  57838. }
  57839. }
  57840. };
  57841. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57842. this._isMonitoring = false;
  57843. };
  57844. GamepadManager.prototype._checkGamepadsStatus = function () {
  57845. var _this = this;
  57846. // Hack to be compatible Chrome
  57847. this._updateGamepadObjects();
  57848. for (var i in this._babylonGamepads) {
  57849. var gamepad = this._babylonGamepads[i];
  57850. if (!gamepad || !gamepad.isConnected) {
  57851. continue;
  57852. }
  57853. gamepad.update();
  57854. }
  57855. if (this._isMonitoring && !this._scene) {
  57856. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57857. }
  57858. };
  57859. // This function is called only on Chrome, which does not properly support
  57860. // connection/disconnection events and forces you to recopy again the gamepad object
  57861. GamepadManager.prototype._updateGamepadObjects = function () {
  57862. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57863. for (var i = 0; i < gamepads.length; i++) {
  57864. if (gamepads[i]) {
  57865. if (!this._babylonGamepads[gamepads[i].index]) {
  57866. var newGamepad = this._addNewGamepad(gamepads[i]);
  57867. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57868. }
  57869. else {
  57870. // Forced to copy again this object for Chrome for unknown reason
  57871. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57872. if (!this._babylonGamepads[i].isConnected) {
  57873. this._babylonGamepads[i]._isConnected = true;
  57874. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57875. }
  57876. }
  57877. }
  57878. }
  57879. };
  57880. return GamepadManager;
  57881. }());
  57882. BABYLON.GamepadManager = GamepadManager;
  57883. })(BABYLON || (BABYLON = {}));
  57884. //# sourceMappingURL=babylon.gamepadManager.js.map
  57885. var BABYLON;
  57886. (function (BABYLON) {
  57887. var StickValues = /** @class */ (function () {
  57888. function StickValues(x, y) {
  57889. this.x = x;
  57890. this.y = y;
  57891. }
  57892. return StickValues;
  57893. }());
  57894. BABYLON.StickValues = StickValues;
  57895. var Gamepad = /** @class */ (function () {
  57896. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57897. if (leftStickX === void 0) { leftStickX = 0; }
  57898. if (leftStickY === void 0) { leftStickY = 1; }
  57899. if (rightStickX === void 0) { rightStickX = 2; }
  57900. if (rightStickY === void 0) { rightStickY = 3; }
  57901. this.id = id;
  57902. this.index = index;
  57903. this.browserGamepad = browserGamepad;
  57904. this._isConnected = true;
  57905. this._invertLeftStickY = false;
  57906. this.type = Gamepad.GAMEPAD;
  57907. this._leftStickAxisX = leftStickX;
  57908. this._leftStickAxisY = leftStickY;
  57909. this._rightStickAxisX = rightStickX;
  57910. this._rightStickAxisY = rightStickY;
  57911. if (this.browserGamepad.axes.length >= 2) {
  57912. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57913. }
  57914. if (this.browserGamepad.axes.length >= 4) {
  57915. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57916. }
  57917. }
  57918. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57919. get: function () {
  57920. return this._isConnected;
  57921. },
  57922. enumerable: true,
  57923. configurable: true
  57924. });
  57925. Gamepad.prototype.onleftstickchanged = function (callback) {
  57926. this._onleftstickchanged = callback;
  57927. };
  57928. Gamepad.prototype.onrightstickchanged = function (callback) {
  57929. this._onrightstickchanged = callback;
  57930. };
  57931. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57932. get: function () {
  57933. return this._leftStick;
  57934. },
  57935. set: function (newValues) {
  57936. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57937. this._onleftstickchanged(newValues);
  57938. }
  57939. this._leftStick = newValues;
  57940. },
  57941. enumerable: true,
  57942. configurable: true
  57943. });
  57944. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57945. get: function () {
  57946. return this._rightStick;
  57947. },
  57948. set: function (newValues) {
  57949. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57950. this._onrightstickchanged(newValues);
  57951. }
  57952. this._rightStick = newValues;
  57953. },
  57954. enumerable: true,
  57955. configurable: true
  57956. });
  57957. Gamepad.prototype.update = function () {
  57958. if (this._leftStick) {
  57959. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57960. if (this._invertLeftStickY) {
  57961. this.leftStick.y *= -1;
  57962. }
  57963. }
  57964. if (this._rightStick) {
  57965. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57966. }
  57967. };
  57968. Gamepad.prototype.dispose = function () {
  57969. };
  57970. Gamepad.GAMEPAD = 0;
  57971. Gamepad.GENERIC = 1;
  57972. Gamepad.XBOX = 2;
  57973. Gamepad.POSE_ENABLED = 3;
  57974. return Gamepad;
  57975. }());
  57976. BABYLON.Gamepad = Gamepad;
  57977. var GenericPad = /** @class */ (function (_super) {
  57978. __extends(GenericPad, _super);
  57979. function GenericPad(id, index, browserGamepad) {
  57980. var _this = _super.call(this, id, index, browserGamepad) || this;
  57981. _this.onButtonDownObservable = new BABYLON.Observable();
  57982. _this.onButtonUpObservable = new BABYLON.Observable();
  57983. _this.type = Gamepad.GENERIC;
  57984. _this._buttons = new Array(browserGamepad.buttons.length);
  57985. return _this;
  57986. }
  57987. GenericPad.prototype.onbuttondown = function (callback) {
  57988. this._onbuttondown = callback;
  57989. };
  57990. GenericPad.prototype.onbuttonup = function (callback) {
  57991. this._onbuttonup = callback;
  57992. };
  57993. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57994. if (newValue !== currentValue) {
  57995. if (newValue === 1) {
  57996. if (this._onbuttondown) {
  57997. this._onbuttondown(buttonIndex);
  57998. }
  57999. this.onButtonDownObservable.notifyObservers(buttonIndex);
  58000. }
  58001. if (newValue === 0) {
  58002. if (this._onbuttonup) {
  58003. this._onbuttonup(buttonIndex);
  58004. }
  58005. this.onButtonUpObservable.notifyObservers(buttonIndex);
  58006. }
  58007. }
  58008. return newValue;
  58009. };
  58010. GenericPad.prototype.update = function () {
  58011. _super.prototype.update.call(this);
  58012. for (var index = 0; index < this._buttons.length; index++) {
  58013. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  58014. }
  58015. };
  58016. GenericPad.prototype.dispose = function () {
  58017. _super.prototype.dispose.call(this);
  58018. this.onButtonDownObservable.clear();
  58019. this.onButtonUpObservable.clear();
  58020. };
  58021. return GenericPad;
  58022. }(Gamepad));
  58023. BABYLON.GenericPad = GenericPad;
  58024. })(BABYLON || (BABYLON = {}));
  58025. //# sourceMappingURL=babylon.gamepad.js.map
  58026. var BABYLON;
  58027. (function (BABYLON) {
  58028. var Xbox360Button;
  58029. (function (Xbox360Button) {
  58030. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  58031. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  58032. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  58033. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  58034. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  58035. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  58036. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  58037. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  58038. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  58039. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  58040. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  58041. var Xbox360Dpad;
  58042. (function (Xbox360Dpad) {
  58043. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  58044. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  58045. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  58046. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  58047. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  58048. var Xbox360Pad = /** @class */ (function (_super) {
  58049. __extends(Xbox360Pad, _super);
  58050. function Xbox360Pad(id, index, gamepad, xboxOne) {
  58051. if (xboxOne === void 0) { xboxOne = false; }
  58052. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  58053. _this._leftTrigger = 0;
  58054. _this._rightTrigger = 0;
  58055. _this.onButtonDownObservable = new BABYLON.Observable();
  58056. _this.onButtonUpObservable = new BABYLON.Observable();
  58057. _this.onPadDownObservable = new BABYLON.Observable();
  58058. _this.onPadUpObservable = new BABYLON.Observable();
  58059. _this._buttonA = 0;
  58060. _this._buttonB = 0;
  58061. _this._buttonX = 0;
  58062. _this._buttonY = 0;
  58063. _this._buttonBack = 0;
  58064. _this._buttonStart = 0;
  58065. _this._buttonLB = 0;
  58066. _this._buttonRB = 0;
  58067. _this._buttonLeftStick = 0;
  58068. _this._buttonRightStick = 0;
  58069. _this._dPadUp = 0;
  58070. _this._dPadDown = 0;
  58071. _this._dPadLeft = 0;
  58072. _this._dPadRight = 0;
  58073. _this._isXboxOnePad = false;
  58074. _this.type = BABYLON.Gamepad.XBOX;
  58075. _this._isXboxOnePad = xboxOne;
  58076. return _this;
  58077. }
  58078. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  58079. this._onlefttriggerchanged = callback;
  58080. };
  58081. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  58082. this._onrighttriggerchanged = callback;
  58083. };
  58084. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  58085. get: function () {
  58086. return this._leftTrigger;
  58087. },
  58088. set: function (newValue) {
  58089. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  58090. this._onlefttriggerchanged(newValue);
  58091. }
  58092. this._leftTrigger = newValue;
  58093. },
  58094. enumerable: true,
  58095. configurable: true
  58096. });
  58097. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  58098. get: function () {
  58099. return this._rightTrigger;
  58100. },
  58101. set: function (newValue) {
  58102. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  58103. this._onrighttriggerchanged(newValue);
  58104. }
  58105. this._rightTrigger = newValue;
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. Xbox360Pad.prototype.onbuttondown = function (callback) {
  58111. this._onbuttondown = callback;
  58112. };
  58113. Xbox360Pad.prototype.onbuttonup = function (callback) {
  58114. this._onbuttonup = callback;
  58115. };
  58116. Xbox360Pad.prototype.ondpaddown = function (callback) {
  58117. this._ondpaddown = callback;
  58118. };
  58119. Xbox360Pad.prototype.ondpadup = function (callback) {
  58120. this._ondpadup = callback;
  58121. };
  58122. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  58123. if (newValue !== currentValue) {
  58124. if (newValue === 1) {
  58125. if (this._onbuttondown) {
  58126. this._onbuttondown(buttonType);
  58127. }
  58128. this.onButtonDownObservable.notifyObservers(buttonType);
  58129. }
  58130. if (newValue === 0) {
  58131. if (this._onbuttonup) {
  58132. this._onbuttonup(buttonType);
  58133. }
  58134. this.onButtonUpObservable.notifyObservers(buttonType);
  58135. }
  58136. }
  58137. return newValue;
  58138. };
  58139. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  58140. if (newValue !== currentValue) {
  58141. if (newValue === 1) {
  58142. if (this._ondpaddown) {
  58143. this._ondpaddown(buttonType);
  58144. }
  58145. this.onPadDownObservable.notifyObservers(buttonType);
  58146. }
  58147. if (newValue === 0) {
  58148. if (this._ondpadup) {
  58149. this._ondpadup(buttonType);
  58150. }
  58151. this.onPadUpObservable.notifyObservers(buttonType);
  58152. }
  58153. }
  58154. return newValue;
  58155. };
  58156. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58157. get: function () {
  58158. return this._buttonA;
  58159. },
  58160. set: function (value) {
  58161. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58162. },
  58163. enumerable: true,
  58164. configurable: true
  58165. });
  58166. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58167. get: function () {
  58168. return this._buttonB;
  58169. },
  58170. set: function (value) {
  58171. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58172. },
  58173. enumerable: true,
  58174. configurable: true
  58175. });
  58176. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58177. get: function () {
  58178. return this._buttonX;
  58179. },
  58180. set: function (value) {
  58181. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58182. },
  58183. enumerable: true,
  58184. configurable: true
  58185. });
  58186. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58187. get: function () {
  58188. return this._buttonY;
  58189. },
  58190. set: function (value) {
  58191. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58192. },
  58193. enumerable: true,
  58194. configurable: true
  58195. });
  58196. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58197. get: function () {
  58198. return this._buttonStart;
  58199. },
  58200. set: function (value) {
  58201. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58202. },
  58203. enumerable: true,
  58204. configurable: true
  58205. });
  58206. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58207. get: function () {
  58208. return this._buttonBack;
  58209. },
  58210. set: function (value) {
  58211. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58212. },
  58213. enumerable: true,
  58214. configurable: true
  58215. });
  58216. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58217. get: function () {
  58218. return this._buttonLB;
  58219. },
  58220. set: function (value) {
  58221. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58222. },
  58223. enumerable: true,
  58224. configurable: true
  58225. });
  58226. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58227. get: function () {
  58228. return this._buttonRB;
  58229. },
  58230. set: function (value) {
  58231. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58232. },
  58233. enumerable: true,
  58234. configurable: true
  58235. });
  58236. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58237. get: function () {
  58238. return this._buttonLeftStick;
  58239. },
  58240. set: function (value) {
  58241. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58242. },
  58243. enumerable: true,
  58244. configurable: true
  58245. });
  58246. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58247. get: function () {
  58248. return this._buttonRightStick;
  58249. },
  58250. set: function (value) {
  58251. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58252. },
  58253. enumerable: true,
  58254. configurable: true
  58255. });
  58256. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58257. get: function () {
  58258. return this._dPadUp;
  58259. },
  58260. set: function (value) {
  58261. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58262. },
  58263. enumerable: true,
  58264. configurable: true
  58265. });
  58266. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58267. get: function () {
  58268. return this._dPadDown;
  58269. },
  58270. set: function (value) {
  58271. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58272. },
  58273. enumerable: true,
  58274. configurable: true
  58275. });
  58276. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58277. get: function () {
  58278. return this._dPadLeft;
  58279. },
  58280. set: function (value) {
  58281. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58282. },
  58283. enumerable: true,
  58284. configurable: true
  58285. });
  58286. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58287. get: function () {
  58288. return this._dPadRight;
  58289. },
  58290. set: function (value) {
  58291. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58292. },
  58293. enumerable: true,
  58294. configurable: true
  58295. });
  58296. Xbox360Pad.prototype.update = function () {
  58297. _super.prototype.update.call(this);
  58298. if (this._isXboxOnePad) {
  58299. this.buttonA = this.browserGamepad.buttons[0].value;
  58300. this.buttonB = this.browserGamepad.buttons[1].value;
  58301. this.buttonX = this.browserGamepad.buttons[2].value;
  58302. this.buttonY = this.browserGamepad.buttons[3].value;
  58303. this.buttonLB = this.browserGamepad.buttons[4].value;
  58304. this.buttonRB = this.browserGamepad.buttons[5].value;
  58305. this.leftTrigger = this.browserGamepad.axes[2];
  58306. this.rightTrigger = this.browserGamepad.axes[5];
  58307. this.buttonBack = this.browserGamepad.buttons[9].value;
  58308. this.buttonStart = this.browserGamepad.buttons[8].value;
  58309. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58310. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58311. this.dPadUp = this.browserGamepad.buttons[11].value;
  58312. this.dPadDown = this.browserGamepad.buttons[12].value;
  58313. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58314. this.dPadRight = this.browserGamepad.buttons[14].value;
  58315. }
  58316. else {
  58317. this.buttonA = this.browserGamepad.buttons[0].value;
  58318. this.buttonB = this.browserGamepad.buttons[1].value;
  58319. this.buttonX = this.browserGamepad.buttons[2].value;
  58320. this.buttonY = this.browserGamepad.buttons[3].value;
  58321. this.buttonLB = this.browserGamepad.buttons[4].value;
  58322. this.buttonRB = this.browserGamepad.buttons[5].value;
  58323. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58324. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58325. this.buttonBack = this.browserGamepad.buttons[8].value;
  58326. this.buttonStart = this.browserGamepad.buttons[9].value;
  58327. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58328. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58329. this.dPadUp = this.browserGamepad.buttons[12].value;
  58330. this.dPadDown = this.browserGamepad.buttons[13].value;
  58331. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58332. this.dPadRight = this.browserGamepad.buttons[15].value;
  58333. }
  58334. };
  58335. Xbox360Pad.prototype.dispose = function () {
  58336. _super.prototype.dispose.call(this);
  58337. this.onButtonDownObservable.clear();
  58338. this.onButtonUpObservable.clear();
  58339. this.onPadDownObservable.clear();
  58340. this.onPadUpObservable.clear();
  58341. };
  58342. return Xbox360Pad;
  58343. }(BABYLON.Gamepad));
  58344. BABYLON.Xbox360Pad = Xbox360Pad;
  58345. })(BABYLON || (BABYLON = {}));
  58346. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58347. var BABYLON;
  58348. (function (BABYLON) {
  58349. var PoseEnabledControllerType;
  58350. (function (PoseEnabledControllerType) {
  58351. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58352. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58353. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58354. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58355. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58356. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58357. var PoseEnabledControllerHelper = /** @class */ (function () {
  58358. function PoseEnabledControllerHelper() {
  58359. }
  58360. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58361. // Oculus Touch
  58362. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58363. return new BABYLON.OculusTouchController(vrGamepad);
  58364. }
  58365. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58366. return new BABYLON.WindowsMotionController(vrGamepad);
  58367. }
  58368. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58369. return new BABYLON.ViveController(vrGamepad);
  58370. }
  58371. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58372. return new BABYLON.GearVRController(vrGamepad);
  58373. }
  58374. else {
  58375. return new BABYLON.GenericController(vrGamepad);
  58376. }
  58377. };
  58378. return PoseEnabledControllerHelper;
  58379. }());
  58380. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58381. var PoseEnabledController = /** @class */ (function (_super) {
  58382. __extends(PoseEnabledController, _super);
  58383. function PoseEnabledController(browserGamepad) {
  58384. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58385. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58386. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58387. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58388. // Represents device position and rotation in babylon space
  58389. _this.devicePosition = BABYLON.Vector3.Zero();
  58390. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58391. _this.deviceScaleFactor = 1;
  58392. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58393. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58394. _this._workingMatrix = BABYLON.Matrix.Identity();
  58395. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58396. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58397. _this.position = BABYLON.Vector3.Zero();
  58398. _this.rotationQuaternion = new BABYLON.Quaternion();
  58399. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58400. _this._calculatedRotation = new BABYLON.Quaternion();
  58401. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58402. return _this;
  58403. }
  58404. PoseEnabledController.prototype.update = function () {
  58405. _super.prototype.update.call(this);
  58406. var pose = this.browserGamepad.pose;
  58407. this.updateFromDevice(pose);
  58408. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58409. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58410. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58411. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58412. if (this._mesh) {
  58413. this._mesh.position.copyFrom(this.devicePosition);
  58414. if (this._mesh.rotationQuaternion) {
  58415. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58416. }
  58417. }
  58418. };
  58419. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58420. if (poseData) {
  58421. this.rawPose = poseData;
  58422. if (poseData.position) {
  58423. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58424. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58425. this._deviceRoomPosition.z *= -1;
  58426. }
  58427. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58428. this._calculatedPosition.addInPlace(this.position);
  58429. }
  58430. var pose = this.rawPose;
  58431. if (poseData.orientation && pose.orientation) {
  58432. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58433. if (this._mesh) {
  58434. if (this._mesh.getScene().useRightHandedSystem) {
  58435. this._deviceRoomRotationQuaternion.z *= -1;
  58436. this._deviceRoomRotationQuaternion.w *= -1;
  58437. }
  58438. else {
  58439. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58440. }
  58441. }
  58442. // if the camera is set, rotate to the camera's rotation
  58443. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58444. }
  58445. }
  58446. };
  58447. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58448. if (this._mesh) {
  58449. this._mesh.parent = null;
  58450. }
  58451. this._mesh = mesh;
  58452. if (this._poseControlledCamera) {
  58453. this._mesh.parent = this._poseControlledCamera;
  58454. }
  58455. if (!this._mesh.rotationQuaternion) {
  58456. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58457. }
  58458. };
  58459. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58460. this._poseControlledCamera = camera;
  58461. if (this._mesh) {
  58462. this._mesh.parent = this._poseControlledCamera;
  58463. }
  58464. };
  58465. PoseEnabledController.prototype.dispose = function () {
  58466. if (this._mesh) {
  58467. this._mesh.dispose();
  58468. }
  58469. this._mesh = null;
  58470. _super.prototype.dispose.call(this);
  58471. };
  58472. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58473. get: function () {
  58474. return this._mesh;
  58475. },
  58476. enumerable: true,
  58477. configurable: true
  58478. });
  58479. PoseEnabledController.prototype.getForwardRay = function (length) {
  58480. if (length === void 0) { length = 100; }
  58481. if (!this.mesh) {
  58482. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58483. }
  58484. var m = this.mesh.getWorldMatrix();
  58485. var origin = m.getTranslation();
  58486. var forward = new BABYLON.Vector3(0, 0, -1);
  58487. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58488. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58489. return new BABYLON.Ray(origin, direction, length);
  58490. };
  58491. return PoseEnabledController;
  58492. }(BABYLON.Gamepad));
  58493. BABYLON.PoseEnabledController = PoseEnabledController;
  58494. })(BABYLON || (BABYLON = {}));
  58495. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58496. var BABYLON;
  58497. (function (BABYLON) {
  58498. var WebVRController = /** @class */ (function (_super) {
  58499. __extends(WebVRController, _super);
  58500. function WebVRController(vrGamepad) {
  58501. var _this = _super.call(this, vrGamepad) || this;
  58502. // Observables
  58503. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58504. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58505. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58506. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58507. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58508. _this.pad = { x: 0, y: 0 };
  58509. // avoid GC, store state in a tmp object
  58510. _this._changes = {
  58511. pressChanged: false,
  58512. touchChanged: false,
  58513. valueChanged: false,
  58514. changed: false
  58515. };
  58516. _this._buttons = new Array(vrGamepad.buttons.length);
  58517. _this.hand = vrGamepad.hand;
  58518. return _this;
  58519. }
  58520. WebVRController.prototype.onButtonStateChange = function (callback) {
  58521. this._onButtonStateChange = callback;
  58522. };
  58523. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58524. get: function () {
  58525. return this._defaultModel;
  58526. },
  58527. enumerable: true,
  58528. configurable: true
  58529. });
  58530. WebVRController.prototype.update = function () {
  58531. _super.prototype.update.call(this);
  58532. for (var index = 0; index < this._buttons.length; index++) {
  58533. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58534. }
  58535. ;
  58536. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58537. this.pad.x = this.leftStick.x;
  58538. this.pad.y = this.leftStick.y;
  58539. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58540. }
  58541. };
  58542. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58543. if (!newState) {
  58544. newState = {
  58545. pressed: false,
  58546. touched: false,
  58547. value: 0
  58548. };
  58549. }
  58550. if (!currentState) {
  58551. this._buttons[buttonIndex] = {
  58552. pressed: newState.pressed,
  58553. touched: newState.touched,
  58554. value: newState.value
  58555. };
  58556. return;
  58557. }
  58558. this._checkChanges(newState, currentState);
  58559. if (this._changes.changed) {
  58560. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58561. this.handleButtonChange(buttonIndex, newState, this._changes);
  58562. }
  58563. this._buttons[buttonIndex].pressed = newState.pressed;
  58564. this._buttons[buttonIndex].touched = newState.touched;
  58565. // oculus triggers are never 0, thou not touched.
  58566. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58567. };
  58568. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58569. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58570. this._changes.touchChanged = newState.touched !== currentState.touched;
  58571. this._changes.valueChanged = newState.value !== currentState.value;
  58572. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58573. return this._changes;
  58574. };
  58575. WebVRController.prototype.dispose = function () {
  58576. _super.prototype.dispose.call(this);
  58577. this.onTriggerStateChangedObservable.clear();
  58578. this.onMainButtonStateChangedObservable.clear();
  58579. this.onSecondaryButtonStateChangedObservable.clear();
  58580. this.onPadStateChangedObservable.clear();
  58581. this.onPadValuesChangedObservable.clear();
  58582. };
  58583. return WebVRController;
  58584. }(BABYLON.PoseEnabledController));
  58585. BABYLON.WebVRController = WebVRController;
  58586. })(BABYLON || (BABYLON = {}));
  58587. //# sourceMappingURL=babylon.webVRController.js.map
  58588. var BABYLON;
  58589. (function (BABYLON) {
  58590. var OculusTouchController = /** @class */ (function (_super) {
  58591. __extends(OculusTouchController, _super);
  58592. function OculusTouchController(vrGamepad) {
  58593. var _this = _super.call(this, vrGamepad) || this;
  58594. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58595. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58596. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58597. return _this;
  58598. }
  58599. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58600. var _this = this;
  58601. var meshName;
  58602. // Hand
  58603. if (this.hand === 'left') {
  58604. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58605. }
  58606. else {
  58607. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58608. }
  58609. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58610. /*
  58611. Parent Mesh name: oculus_touch_left
  58612. - body
  58613. - trigger
  58614. - thumbstick
  58615. - grip
  58616. - button_y
  58617. - button_x
  58618. - button_enter
  58619. */
  58620. _this._defaultModel = newMeshes[1];
  58621. _this.attachToMesh(_this._defaultModel);
  58622. if (meshLoaded) {
  58623. meshLoaded(_this._defaultModel);
  58624. }
  58625. });
  58626. };
  58627. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58628. // helper getters for left and right hand.
  58629. get: function () {
  58630. if (this.hand === 'right') {
  58631. return this.onMainButtonStateChangedObservable;
  58632. }
  58633. else {
  58634. throw new Error('No A button on left hand');
  58635. }
  58636. },
  58637. enumerable: true,
  58638. configurable: true
  58639. });
  58640. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58641. get: function () {
  58642. if (this.hand === 'right') {
  58643. return this.onSecondaryButtonStateChangedObservable;
  58644. }
  58645. else {
  58646. throw new Error('No B button on left hand');
  58647. }
  58648. },
  58649. enumerable: true,
  58650. configurable: true
  58651. });
  58652. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58653. get: function () {
  58654. if (this.hand === 'left') {
  58655. return this.onMainButtonStateChangedObservable;
  58656. }
  58657. else {
  58658. throw new Error('No X button on right hand');
  58659. }
  58660. },
  58661. enumerable: true,
  58662. configurable: true
  58663. });
  58664. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58665. get: function () {
  58666. if (this.hand === 'left') {
  58667. return this.onSecondaryButtonStateChangedObservable;
  58668. }
  58669. else {
  58670. throw new Error('No Y button on right hand');
  58671. }
  58672. },
  58673. enumerable: true,
  58674. configurable: true
  58675. });
  58676. /*
  58677. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58678. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58679. 2) secondary trigger (same)
  58680. 3) A (right) X (left), touch, pressed = value
  58681. 4) B / Y
  58682. 5) thumb rest
  58683. */
  58684. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58685. var notifyObject = state; //{ state: state, changes: changes };
  58686. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58687. switch (buttonIdx) {
  58688. case 0:
  58689. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58690. return;
  58691. case 1:// index trigger
  58692. if (this._defaultModel) {
  58693. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58694. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58695. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58696. }
  58697. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58698. return;
  58699. case 2:// secondary trigger
  58700. if (this._defaultModel) {
  58701. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58702. }
  58703. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58704. return;
  58705. case 3:
  58706. if (this._defaultModel) {
  58707. if (notifyObject.pressed) {
  58708. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58709. }
  58710. else {
  58711. (this._defaultModel.getChildren()[1]).position.y = 0;
  58712. }
  58713. }
  58714. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58715. return;
  58716. case 4:
  58717. if (this._defaultModel) {
  58718. if (notifyObject.pressed) {
  58719. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58720. }
  58721. else {
  58722. (this._defaultModel.getChildren()[2]).position.y = 0;
  58723. }
  58724. }
  58725. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58726. return;
  58727. case 5:
  58728. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58729. return;
  58730. }
  58731. };
  58732. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58733. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58734. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58735. return OculusTouchController;
  58736. }(BABYLON.WebVRController));
  58737. BABYLON.OculusTouchController = OculusTouchController;
  58738. })(BABYLON || (BABYLON = {}));
  58739. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58740. var BABYLON;
  58741. (function (BABYLON) {
  58742. var ViveController = /** @class */ (function (_super) {
  58743. __extends(ViveController, _super);
  58744. function ViveController(vrGamepad) {
  58745. var _this = _super.call(this, vrGamepad) || this;
  58746. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58747. _this._invertLeftStickY = true;
  58748. return _this;
  58749. }
  58750. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58751. var _this = this;
  58752. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58753. /*
  58754. Parent Mesh name: ViveWand
  58755. - body
  58756. - r_gripper
  58757. - l_gripper
  58758. - menu_button
  58759. - system_button
  58760. - trackpad
  58761. - trigger
  58762. - LED
  58763. */
  58764. _this._defaultModel = newMeshes[1];
  58765. _this.attachToMesh(_this._defaultModel);
  58766. if (meshLoaded) {
  58767. meshLoaded(_this._defaultModel);
  58768. }
  58769. });
  58770. };
  58771. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58772. get: function () {
  58773. return this.onMainButtonStateChangedObservable;
  58774. },
  58775. enumerable: true,
  58776. configurable: true
  58777. });
  58778. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58779. get: function () {
  58780. return this.onMainButtonStateChangedObservable;
  58781. },
  58782. enumerable: true,
  58783. configurable: true
  58784. });
  58785. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58786. get: function () {
  58787. return this.onSecondaryButtonStateChangedObservable;
  58788. },
  58789. enumerable: true,
  58790. configurable: true
  58791. });
  58792. /**
  58793. * Vive mapping:
  58794. * 0: touchpad
  58795. * 1: trigger
  58796. * 2: left AND right buttons
  58797. * 3: menu button
  58798. */
  58799. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58800. var notifyObject = state; //{ state: state, changes: changes };
  58801. switch (buttonIdx) {
  58802. case 0:
  58803. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58804. return;
  58805. case 1:// index trigger
  58806. if (this._defaultModel) {
  58807. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58808. }
  58809. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58810. return;
  58811. case 2:// left AND right button
  58812. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58813. return;
  58814. case 3:
  58815. if (this._defaultModel) {
  58816. if (notifyObject.pressed) {
  58817. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58818. }
  58819. else {
  58820. (this._defaultModel.getChildren()[2]).position.y = 0;
  58821. }
  58822. }
  58823. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58824. return;
  58825. }
  58826. };
  58827. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58828. ViveController.MODEL_FILENAME = 'wand.babylon';
  58829. return ViveController;
  58830. }(BABYLON.WebVRController));
  58831. BABYLON.ViveController = ViveController;
  58832. })(BABYLON || (BABYLON = {}));
  58833. //# sourceMappingURL=babylon.viveController.js.map
  58834. var BABYLON;
  58835. (function (BABYLON) {
  58836. var GenericController = /** @class */ (function (_super) {
  58837. __extends(GenericController, _super);
  58838. function GenericController(vrGamepad) {
  58839. return _super.call(this, vrGamepad) || this;
  58840. }
  58841. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58842. var _this = this;
  58843. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58844. _this._defaultModel = newMeshes[1];
  58845. _this.attachToMesh(_this._defaultModel);
  58846. if (meshLoaded) {
  58847. meshLoaded(_this._defaultModel);
  58848. }
  58849. });
  58850. };
  58851. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58852. console.log("Button id: " + buttonIdx + "state: ");
  58853. console.dir(state);
  58854. };
  58855. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58856. GenericController.MODEL_FILENAME = 'generic.babylon';
  58857. return GenericController;
  58858. }(BABYLON.WebVRController));
  58859. BABYLON.GenericController = GenericController;
  58860. })(BABYLON || (BABYLON = {}));
  58861. //# sourceMappingURL=babylon.genericController.js.map
  58862. var BABYLON;
  58863. (function (BABYLON) {
  58864. var LoadedMeshInfo = /** @class */ (function () {
  58865. function LoadedMeshInfo() {
  58866. this.buttonMeshes = {};
  58867. this.axisMeshes = {};
  58868. }
  58869. return LoadedMeshInfo;
  58870. }());
  58871. var WindowsMotionController = /** @class */ (function (_super) {
  58872. __extends(WindowsMotionController, _super);
  58873. function WindowsMotionController(vrGamepad) {
  58874. var _this = _super.call(this, vrGamepad) || this;
  58875. _this._mapping = {
  58876. // Semantic button names
  58877. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58878. // A mapping of the button name to glTF model node name
  58879. // that should be transformed by button value.
  58880. buttonMeshNames: {
  58881. 'trigger': 'SELECT',
  58882. 'menu': 'MENU',
  58883. 'grip': 'GRASP',
  58884. 'thumbstick': 'THUMBSTICK_PRESS',
  58885. 'trackpad': 'TOUCHPAD_PRESS'
  58886. },
  58887. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58888. buttonObservableNames: {
  58889. 'trigger': 'onTriggerStateChangedObservable',
  58890. 'menu': 'onSecondaryButtonStateChangedObservable',
  58891. 'grip': 'onMainButtonStateChangedObservable',
  58892. 'thumbstick': 'onPadStateChangedObservable',
  58893. 'trackpad': 'onTrackpadChangedObservable'
  58894. },
  58895. // A mapping of the axis name to glTF model node name
  58896. // that should be transformed by axis value.
  58897. // This array mirrors the browserGamepad.axes array, such that
  58898. // the mesh corresponding to axis 0 is in this array index 0.
  58899. axisMeshNames: [
  58900. 'THUMBSTICK_X',
  58901. 'THUMBSTICK_Y',
  58902. 'TOUCHPAD_TOUCH_X',
  58903. 'TOUCHPAD_TOUCH_Y'
  58904. ],
  58905. pointingPoseMeshName: 'POINTING_POSE'
  58906. };
  58907. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58908. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58909. _this.trackpad = { x: 0, y: 0 };
  58910. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58911. _this._loadedMeshInfo = null;
  58912. return _this;
  58913. }
  58914. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58915. get: function () {
  58916. return this.onTriggerStateChangedObservable;
  58917. },
  58918. enumerable: true,
  58919. configurable: true
  58920. });
  58921. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58922. get: function () {
  58923. return this.onSecondaryButtonStateChangedObservable;
  58924. },
  58925. enumerable: true,
  58926. configurable: true
  58927. });
  58928. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58929. get: function () {
  58930. return this.onMainButtonStateChangedObservable;
  58931. },
  58932. enumerable: true,
  58933. configurable: true
  58934. });
  58935. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58936. get: function () {
  58937. return this.onPadStateChangedObservable;
  58938. },
  58939. enumerable: true,
  58940. configurable: true
  58941. });
  58942. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58943. get: function () {
  58944. return this.onTrackpadChangedObservable;
  58945. },
  58946. enumerable: true,
  58947. configurable: true
  58948. });
  58949. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58950. get: function () {
  58951. return this.onTrackpadValuesChangedObservable;
  58952. },
  58953. enumerable: true,
  58954. configurable: true
  58955. });
  58956. /**
  58957. * Called once per frame by the engine.
  58958. */
  58959. WindowsMotionController.prototype.update = function () {
  58960. _super.prototype.update.call(this);
  58961. // Only need to animate axes if there is a loaded mesh
  58962. if (this._loadedMeshInfo) {
  58963. if (this.browserGamepad.axes) {
  58964. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58965. this.trackpad.x = this.browserGamepad["axes"][2];
  58966. this.trackpad.y = this.browserGamepad["axes"][3];
  58967. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58968. }
  58969. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58970. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58971. }
  58972. }
  58973. }
  58974. };
  58975. /**
  58976. * Called once for each button that changed state since the last frame
  58977. * @param buttonIdx Which button index changed
  58978. * @param state New state of the button
  58979. * @param changes Which properties on the state changed since last frame
  58980. */
  58981. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58982. var buttonName = this._mapping.buttons[buttonIdx];
  58983. if (!buttonName) {
  58984. return;
  58985. }
  58986. // Only emit events for buttons that we know how to map from index to name
  58987. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58988. if (observable) {
  58989. observable.notifyObservers(state);
  58990. }
  58991. this.lerpButtonTransform(buttonName, state.value);
  58992. };
  58993. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58994. // If there is no loaded mesh, there is nothing to transform.
  58995. if (!this._loadedMeshInfo) {
  58996. return;
  58997. }
  58998. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58999. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  59000. return;
  59001. }
  59002. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  59003. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  59004. };
  59005. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  59006. if (!this._loadedMeshInfo) {
  59007. return;
  59008. }
  59009. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  59010. if (!meshInfo) {
  59011. return;
  59012. }
  59013. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  59014. return;
  59015. }
  59016. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  59017. var lerpValue = axisValue * 0.5 + 0.5;
  59018. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  59019. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  59020. };
  59021. /**
  59022. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  59023. * @param scene scene in which to add meshes
  59024. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  59025. */
  59026. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  59027. var _this = this;
  59028. if (forceDefault === void 0) { forceDefault = false; }
  59029. var path;
  59030. var filename;
  59031. // Checking if GLB loader is present
  59032. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  59033. // Determine the device specific folder based on the ID suffix
  59034. var device = 'default';
  59035. if (this.id && !forceDefault) {
  59036. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  59037. device = ((match && match[0]) || device);
  59038. }
  59039. // Hand
  59040. if (this.hand === 'left') {
  59041. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  59042. }
  59043. else {
  59044. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  59045. }
  59046. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  59047. }
  59048. else {
  59049. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  59050. path = BABYLON.GenericController.MODEL_BASE_URL;
  59051. filename = BABYLON.GenericController.MODEL_FILENAME;
  59052. }
  59053. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  59054. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  59055. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  59056. if (!_this._loadedMeshInfo) {
  59057. return;
  59058. }
  59059. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  59060. _this.attachToMesh(_this._defaultModel);
  59061. if (meshLoaded) {
  59062. meshLoaded(_this._defaultModel);
  59063. }
  59064. }, null, function (scene, message) {
  59065. BABYLON.Tools.Log(message);
  59066. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  59067. if (!forceDefault) {
  59068. _this.initControllerMesh(scene, meshLoaded, true);
  59069. }
  59070. });
  59071. };
  59072. /**
  59073. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  59074. * can be transformed by button presses and axes values, based on this._mapping.
  59075. *
  59076. * @param scene scene in which the meshes exist
  59077. * @param meshes list of meshes that make up the controller model to process
  59078. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  59079. */
  59080. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  59081. var loadedMeshInfo = null;
  59082. // Create a new mesh to contain the glTF hierarchy
  59083. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  59084. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  59085. var childMesh = null;
  59086. for (var i = 0; i < meshes.length; i++) {
  59087. var mesh = meshes[i];
  59088. if (!mesh.parent) {
  59089. // Exclude controller meshes from picking results
  59090. mesh.isPickable = false;
  59091. // Handle root node, attach to the new parentMesh
  59092. childMesh = mesh;
  59093. break;
  59094. }
  59095. }
  59096. if (childMesh) {
  59097. childMesh.setParent(parentMesh);
  59098. // Create our mesh info. Note that this method will always return non-null.
  59099. loadedMeshInfo = this.createMeshInfo(parentMesh);
  59100. }
  59101. else {
  59102. BABYLON.Tools.Warn('Could not find root node in model file.');
  59103. }
  59104. return loadedMeshInfo;
  59105. };
  59106. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  59107. var loadedMeshInfo = new LoadedMeshInfo();
  59108. var i;
  59109. loadedMeshInfo.rootNode = rootNode;
  59110. // Reset the caches
  59111. loadedMeshInfo.buttonMeshes = {};
  59112. loadedMeshInfo.axisMeshes = {};
  59113. // Button Meshes
  59114. for (i = 0; i < this._mapping.buttons.length; i++) {
  59115. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  59116. if (!buttonMeshName) {
  59117. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  59118. continue;
  59119. }
  59120. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  59121. if (!buttonMesh) {
  59122. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  59123. continue;
  59124. }
  59125. var buttonMeshInfo = {
  59126. index: i,
  59127. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  59128. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  59129. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  59130. };
  59131. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  59132. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  59133. }
  59134. else {
  59135. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  59136. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  59137. '(VALUE: ' + !!buttonMeshInfo.value +
  59138. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  59139. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  59140. ')');
  59141. }
  59142. }
  59143. // Axis Meshes
  59144. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  59145. var axisMeshName = this._mapping.axisMeshNames[i];
  59146. if (!axisMeshName) {
  59147. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  59148. continue;
  59149. }
  59150. var axisMesh = getChildByName(rootNode, axisMeshName);
  59151. if (!axisMesh) {
  59152. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59153. continue;
  59154. }
  59155. var axisMeshInfo = {
  59156. index: i,
  59157. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59158. min: getImmediateChildByName(axisMesh, 'MIN'),
  59159. max: getImmediateChildByName(axisMesh, 'MAX')
  59160. };
  59161. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59162. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59163. }
  59164. else {
  59165. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59166. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59167. '(VALUE: ' + !!axisMeshInfo.value +
  59168. ', MIN: ' + !!axisMeshInfo.min +
  59169. ', MAX:' + !!axisMeshInfo.max +
  59170. ')');
  59171. }
  59172. }
  59173. // Pointing Ray
  59174. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59175. if (!loadedMeshInfo.pointingPoseNode) {
  59176. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59177. }
  59178. return loadedMeshInfo;
  59179. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59180. function getChildByName(node, name) {
  59181. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59182. }
  59183. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59184. function getImmediateChildByName(node, name) {
  59185. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59186. }
  59187. };
  59188. WindowsMotionController.prototype.getForwardRay = function (length) {
  59189. if (length === void 0) { length = 100; }
  59190. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59191. return _super.prototype.getForwardRay.call(this, length);
  59192. }
  59193. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59194. var origin = m.getTranslation();
  59195. var forward = new BABYLON.Vector3(0, 0, -1);
  59196. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59197. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59198. return new BABYLON.Ray(origin, direction, length);
  59199. };
  59200. WindowsMotionController.prototype.dispose = function () {
  59201. _super.prototype.dispose.call(this);
  59202. this.onTrackpadChangedObservable.clear();
  59203. };
  59204. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59205. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59206. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59207. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59208. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59209. return WindowsMotionController;
  59210. }(BABYLON.WebVRController));
  59211. BABYLON.WindowsMotionController = WindowsMotionController;
  59212. })(BABYLON || (BABYLON = {}));
  59213. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59214. var BABYLON;
  59215. (function (BABYLON) {
  59216. var GearVRController = /** @class */ (function (_super) {
  59217. __extends(GearVRController, _super);
  59218. function GearVRController(vrGamepad) {
  59219. var _this = _super.call(this, vrGamepad) || this;
  59220. _this._buttonIndexToObservableNameMap = [
  59221. 'onTrackpadChangedObservable',
  59222. 'onTriggerStateChangedObservable' // Trigger
  59223. ];
  59224. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59225. return _this;
  59226. }
  59227. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59228. var _this = this;
  59229. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59230. _this._defaultModel = newMeshes[1];
  59231. _this.attachToMesh(_this._defaultModel);
  59232. if (meshLoaded) {
  59233. meshLoaded(_this._defaultModel);
  59234. }
  59235. });
  59236. };
  59237. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59238. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59239. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59240. // Only emit events for buttons that we know how to map from index to observable
  59241. var observable = this[observableName];
  59242. if (observable) {
  59243. observable.notifyObservers(state);
  59244. }
  59245. }
  59246. };
  59247. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59248. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59249. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59250. return GearVRController;
  59251. }(BABYLON.WebVRController));
  59252. BABYLON.GearVRController = GearVRController;
  59253. })(BABYLON || (BABYLON = {}));
  59254. //# sourceMappingURL=babylon.gearVRController.js.map
  59255. var BABYLON;
  59256. (function (BABYLON) {
  59257. var FollowCamera = /** @class */ (function (_super) {
  59258. __extends(FollowCamera, _super);
  59259. function FollowCamera(name, position, scene, lockedTarget) {
  59260. if (lockedTarget === void 0) { lockedTarget = null; }
  59261. var _this = _super.call(this, name, position, scene) || this;
  59262. _this.radius = 12;
  59263. _this.rotationOffset = 0;
  59264. _this.heightOffset = 4;
  59265. _this.cameraAcceleration = 0.05;
  59266. _this.maxCameraSpeed = 20;
  59267. _this.lockedTarget = lockedTarget;
  59268. return _this;
  59269. }
  59270. FollowCamera.prototype.getRadians = function (degrees) {
  59271. return degrees * Math.PI / 180;
  59272. };
  59273. FollowCamera.prototype.follow = function (cameraTarget) {
  59274. if (!cameraTarget)
  59275. return;
  59276. var yRotation;
  59277. if (cameraTarget.rotationQuaternion) {
  59278. var rotMatrix = new BABYLON.Matrix();
  59279. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59280. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59281. }
  59282. else {
  59283. yRotation = cameraTarget.rotation.y;
  59284. }
  59285. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59286. var targetPosition = cameraTarget.getAbsolutePosition();
  59287. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59288. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59289. var dx = targetX - this.position.x;
  59290. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59291. var dz = (targetZ) - this.position.z;
  59292. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59293. var vy = dy * this.cameraAcceleration;
  59294. var vz = dz * this.cameraAcceleration * 2;
  59295. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59296. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59297. }
  59298. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59299. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59300. }
  59301. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59302. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59303. }
  59304. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59305. this.setTarget(targetPosition);
  59306. };
  59307. FollowCamera.prototype._checkInputs = function () {
  59308. _super.prototype._checkInputs.call(this);
  59309. if (this.lockedTarget) {
  59310. this.follow(this.lockedTarget);
  59311. }
  59312. };
  59313. FollowCamera.prototype.getClassName = function () {
  59314. return "FollowCamera";
  59315. };
  59316. __decorate([
  59317. BABYLON.serialize()
  59318. ], FollowCamera.prototype, "radius", void 0);
  59319. __decorate([
  59320. BABYLON.serialize()
  59321. ], FollowCamera.prototype, "rotationOffset", void 0);
  59322. __decorate([
  59323. BABYLON.serialize()
  59324. ], FollowCamera.prototype, "heightOffset", void 0);
  59325. __decorate([
  59326. BABYLON.serialize()
  59327. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59328. __decorate([
  59329. BABYLON.serialize()
  59330. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59331. __decorate([
  59332. BABYLON.serializeAsMeshReference("lockedTargetId")
  59333. ], FollowCamera.prototype, "lockedTarget", void 0);
  59334. return FollowCamera;
  59335. }(BABYLON.TargetCamera));
  59336. BABYLON.FollowCamera = FollowCamera;
  59337. var ArcFollowCamera = /** @class */ (function (_super) {
  59338. __extends(ArcFollowCamera, _super);
  59339. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59340. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59341. _this.alpha = alpha;
  59342. _this.beta = beta;
  59343. _this.radius = radius;
  59344. _this.target = target;
  59345. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59346. _this.follow();
  59347. return _this;
  59348. }
  59349. ArcFollowCamera.prototype.follow = function () {
  59350. if (!this.target) {
  59351. return;
  59352. }
  59353. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59354. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59355. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59356. var targetPosition = this.target.getAbsolutePosition();
  59357. this.position = targetPosition.add(this._cartesianCoordinates);
  59358. this.setTarget(targetPosition);
  59359. };
  59360. ArcFollowCamera.prototype._checkInputs = function () {
  59361. _super.prototype._checkInputs.call(this);
  59362. this.follow();
  59363. };
  59364. ArcFollowCamera.prototype.getClassName = function () {
  59365. return "ArcFollowCamera";
  59366. };
  59367. return ArcFollowCamera;
  59368. }(BABYLON.TargetCamera));
  59369. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59370. })(BABYLON || (BABYLON = {}));
  59371. //# sourceMappingURL=babylon.followCamera.js.map
  59372. var BABYLON;
  59373. (function (BABYLON) {
  59374. // We're mainly based on the logic defined into the FreeCamera code
  59375. var UniversalCamera = /** @class */ (function (_super) {
  59376. __extends(UniversalCamera, _super);
  59377. //-- end properties for backward compatibility for inputs
  59378. function UniversalCamera(name, position, scene) {
  59379. var _this = _super.call(this, name, position, scene) || this;
  59380. _this.inputs.addGamepad();
  59381. return _this;
  59382. }
  59383. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59384. //-- Begin properties for backward compatibility for inputs
  59385. get: function () {
  59386. var gamepad = this.inputs.attached["gamepad"];
  59387. if (gamepad)
  59388. return gamepad.gamepadAngularSensibility;
  59389. return 0;
  59390. },
  59391. set: function (value) {
  59392. var gamepad = this.inputs.attached["gamepad"];
  59393. if (gamepad)
  59394. gamepad.gamepadAngularSensibility = value;
  59395. },
  59396. enumerable: true,
  59397. configurable: true
  59398. });
  59399. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59400. get: function () {
  59401. var gamepad = this.inputs.attached["gamepad"];
  59402. if (gamepad)
  59403. return gamepad.gamepadMoveSensibility;
  59404. return 0;
  59405. },
  59406. set: function (value) {
  59407. var gamepad = this.inputs.attached["gamepad"];
  59408. if (gamepad)
  59409. gamepad.gamepadMoveSensibility = value;
  59410. },
  59411. enumerable: true,
  59412. configurable: true
  59413. });
  59414. UniversalCamera.prototype.getClassName = function () {
  59415. return "UniversalCamera";
  59416. };
  59417. return UniversalCamera;
  59418. }(BABYLON.TouchCamera));
  59419. BABYLON.UniversalCamera = UniversalCamera;
  59420. })(BABYLON || (BABYLON = {}));
  59421. //# sourceMappingURL=babylon.universalCamera.js.map
  59422. var BABYLON;
  59423. (function (BABYLON) {
  59424. // We're mainly based on the logic defined into the FreeCamera code
  59425. var GamepadCamera = /** @class */ (function (_super) {
  59426. __extends(GamepadCamera, _super);
  59427. //-- end properties for backward compatibility for inputs
  59428. function GamepadCamera(name, position, scene) {
  59429. return _super.call(this, name, position, scene) || this;
  59430. }
  59431. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59432. //-- Begin properties for backward compatibility for inputs
  59433. get: function () {
  59434. var gamepad = this.inputs.attached["gamepad"];
  59435. if (gamepad)
  59436. return gamepad.gamepadAngularSensibility;
  59437. return 0;
  59438. },
  59439. set: function (value) {
  59440. var gamepad = this.inputs.attached["gamepad"];
  59441. if (gamepad)
  59442. gamepad.gamepadAngularSensibility = value;
  59443. },
  59444. enumerable: true,
  59445. configurable: true
  59446. });
  59447. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59448. get: function () {
  59449. var gamepad = this.inputs.attached["gamepad"];
  59450. if (gamepad)
  59451. return gamepad.gamepadMoveSensibility;
  59452. return 0;
  59453. },
  59454. set: function (value) {
  59455. var gamepad = this.inputs.attached["gamepad"];
  59456. if (gamepad)
  59457. gamepad.gamepadMoveSensibility = value;
  59458. },
  59459. enumerable: true,
  59460. configurable: true
  59461. });
  59462. GamepadCamera.prototype.getClassName = function () {
  59463. return "GamepadCamera";
  59464. };
  59465. return GamepadCamera;
  59466. }(BABYLON.UniversalCamera));
  59467. BABYLON.GamepadCamera = GamepadCamera;
  59468. })(BABYLON || (BABYLON = {}));
  59469. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59470. var BABYLON;
  59471. (function (BABYLON) {
  59472. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59473. function PostProcessRenderPipelineManager() {
  59474. this._renderPipelines = {};
  59475. }
  59476. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59477. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59478. };
  59479. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59480. if (unique === void 0) { unique = false; }
  59481. var renderPipeline = this._renderPipelines[renderPipelineName];
  59482. if (!renderPipeline) {
  59483. return;
  59484. }
  59485. renderPipeline._attachCameras(cameras, unique);
  59486. };
  59487. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59488. var renderPipeline = this._renderPipelines[renderPipelineName];
  59489. if (!renderPipeline) {
  59490. return;
  59491. }
  59492. renderPipeline._detachCameras(cameras);
  59493. };
  59494. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59495. var renderPipeline = this._renderPipelines[renderPipelineName];
  59496. if (!renderPipeline) {
  59497. return;
  59498. }
  59499. renderPipeline._enableEffect(renderEffectName, cameras);
  59500. };
  59501. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59502. var renderPipeline = this._renderPipelines[renderPipelineName];
  59503. if (!renderPipeline) {
  59504. return;
  59505. }
  59506. renderPipeline._disableEffect(renderEffectName, cameras);
  59507. };
  59508. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59509. var renderPipeline = this._renderPipelines[renderPipelineName];
  59510. if (!renderPipeline) {
  59511. return;
  59512. }
  59513. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59514. };
  59515. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59516. var renderPipeline = this._renderPipelines[renderPipelineName];
  59517. if (!renderPipeline) {
  59518. return;
  59519. }
  59520. renderPipeline._disableDisplayOnlyPass(cameras);
  59521. };
  59522. PostProcessRenderPipelineManager.prototype.update = function () {
  59523. for (var renderPipelineName in this._renderPipelines) {
  59524. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59525. var pipeline = this._renderPipelines[renderPipelineName];
  59526. if (!pipeline.isSupported) {
  59527. pipeline.dispose();
  59528. delete this._renderPipelines[renderPipelineName];
  59529. }
  59530. else {
  59531. pipeline._update();
  59532. }
  59533. }
  59534. }
  59535. };
  59536. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59537. for (var renderPipelineName in this._renderPipelines) {
  59538. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59539. var pipeline = this._renderPipelines[renderPipelineName];
  59540. pipeline._rebuild();
  59541. }
  59542. }
  59543. };
  59544. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59545. for (var renderPipelineName in this._renderPipelines) {
  59546. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59547. var pipeline = this._renderPipelines[renderPipelineName];
  59548. pipeline.dispose();
  59549. }
  59550. }
  59551. };
  59552. return PostProcessRenderPipelineManager;
  59553. }());
  59554. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59555. })(BABYLON || (BABYLON = {}));
  59556. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59557. var BABYLON;
  59558. (function (BABYLON) {
  59559. var PostProcessRenderPass = /** @class */ (function () {
  59560. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59561. this._refCount = 0;
  59562. this._name = name;
  59563. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59564. this.setRenderList(renderList);
  59565. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59566. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59567. this._scene = scene;
  59568. this._renderList = renderList;
  59569. }
  59570. // private
  59571. PostProcessRenderPass.prototype._incRefCount = function () {
  59572. if (this._refCount === 0) {
  59573. this._scene.customRenderTargets.push(this._renderTexture);
  59574. }
  59575. return ++this._refCount;
  59576. };
  59577. PostProcessRenderPass.prototype._decRefCount = function () {
  59578. this._refCount--;
  59579. if (this._refCount <= 0) {
  59580. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59581. }
  59582. return this._refCount;
  59583. };
  59584. PostProcessRenderPass.prototype._update = function () {
  59585. this.setRenderList(this._renderList);
  59586. };
  59587. // public
  59588. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59589. this._renderTexture.renderList = renderList;
  59590. };
  59591. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59592. return this._renderTexture;
  59593. };
  59594. return PostProcessRenderPass;
  59595. }());
  59596. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59597. })(BABYLON || (BABYLON = {}));
  59598. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59599. var BABYLON;
  59600. (function (BABYLON) {
  59601. var PostProcessRenderEffect = /** @class */ (function () {
  59602. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59603. this._name = name;
  59604. this._singleInstance = singleInstance || true;
  59605. this._getPostProcess = getPostProcess;
  59606. this._cameras = {};
  59607. this._indicesForCamera = {};
  59608. this._postProcesses = {};
  59609. this._renderPasses = {};
  59610. this._renderEffectAsPasses = {};
  59611. }
  59612. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59613. get: function () {
  59614. for (var index in this._postProcesses) {
  59615. if (!this._postProcesses[index].isSupported) {
  59616. return false;
  59617. }
  59618. }
  59619. return true;
  59620. },
  59621. enumerable: true,
  59622. configurable: true
  59623. });
  59624. PostProcessRenderEffect.prototype._update = function () {
  59625. for (var renderPassName in this._renderPasses) {
  59626. this._renderPasses[renderPassName]._update();
  59627. }
  59628. };
  59629. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59630. this._renderPasses[renderPass._name] = renderPass;
  59631. this._linkParameters();
  59632. };
  59633. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59634. delete this._renderPasses[renderPass._name];
  59635. this._linkParameters();
  59636. };
  59637. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59638. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59639. this._linkParameters();
  59640. };
  59641. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59642. for (var renderPassName in this._renderPasses) {
  59643. if (renderPassName === passName) {
  59644. return this._renderPasses[passName];
  59645. }
  59646. }
  59647. return null;
  59648. };
  59649. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59650. this._renderPasses = {};
  59651. this._linkParameters();
  59652. };
  59653. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59654. var cameraKey;
  59655. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59656. if (!cams) {
  59657. return;
  59658. }
  59659. for (var i = 0; i < cams.length; i++) {
  59660. var camera = cams[i];
  59661. var cameraName = camera.name;
  59662. if (this._singleInstance) {
  59663. cameraKey = 0;
  59664. }
  59665. else {
  59666. cameraKey = cameraName;
  59667. }
  59668. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59669. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59670. if (!this._indicesForCamera[cameraName]) {
  59671. this._indicesForCamera[cameraName] = [];
  59672. }
  59673. this._indicesForCamera[cameraName].push(index);
  59674. if (!this._cameras[cameraName]) {
  59675. this._cameras[cameraName] = camera;
  59676. }
  59677. for (var passName in this._renderPasses) {
  59678. this._renderPasses[passName]._incRefCount();
  59679. }
  59680. }
  59681. this._linkParameters();
  59682. };
  59683. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59684. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59685. if (!cams) {
  59686. return;
  59687. }
  59688. for (var i = 0; i < cams.length; i++) {
  59689. var camera = cams[i];
  59690. var cameraName = camera.name;
  59691. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59692. if (this._cameras[cameraName]) {
  59693. //this._indicesForCamera.splice(index, 1);
  59694. this._cameras[cameraName] = null;
  59695. }
  59696. for (var passName in this._renderPasses) {
  59697. this._renderPasses[passName]._decRefCount();
  59698. }
  59699. }
  59700. };
  59701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59702. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59703. if (!cams) {
  59704. return;
  59705. }
  59706. for (var i = 0; i < cams.length; i++) {
  59707. var camera = cams[i];
  59708. var cameraName = camera.name;
  59709. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59710. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59711. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59712. }
  59713. }
  59714. for (var passName in this._renderPasses) {
  59715. this._renderPasses[passName]._incRefCount();
  59716. }
  59717. }
  59718. };
  59719. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59720. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59721. if (!cams) {
  59722. return;
  59723. }
  59724. for (var i = 0; i < cams.length; i++) {
  59725. var camera = cams[i];
  59726. var cameraName = camera.Name;
  59727. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59728. for (var passName in this._renderPasses) {
  59729. this._renderPasses[passName]._decRefCount();
  59730. }
  59731. }
  59732. };
  59733. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59734. if (this._singleInstance) {
  59735. return this._postProcesses[0];
  59736. }
  59737. else {
  59738. if (!camera) {
  59739. return null;
  59740. }
  59741. return this._postProcesses[camera.name];
  59742. }
  59743. };
  59744. PostProcessRenderEffect.prototype._linkParameters = function () {
  59745. var _this = this;
  59746. for (var index in this._postProcesses) {
  59747. if (this.applyParameters) {
  59748. this.applyParameters(this._postProcesses[index]);
  59749. }
  59750. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59751. _this._linkTextures(effect);
  59752. });
  59753. }
  59754. };
  59755. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59756. for (var renderPassName in this._renderPasses) {
  59757. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59758. }
  59759. for (var renderEffectName in this._renderEffectAsPasses) {
  59760. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59761. }
  59762. };
  59763. return PostProcessRenderEffect;
  59764. }());
  59765. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59766. })(BABYLON || (BABYLON = {}));
  59767. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59768. var BABYLON;
  59769. (function (BABYLON) {
  59770. var PostProcessRenderPipeline = /** @class */ (function () {
  59771. function PostProcessRenderPipeline(engine, name) {
  59772. this._engine = engine;
  59773. this._name = name;
  59774. this._renderEffects = {};
  59775. this._renderEffectsForIsolatedPass = new Array();
  59776. this._cameras = [];
  59777. }
  59778. PostProcessRenderPipeline.prototype.getClassName = function () {
  59779. return "PostProcessRenderPipeline";
  59780. };
  59781. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59782. get: function () {
  59783. for (var renderEffectName in this._renderEffects) {
  59784. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59785. if (!this._renderEffects[renderEffectName].isSupported) {
  59786. return false;
  59787. }
  59788. }
  59789. }
  59790. return true;
  59791. },
  59792. enumerable: true,
  59793. configurable: true
  59794. });
  59795. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59796. this._renderEffects[renderEffect._name] = renderEffect;
  59797. };
  59798. // private
  59799. PostProcessRenderPipeline.prototype._rebuild = function () {
  59800. };
  59801. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59802. var renderEffects = this._renderEffects[renderEffectName];
  59803. if (!renderEffects) {
  59804. return;
  59805. }
  59806. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59807. };
  59808. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59809. var renderEffects = this._renderEffects[renderEffectName];
  59810. if (!renderEffects) {
  59811. return;
  59812. }
  59813. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59814. };
  59815. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59816. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59817. if (!cams) {
  59818. return;
  59819. }
  59820. var indicesToDelete = [];
  59821. var i;
  59822. for (i = 0; i < cams.length; i++) {
  59823. var camera = cams[i];
  59824. var cameraName = camera.name;
  59825. if (this._cameras.indexOf(camera) === -1) {
  59826. this._cameras[cameraName] = camera;
  59827. }
  59828. else if (unique) {
  59829. indicesToDelete.push(i);
  59830. }
  59831. }
  59832. for (i = 0; i < indicesToDelete.length; i++) {
  59833. cameras.splice(indicesToDelete[i], 1);
  59834. }
  59835. for (var renderEffectName in this._renderEffects) {
  59836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59837. this._renderEffects[renderEffectName]._attachCameras(cams);
  59838. }
  59839. }
  59840. };
  59841. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59842. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59843. if (!cams) {
  59844. return;
  59845. }
  59846. for (var renderEffectName in this._renderEffects) {
  59847. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59848. this._renderEffects[renderEffectName]._detachCameras(cams);
  59849. }
  59850. }
  59851. for (var i = 0; i < cams.length; i++) {
  59852. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59853. }
  59854. };
  59855. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59856. var _this = this;
  59857. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59858. if (!cams) {
  59859. return;
  59860. }
  59861. var pass = null;
  59862. var renderEffectName;
  59863. for (renderEffectName in this._renderEffects) {
  59864. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59865. pass = this._renderEffects[renderEffectName].getPass(passName);
  59866. if (pass != null) {
  59867. break;
  59868. }
  59869. }
  59870. }
  59871. if (pass === null) {
  59872. return;
  59873. }
  59874. for (renderEffectName in this._renderEffects) {
  59875. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59876. this._renderEffects[renderEffectName]._disable(cams);
  59877. }
  59878. }
  59879. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59880. for (var i = 0; i < cams.length; i++) {
  59881. var camera = cams[i];
  59882. var cameraName = camera.name;
  59883. 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); });
  59884. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59885. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59886. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59887. }
  59888. };
  59889. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59890. var _this = this;
  59891. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59892. if (!cams) {
  59893. return;
  59894. }
  59895. for (var i = 0; i < cams.length; i++) {
  59896. var camera = cams[i];
  59897. var cameraName = camera.name;
  59898. 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); });
  59899. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59900. }
  59901. for (var renderEffectName in this._renderEffects) {
  59902. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59903. this._renderEffects[renderEffectName]._enable(cams);
  59904. }
  59905. }
  59906. };
  59907. PostProcessRenderPipeline.prototype._update = function () {
  59908. for (var renderEffectName in this._renderEffects) {
  59909. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59910. this._renderEffects[renderEffectName]._update();
  59911. }
  59912. }
  59913. for (var i = 0; i < this._cameras.length; i++) {
  59914. var cameraName = this._cameras[i].name;
  59915. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59916. this._renderEffectsForIsolatedPass[cameraName]._update();
  59917. }
  59918. }
  59919. };
  59920. PostProcessRenderPipeline.prototype._reset = function () {
  59921. this._renderEffects = {};
  59922. this._renderEffectsForIsolatedPass = new Array();
  59923. };
  59924. PostProcessRenderPipeline.prototype.dispose = function () {
  59925. // Must be implemented by children
  59926. };
  59927. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59928. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59929. __decorate([
  59930. BABYLON.serialize()
  59931. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59932. return PostProcessRenderPipeline;
  59933. }());
  59934. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59935. })(BABYLON || (BABYLON = {}));
  59936. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59937. var BABYLON;
  59938. (function (BABYLON) {
  59939. var DepthRenderer = /** @class */ (function () {
  59940. function DepthRenderer(scene, type) {
  59941. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59942. var _this = this;
  59943. this._scene = scene;
  59944. var engine = scene.getEngine();
  59945. // Render target
  59946. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59947. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59948. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59949. this._depthMap.refreshRate = 1;
  59950. this._depthMap.renderParticles = false;
  59951. this._depthMap.renderList = null;
  59952. // set default depth value to 1.0 (far away)
  59953. this._depthMap.onClearObservable.add(function (engine) {
  59954. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59955. });
  59956. // Custom render function
  59957. var renderSubMesh = function (subMesh) {
  59958. var mesh = subMesh.getRenderingMesh();
  59959. var scene = _this._scene;
  59960. var engine = scene.getEngine();
  59961. var material = subMesh.getMaterial();
  59962. if (!material) {
  59963. return;
  59964. }
  59965. // Culling and reverse (right handed system)
  59966. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59967. // Managing instances
  59968. var batch = mesh._getInstancesRenderList(subMesh._id);
  59969. if (batch.mustReturn) {
  59970. return;
  59971. }
  59972. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59973. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59974. engine.enableEffect(_this._effect);
  59975. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59976. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59977. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59978. // Alpha test
  59979. if (material && material.needAlphaTesting()) {
  59980. var alphaTexture = material.getAlphaTestTexture();
  59981. if (alphaTexture) {
  59982. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59983. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59984. }
  59985. }
  59986. // Bones
  59987. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59989. }
  59990. // Draw
  59991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59992. }
  59993. };
  59994. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59995. var index;
  59996. if (depthOnlySubMeshes.length) {
  59997. engine.setColorWrite(false);
  59998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59999. renderSubMesh(depthOnlySubMeshes.data[index]);
  60000. }
  60001. engine.setColorWrite(true);
  60002. }
  60003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60004. renderSubMesh(opaqueSubMeshes.data[index]);
  60005. }
  60006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60007. renderSubMesh(alphaTestSubMeshes.data[index]);
  60008. }
  60009. };
  60010. }
  60011. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  60012. var material = subMesh.getMaterial();
  60013. if (material.disableDepthWrite) {
  60014. return false;
  60015. }
  60016. var defines = [];
  60017. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60018. var mesh = subMesh.getMesh();
  60019. // Alpha test
  60020. if (material && material.needAlphaTesting()) {
  60021. defines.push("#define ALPHATEST");
  60022. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60023. attribs.push(BABYLON.VertexBuffer.UVKind);
  60024. defines.push("#define UV1");
  60025. }
  60026. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60027. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60028. defines.push("#define UV2");
  60029. }
  60030. }
  60031. // Bones
  60032. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60033. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60034. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60035. if (mesh.numBoneInfluencers > 4) {
  60036. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60037. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60038. }
  60039. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60040. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60041. }
  60042. else {
  60043. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60044. }
  60045. // Instances
  60046. if (useInstances) {
  60047. defines.push("#define INSTANCES");
  60048. attribs.push("world0");
  60049. attribs.push("world1");
  60050. attribs.push("world2");
  60051. attribs.push("world3");
  60052. }
  60053. // Get correct effect
  60054. var join = defines.join("\n");
  60055. if (this._cachedDefines !== join) {
  60056. this._cachedDefines = join;
  60057. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  60058. }
  60059. return this._effect.isReady();
  60060. };
  60061. DepthRenderer.prototype.getDepthMap = function () {
  60062. return this._depthMap;
  60063. };
  60064. // Methods
  60065. DepthRenderer.prototype.dispose = function () {
  60066. this._depthMap.dispose();
  60067. };
  60068. return DepthRenderer;
  60069. }());
  60070. BABYLON.DepthRenderer = DepthRenderer;
  60071. })(BABYLON || (BABYLON = {}));
  60072. //# sourceMappingURL=babylon.depthRenderer.js.map
  60073. var BABYLON;
  60074. (function (BABYLON) {
  60075. var SSAORenderingPipeline = /** @class */ (function (_super) {
  60076. __extends(SSAORenderingPipeline, _super);
  60077. /**
  60078. * @constructor
  60079. * @param {string} name - The rendering pipeline name
  60080. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60081. * @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 }
  60082. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60083. */
  60084. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  60085. var _this = _super.call(this, scene.getEngine(), name) || this;
  60086. // Members
  60087. /**
  60088. * The PassPostProcess id in the pipeline that contains the original scene color
  60089. * @type {string}
  60090. */
  60091. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60092. /**
  60093. * The SSAO PostProcess id in the pipeline
  60094. * @type {string}
  60095. */
  60096. _this.SSAORenderEffect = "SSAORenderEffect";
  60097. /**
  60098. * The horizontal blur PostProcess id in the pipeline
  60099. * @type {string}
  60100. */
  60101. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60102. /**
  60103. * The vertical blur PostProcess id in the pipeline
  60104. * @type {string}
  60105. */
  60106. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60107. /**
  60108. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60109. * @type {string}
  60110. */
  60111. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60112. /**
  60113. * The output strength of the SSAO post-process. Default value is 1.0.
  60114. * @type {number}
  60115. */
  60116. _this.totalStrength = 1.0;
  60117. /**
  60118. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  60119. * @type {number}
  60120. */
  60121. _this.radius = 0.0001;
  60122. /**
  60123. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  60124. * Must not be equal to fallOff and superior to fallOff.
  60125. * Default value is 0.975
  60126. * @type {number}
  60127. */
  60128. _this.area = 0.0075;
  60129. /**
  60130. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  60131. * Must not be equal to area and inferior to area.
  60132. * Default value is 0.0
  60133. * @type {number}
  60134. */
  60135. _this.fallOff = 0.000001;
  60136. /**
  60137. * The base color of the SSAO post-process
  60138. * The final result is "base + ssao" between [0, 1]
  60139. * @type {number}
  60140. */
  60141. _this.base = 0.5;
  60142. _this._firstUpdate = true;
  60143. _this._scene = scene;
  60144. // Set up assets
  60145. _this._createRandomTexture();
  60146. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60147. var ssaoRatio = ratio.ssaoRatio || ratio;
  60148. var combineRatio = ratio.combineRatio || ratio;
  60149. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60150. _this._createSSAOPostProcess(ssaoRatio);
  60151. _this._createBlurPostProcess(ssaoRatio);
  60152. _this._createSSAOCombinePostProcess(combineRatio);
  60153. // Set up pipeline
  60154. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60156. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60157. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60158. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60159. // Finish
  60160. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60161. if (cameras)
  60162. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60163. return _this;
  60164. }
  60165. // Public Methods
  60166. /**
  60167. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60168. */
  60169. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60170. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60171. for (var i = 0; i < this._scene.cameras.length; i++) {
  60172. var camera = this._scene.cameras[i];
  60173. this._originalColorPostProcess.dispose(camera);
  60174. this._ssaoPostProcess.dispose(camera);
  60175. this._blurHPostProcess.dispose(camera);
  60176. this._blurVPostProcess.dispose(camera);
  60177. this._ssaoCombinePostProcess.dispose(camera);
  60178. }
  60179. this._randomTexture.dispose();
  60180. if (disableDepthRender)
  60181. this._scene.disableDepthRenderer();
  60182. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60183. _super.prototype.dispose.call(this);
  60184. };
  60185. // Private Methods
  60186. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60187. var _this = this;
  60188. var size = 16;
  60189. 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);
  60190. 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);
  60191. this._blurHPostProcess.onActivateObservable.add(function () {
  60192. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60193. _this._blurHPostProcess.kernel = size * dw;
  60194. });
  60195. this._blurVPostProcess.onActivateObservable.add(function () {
  60196. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60197. _this._blurVPostProcess.kernel = size * dw;
  60198. });
  60199. };
  60200. SSAORenderingPipeline.prototype._rebuild = function () {
  60201. this._firstUpdate = true;
  60202. _super.prototype._rebuild.call(this);
  60203. };
  60204. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60205. var _this = this;
  60206. var numSamples = 16;
  60207. var sampleSphere = [
  60208. 0.5381, 0.1856, -0.4319,
  60209. 0.1379, 0.2486, 0.4430,
  60210. 0.3371, 0.5679, -0.0057,
  60211. -0.6999, -0.0451, -0.0019,
  60212. 0.0689, -0.1598, -0.8547,
  60213. 0.0560, 0.0069, -0.1843,
  60214. -0.0146, 0.1402, 0.0762,
  60215. 0.0100, -0.1924, -0.0344,
  60216. -0.3577, -0.5301, -0.4358,
  60217. -0.3169, 0.1063, 0.0158,
  60218. 0.0103, -0.5869, 0.0046,
  60219. -0.0897, -0.4940, 0.3287,
  60220. 0.7119, -0.0154, -0.0918,
  60221. -0.0533, 0.0596, -0.5411,
  60222. 0.0352, -0.0631, 0.5460,
  60223. -0.4776, 0.2847, -0.0271
  60224. ];
  60225. var samplesFactor = 1.0 / numSamples;
  60226. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60227. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60228. "area", "fallOff", "base", "range", "viewport"
  60229. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60230. this._ssaoPostProcess.onApply = function (effect) {
  60231. if (_this._firstUpdate) {
  60232. effect.setArray3("sampleSphere", sampleSphere);
  60233. effect.setFloat("samplesFactor", samplesFactor);
  60234. effect.setFloat("randTextureTiles", 4.0);
  60235. }
  60236. effect.setFloat("totalStrength", _this.totalStrength);
  60237. effect.setFloat("radius", _this.radius);
  60238. effect.setFloat("area", _this.area);
  60239. effect.setFloat("fallOff", _this.fallOff);
  60240. effect.setFloat("base", _this.base);
  60241. effect.setTexture("textureSampler", _this._depthTexture);
  60242. effect.setTexture("randomSampler", _this._randomTexture);
  60243. };
  60244. };
  60245. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60246. var _this = this;
  60247. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60248. this._ssaoCombinePostProcess.onApply = function (effect) {
  60249. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60250. };
  60251. };
  60252. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60253. var size = 512;
  60254. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60255. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60256. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60257. var context = this._randomTexture.getContext();
  60258. var rand = function (min, max) {
  60259. return Math.random() * (max - min) + min;
  60260. };
  60261. var randVector = BABYLON.Vector3.Zero();
  60262. for (var x = 0; x < size; x++) {
  60263. for (var y = 0; y < size; y++) {
  60264. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60265. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60266. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60267. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60268. context.fillRect(x, y, 1, 1);
  60269. }
  60270. }
  60271. this._randomTexture.update(false);
  60272. };
  60273. __decorate([
  60274. BABYLON.serialize()
  60275. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60276. __decorate([
  60277. BABYLON.serialize()
  60278. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60279. __decorate([
  60280. BABYLON.serialize()
  60281. ], SSAORenderingPipeline.prototype, "area", void 0);
  60282. __decorate([
  60283. BABYLON.serialize()
  60284. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60285. __decorate([
  60286. BABYLON.serialize()
  60287. ], SSAORenderingPipeline.prototype, "base", void 0);
  60288. return SSAORenderingPipeline;
  60289. }(BABYLON.PostProcessRenderPipeline));
  60290. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60291. })(BABYLON || (BABYLON = {}));
  60292. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60293. var BABYLON;
  60294. (function (BABYLON) {
  60295. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60296. __extends(SSAO2RenderingPipeline, _super);
  60297. /**
  60298. * @constructor
  60299. * @param {string} name - The rendering pipeline name
  60300. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60301. * @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 }
  60302. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60303. */
  60304. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60305. var _this = _super.call(this, scene.getEngine(), name) || this;
  60306. // Members
  60307. /**
  60308. * The PassPostProcess id in the pipeline that contains the original scene color
  60309. * @type {string}
  60310. */
  60311. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60312. /**
  60313. * The SSAO PostProcess id in the pipeline
  60314. * @type {string}
  60315. */
  60316. _this.SSAORenderEffect = "SSAORenderEffect";
  60317. /**
  60318. * The horizontal blur PostProcess id in the pipeline
  60319. * @type {string}
  60320. */
  60321. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60322. /**
  60323. * The vertical blur PostProcess id in the pipeline
  60324. * @type {string}
  60325. */
  60326. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60327. /**
  60328. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60329. * @type {string}
  60330. */
  60331. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60332. /**
  60333. * The output strength of the SSAO post-process. Default value is 1.0.
  60334. * @type {number}
  60335. */
  60336. _this.totalStrength = 1.0;
  60337. /**
  60338. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60339. * @type {number}
  60340. */
  60341. _this.maxZ = 100.0;
  60342. /**
  60343. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60344. * @type {number}
  60345. */
  60346. _this.minZAspect = 0.2;
  60347. /**
  60348. * Number of samples used for the SSAO calculations. Default value is 8
  60349. * @type {number}
  60350. */
  60351. _this._samples = 8;
  60352. /**
  60353. * Are we using bilateral blur ?
  60354. * @type {boolean}
  60355. */
  60356. _this._expensiveBlur = true;
  60357. /**
  60358. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60359. * @type {number}
  60360. */
  60361. _this.radius = 2.0;
  60362. /**
  60363. * The base color of the SSAO post-process
  60364. * The final result is "base + ssao" between [0, 1]
  60365. * @type {number}
  60366. */
  60367. _this.base = 0.1;
  60368. _this._firstUpdate = true;
  60369. _this._scene = scene;
  60370. if (!_this.isSupported) {
  60371. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60372. return _this;
  60373. }
  60374. var ssaoRatio = ratio.ssaoRatio || ratio;
  60375. var blurRatio = ratio.blurRatio || ratio;
  60376. // Set up assets
  60377. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60378. _this._createRandomTexture();
  60379. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60380. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60381. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60382. _this._createSSAOPostProcess(1.0);
  60383. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60384. _this._createSSAOCombinePostProcess(blurRatio);
  60385. // Set up pipeline
  60386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60390. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60391. // Finish
  60392. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60393. if (cameras)
  60394. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60395. return _this;
  60396. }
  60397. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60398. get: function () {
  60399. return this._samples;
  60400. },
  60401. set: function (n) {
  60402. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60403. this._samples = n;
  60404. this._sampleSphere = this._generateHemisphere();
  60405. this._firstUpdate = true;
  60406. },
  60407. enumerable: true,
  60408. configurable: true
  60409. });
  60410. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60411. get: function () {
  60412. return this._expensiveBlur;
  60413. },
  60414. set: function (b) {
  60415. 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"]);
  60416. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60417. this._expensiveBlur = b;
  60418. this._firstUpdate = true;
  60419. },
  60420. enumerable: true,
  60421. configurable: true
  60422. });
  60423. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60424. /**
  60425. * Support test.
  60426. * @type {boolean}
  60427. */
  60428. get: function () {
  60429. var engine = BABYLON.Engine.LastCreatedEngine;
  60430. if (!engine) {
  60431. return false;
  60432. }
  60433. return engine.getCaps().drawBuffersExtension;
  60434. },
  60435. enumerable: true,
  60436. configurable: true
  60437. });
  60438. // Public Methods
  60439. /**
  60440. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60441. */
  60442. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60443. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60444. for (var i = 0; i < this._scene.cameras.length; i++) {
  60445. var camera = this._scene.cameras[i];
  60446. this._originalColorPostProcess.dispose(camera);
  60447. this._ssaoPostProcess.dispose(camera);
  60448. this._blurHPostProcess.dispose(camera);
  60449. this._blurVPostProcess.dispose(camera);
  60450. this._ssaoCombinePostProcess.dispose(camera);
  60451. }
  60452. this._randomTexture.dispose();
  60453. if (disableGeometryBufferRenderer)
  60454. this._scene.disableGeometryBufferRenderer();
  60455. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60456. _super.prototype.dispose.call(this);
  60457. };
  60458. // Private Methods
  60459. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60460. var _this = this;
  60461. this._samplerOffsets = [];
  60462. var expensive = this.expensiveBlur;
  60463. for (var i = -8; i < 8; i++) {
  60464. this._samplerOffsets.push(i * 2 + 0.5);
  60465. }
  60466. 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");
  60467. this._blurHPostProcess.onApply = function (effect) {
  60468. if (!_this._scene.activeCamera) {
  60469. return;
  60470. }
  60471. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60472. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60473. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60474. effect.setFloat("radius", _this.radius);
  60475. effect.setTexture("depthSampler", _this._depthTexture);
  60476. if (_this._firstUpdate) {
  60477. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60478. }
  60479. };
  60480. 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");
  60481. this._blurVPostProcess.onApply = function (effect) {
  60482. if (!_this._scene.activeCamera) {
  60483. return;
  60484. }
  60485. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60486. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60487. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60488. effect.setFloat("radius", _this.radius);
  60489. effect.setTexture("depthSampler", _this._depthTexture);
  60490. if (_this._firstUpdate) {
  60491. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60492. _this._firstUpdate = false;
  60493. }
  60494. };
  60495. };
  60496. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60497. this._firstUpdate = true;
  60498. _super.prototype._rebuild.call(this);
  60499. };
  60500. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60501. var numSamples = this.samples;
  60502. var result = [];
  60503. var vector, scale;
  60504. var rand = function (min, max) {
  60505. return Math.random() * (max - min) + min;
  60506. };
  60507. var i = 0;
  60508. while (i < numSamples) {
  60509. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60510. vector.normalize();
  60511. scale = i / numSamples;
  60512. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60513. vector.scaleInPlace(scale);
  60514. result.push(vector.x, vector.y, vector.z);
  60515. i++;
  60516. }
  60517. return result;
  60518. };
  60519. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60520. var _this = this;
  60521. var numSamples = this.samples;
  60522. this._sampleSphere = this._generateHemisphere();
  60523. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60524. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60525. "base", "range", "projection", "near", "far", "texelSize",
  60526. "xViewport", "yViewport", "maxZ", "minZAspect"
  60527. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60528. this._ssaoPostProcess.onApply = function (effect) {
  60529. if (_this._firstUpdate) {
  60530. effect.setArray3("sampleSphere", _this._sampleSphere);
  60531. effect.setFloat("randTextureTiles", 4.0);
  60532. }
  60533. if (!_this._scene.activeCamera) {
  60534. return;
  60535. }
  60536. effect.setFloat("samplesFactor", 1 / _this.samples);
  60537. effect.setFloat("totalStrength", _this.totalStrength);
  60538. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60539. effect.setFloat("radius", _this.radius);
  60540. effect.setFloat("maxZ", _this.maxZ);
  60541. effect.setFloat("minZAspect", _this.minZAspect);
  60542. effect.setFloat("base", _this.base);
  60543. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60544. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60545. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60546. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60547. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60548. effect.setTexture("textureSampler", _this._depthTexture);
  60549. effect.setTexture("normalSampler", _this._normalTexture);
  60550. effect.setTexture("randomSampler", _this._randomTexture);
  60551. };
  60552. };
  60553. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60554. var _this = this;
  60555. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60556. this._ssaoCombinePostProcess.onApply = function (effect) {
  60557. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60558. };
  60559. };
  60560. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60561. var size = 512;
  60562. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60563. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60564. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60565. var context = this._randomTexture.getContext();
  60566. var rand = function (min, max) {
  60567. return Math.random() * (max - min) + min;
  60568. };
  60569. var randVector = BABYLON.Vector3.Zero();
  60570. for (var x = 0; x < size; x++) {
  60571. for (var y = 0; y < size; y++) {
  60572. randVector.x = rand(0.0, 1.0);
  60573. randVector.y = rand(0.0, 1.0);
  60574. randVector.z = 0.0;
  60575. randVector.normalize();
  60576. randVector.scaleInPlace(255);
  60577. randVector.x = Math.floor(randVector.x);
  60578. randVector.y = Math.floor(randVector.y);
  60579. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60580. context.fillRect(x, y, 1, 1);
  60581. }
  60582. }
  60583. this._randomTexture.update(false);
  60584. };
  60585. __decorate([
  60586. BABYLON.serialize()
  60587. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60588. __decorate([
  60589. BABYLON.serialize()
  60590. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60591. __decorate([
  60592. BABYLON.serialize()
  60593. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60594. __decorate([
  60595. BABYLON.serialize("samples")
  60596. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60597. __decorate([
  60598. BABYLON.serialize("expensiveBlur")
  60599. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60600. __decorate([
  60601. BABYLON.serialize()
  60602. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60603. __decorate([
  60604. BABYLON.serialize()
  60605. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60606. return SSAO2RenderingPipeline;
  60607. }(BABYLON.PostProcessRenderPipeline));
  60608. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60609. })(BABYLON || (BABYLON = {}));
  60610. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60611. // BABYLON.JS Chromatic Aberration GLSL Shader
  60612. // Author: Olivier Guyot
  60613. // Separates very slightly R, G and B colors on the edges of the screen
  60614. // Inspired by Francois Tarlier & Martins Upitis
  60615. var BABYLON;
  60616. (function (BABYLON) {
  60617. var LensRenderingPipeline = /** @class */ (function (_super) {
  60618. __extends(LensRenderingPipeline, _super);
  60619. /**
  60620. * @constructor
  60621. *
  60622. * Effect parameters are as follow:
  60623. * {
  60624. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60625. * edge_blur: number; // from 0 to x (1 for realism)
  60626. * distortion: number; // from 0 to x (1 for realism)
  60627. * grain_amount: number; // from 0 to 1
  60628. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60629. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60630. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60631. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60632. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60633. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60634. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60635. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60636. * }
  60637. * Note: if an effect parameter is unset, effect is disabled
  60638. *
  60639. * @param {string} name - The rendering pipeline name
  60640. * @param {object} parameters - An object containing all parameters (see above)
  60641. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60642. * @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)
  60643. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60644. */
  60645. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60646. if (ratio === void 0) { ratio = 1.0; }
  60647. var _this = _super.call(this, scene.getEngine(), name) || this;
  60648. // Lens effects can be of the following:
  60649. // - chromatic aberration (slight shift of RGB colors)
  60650. // - blur on the edge of the lens
  60651. // - lens distortion
  60652. // - depth-of-field blur & highlights enhancing
  60653. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60654. // - grain effect (noise or custom texture)
  60655. // Two additional texture samplers are needed:
  60656. // - depth map (for depth-of-field)
  60657. // - grain texture
  60658. /**
  60659. * The chromatic aberration PostProcess id in the pipeline
  60660. * @type {string}
  60661. */
  60662. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60663. /**
  60664. * The highlights enhancing PostProcess id in the pipeline
  60665. * @type {string}
  60666. */
  60667. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60668. /**
  60669. * The depth-of-field PostProcess id in the pipeline
  60670. * @type {string}
  60671. */
  60672. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60673. _this._scene = scene;
  60674. // Fetch texture samplers
  60675. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60676. if (parameters.grain_texture) {
  60677. _this._grainTexture = parameters.grain_texture;
  60678. }
  60679. else {
  60680. _this._createGrainTexture();
  60681. }
  60682. // save parameters
  60683. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60684. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60685. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60686. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60687. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60688. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60689. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60690. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60691. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60692. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60693. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60694. // Create effects
  60695. _this._createChromaticAberrationPostProcess(ratio);
  60696. _this._createHighlightsPostProcess(ratio);
  60697. _this._createDepthOfFieldPostProcess(ratio / 4);
  60698. // Set up pipeline
  60699. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60700. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60701. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60702. if (_this._highlightsGain === -1) {
  60703. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60704. }
  60705. // Finish
  60706. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60707. if (cameras) {
  60708. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60709. }
  60710. return _this;
  60711. }
  60712. // public methods (self explanatory)
  60713. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60714. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60715. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60716. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60717. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60718. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60719. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60720. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60721. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60722. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60723. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60724. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60725. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60726. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60727. };
  60728. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60729. this._highlightsPostProcess.updateEffect();
  60730. };
  60731. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60732. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60733. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60734. this._highlightsGain = amount;
  60735. };
  60736. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60737. if (this._highlightsGain === -1) {
  60738. this._highlightsGain = 1.0;
  60739. }
  60740. this._highlightsThreshold = amount;
  60741. };
  60742. LensRenderingPipeline.prototype.disableHighlights = function () {
  60743. this._highlightsGain = -1;
  60744. };
  60745. /**
  60746. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60747. */
  60748. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60749. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60750. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60751. this._chromaticAberrationPostProcess = null;
  60752. this._highlightsPostProcess = null;
  60753. this._depthOfFieldPostProcess = null;
  60754. this._grainTexture.dispose();
  60755. if (disableDepthRender)
  60756. this._scene.disableDepthRenderer();
  60757. };
  60758. // colors shifting and distortion
  60759. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60760. var _this = this;
  60761. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60762. [], // samplers
  60763. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60764. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60765. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60766. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60767. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60768. };
  60769. };
  60770. // highlights enhancing
  60771. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60772. var _this = this;
  60773. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60774. [], // samplers
  60775. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60776. this._highlightsPostProcess.onApply = function (effect) {
  60777. effect.setFloat('gain', _this._highlightsGain);
  60778. effect.setFloat('threshold', _this._highlightsThreshold);
  60779. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60780. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60781. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60782. };
  60783. };
  60784. // colors shifting and distortion
  60785. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60786. var _this = this;
  60787. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60788. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60789. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60790. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60791. this._depthOfFieldPostProcess.onApply = function (effect) {
  60792. effect.setTexture("depthSampler", _this._depthTexture);
  60793. effect.setTexture("grainSampler", _this._grainTexture);
  60794. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60795. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60796. effect.setFloat('grain_amount', _this._grainAmount);
  60797. effect.setBool('blur_noise', _this._blurNoise);
  60798. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60799. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60800. effect.setFloat('distortion', _this._distortion);
  60801. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60802. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60803. effect.setFloat('aperture', _this._dofAperture);
  60804. effect.setFloat('darken', _this._dofDarken);
  60805. effect.setFloat('edge_blur', _this._edgeBlur);
  60806. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60807. if (_this._scene.activeCamera) {
  60808. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60809. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60810. }
  60811. };
  60812. };
  60813. // creates a black and white random noise texture, 512x512
  60814. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60815. var size = 512;
  60816. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60817. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60818. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60819. var context = this._grainTexture.getContext();
  60820. var rand = function (min, max) {
  60821. return Math.random() * (max - min) + min;
  60822. };
  60823. var value;
  60824. for (var x = 0; x < size; x++) {
  60825. for (var y = 0; y < size; y++) {
  60826. value = Math.floor(rand(0.42, 0.58) * 255);
  60827. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60828. context.fillRect(x, y, 1, 1);
  60829. }
  60830. }
  60831. this._grainTexture.update(false);
  60832. };
  60833. return LensRenderingPipeline;
  60834. }(BABYLON.PostProcessRenderPipeline));
  60835. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60836. })(BABYLON || (BABYLON = {}));
  60837. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60838. var BABYLON;
  60839. (function (BABYLON) {
  60840. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60841. __extends(StandardRenderingPipeline, _super);
  60842. /**
  60843. * @constructor
  60844. * @param {string} name - The rendering pipeline name
  60845. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60846. * @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)
  60847. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60848. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60849. */
  60850. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60851. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60852. var _this = _super.call(this, scene.getEngine(), name) || this;
  60853. _this.downSampleX4PostProcess = null;
  60854. _this.brightPassPostProcess = null;
  60855. _this.blurHPostProcesses = [];
  60856. _this.blurVPostProcesses = [];
  60857. _this.textureAdderPostProcess = null;
  60858. _this.volumetricLightPostProcess = null;
  60859. _this.volumetricLightSmoothXPostProcess = null;
  60860. _this.volumetricLightSmoothYPostProcess = null;
  60861. _this.volumetricLightMergePostProces = null;
  60862. _this.volumetricLightFinalPostProcess = null;
  60863. _this.luminancePostProcess = null;
  60864. _this.luminanceDownSamplePostProcesses = [];
  60865. _this.hdrPostProcess = null;
  60866. _this.textureAdderFinalPostProcess = null;
  60867. _this.lensFlareFinalPostProcess = null;
  60868. _this.hdrFinalPostProcess = null;
  60869. _this.lensFlarePostProcess = null;
  60870. _this.lensFlareComposePostProcess = null;
  60871. _this.motionBlurPostProcess = null;
  60872. _this.depthOfFieldPostProcess = null;
  60873. // Values
  60874. _this.brightThreshold = 1.0;
  60875. _this.blurWidth = 512.0;
  60876. _this.horizontalBlur = false;
  60877. _this.exposure = 1.0;
  60878. _this.lensTexture = null;
  60879. _this.volumetricLightCoefficient = 0.2;
  60880. _this.volumetricLightPower = 4.0;
  60881. _this.volumetricLightBlurScale = 64.0;
  60882. _this.sourceLight = null;
  60883. _this.hdrMinimumLuminance = 1.0;
  60884. _this.hdrDecreaseRate = 0.5;
  60885. _this.hdrIncreaseRate = 0.5;
  60886. _this.lensColorTexture = null;
  60887. _this.lensFlareStrength = 20.0;
  60888. _this.lensFlareGhostDispersal = 1.4;
  60889. _this.lensFlareHaloWidth = 0.7;
  60890. _this.lensFlareDistortionStrength = 16.0;
  60891. _this.lensStarTexture = null;
  60892. _this.lensFlareDirtTexture = null;
  60893. _this.depthOfFieldDistance = 10.0;
  60894. _this.depthOfFieldBlurWidth = 64.0;
  60895. _this.motionStrength = 1.0;
  60896. // IAnimatable
  60897. _this.animations = [];
  60898. _this._currentDepthOfFieldSource = null;
  60899. _this._hdrCurrentLuminance = 1.0;
  60900. // Getters and setters
  60901. _this._bloomEnabled = true;
  60902. _this._depthOfFieldEnabled = false;
  60903. _this._vlsEnabled = false;
  60904. _this._lensFlareEnabled = false;
  60905. _this._hdrEnabled = false;
  60906. _this._motionBlurEnabled = false;
  60907. _this._motionBlurSamples = 64.0;
  60908. _this._volumetricLightStepsCount = 50.0;
  60909. _this._cameras = cameras || [];
  60910. // Initialize
  60911. _this._scene = scene;
  60912. _this._basePostProcess = originalPostProcess;
  60913. _this._ratio = ratio;
  60914. // Misc
  60915. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60916. // Finish
  60917. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60918. _this._buildPipeline();
  60919. return _this;
  60920. }
  60921. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60922. get: function () {
  60923. return this._bloomEnabled;
  60924. },
  60925. set: function (enabled) {
  60926. if (this._bloomEnabled === enabled) {
  60927. return;
  60928. }
  60929. this._bloomEnabled = enabled;
  60930. this._buildPipeline();
  60931. },
  60932. enumerable: true,
  60933. configurable: true
  60934. });
  60935. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60936. get: function () {
  60937. return this._depthOfFieldEnabled;
  60938. },
  60939. set: function (enabled) {
  60940. if (this._depthOfFieldEnabled === enabled) {
  60941. return;
  60942. }
  60943. this._depthOfFieldEnabled = enabled;
  60944. this._buildPipeline();
  60945. },
  60946. enumerable: true,
  60947. configurable: true
  60948. });
  60949. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60950. get: function () {
  60951. return this._lensFlareEnabled;
  60952. },
  60953. set: function (enabled) {
  60954. if (this._lensFlareEnabled === enabled) {
  60955. return;
  60956. }
  60957. this._lensFlareEnabled = enabled;
  60958. this._buildPipeline();
  60959. },
  60960. enumerable: true,
  60961. configurable: true
  60962. });
  60963. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60964. get: function () {
  60965. return this._hdrEnabled;
  60966. },
  60967. set: function (enabled) {
  60968. if (this._hdrEnabled === enabled) {
  60969. return;
  60970. }
  60971. this._hdrEnabled = enabled;
  60972. this._buildPipeline();
  60973. },
  60974. enumerable: true,
  60975. configurable: true
  60976. });
  60977. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60978. get: function () {
  60979. return this._vlsEnabled;
  60980. },
  60981. set: function (enabled) {
  60982. if (this._vlsEnabled === enabled) {
  60983. return;
  60984. }
  60985. if (enabled) {
  60986. var geometry = this._scene.enableGeometryBufferRenderer();
  60987. if (!geometry) {
  60988. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60989. return;
  60990. }
  60991. }
  60992. this._vlsEnabled = enabled;
  60993. this._buildPipeline();
  60994. },
  60995. enumerable: true,
  60996. configurable: true
  60997. });
  60998. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60999. get: function () {
  61000. return this._motionBlurEnabled;
  61001. },
  61002. set: function (enabled) {
  61003. if (this._motionBlurEnabled === enabled) {
  61004. return;
  61005. }
  61006. this._motionBlurEnabled = enabled;
  61007. this._buildPipeline();
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  61013. get: function () {
  61014. return this._volumetricLightStepsCount;
  61015. },
  61016. set: function (count) {
  61017. if (this.volumetricLightPostProcess) {
  61018. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  61019. }
  61020. this._volumetricLightStepsCount = count;
  61021. },
  61022. enumerable: true,
  61023. configurable: true
  61024. });
  61025. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  61026. get: function () {
  61027. return this._motionBlurSamples;
  61028. },
  61029. set: function (samples) {
  61030. if (this.motionBlurPostProcess) {
  61031. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  61032. }
  61033. this._motionBlurSamples = samples;
  61034. },
  61035. enumerable: true,
  61036. configurable: true
  61037. });
  61038. StandardRenderingPipeline.prototype._buildPipeline = function () {
  61039. var _this = this;
  61040. var ratio = this._ratio;
  61041. var scene = this._scene;
  61042. this._disposePostProcesses();
  61043. this._reset();
  61044. // Create pass post-process
  61045. if (!this._basePostProcess) {
  61046. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  61047. this.originalPostProcess.onApply = function (effect) {
  61048. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  61049. };
  61050. }
  61051. else {
  61052. this.originalPostProcess = this._basePostProcess;
  61053. }
  61054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  61055. this._currentDepthOfFieldSource = this.originalPostProcess;
  61056. if (this._vlsEnabled) {
  61057. // Create volumetric light
  61058. this._createVolumetricLightPostProcess(scene, ratio);
  61059. // Create volumetric light final post-process
  61060. 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);
  61061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  61062. }
  61063. if (this._bloomEnabled) {
  61064. // Create down sample X4 post-process
  61065. this._createDownSampleX4PostProcess(scene, ratio / 2);
  61066. // Create bright pass post-process
  61067. this._createBrightPassPostProcess(scene, ratio / 2);
  61068. // Create gaussian blur post-processes (down sampling blurs)
  61069. this._createBlurPostProcesses(scene, ratio / 4, 1);
  61070. // Create texture adder post-process
  61071. this._createTextureAdderPostProcess(scene, ratio);
  61072. // Create depth-of-field source post-process
  61073. 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);
  61074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  61075. }
  61076. if (this._lensFlareEnabled) {
  61077. // Create lens flare post-process
  61078. this._createLensFlarePostProcess(scene, ratio);
  61079. // Create depth-of-field source post-process post lens-flare and disable it now
  61080. 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);
  61081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  61082. }
  61083. if (this._hdrEnabled) {
  61084. // Create luminance
  61085. this._createLuminancePostProcesses(scene, this._floatTextureType);
  61086. // Create HDR
  61087. this._createHdrPostProcess(scene, ratio);
  61088. // Create depth-of-field source post-process post hdr and disable it now
  61089. 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);
  61090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  61091. }
  61092. if (this._depthOfFieldEnabled) {
  61093. // Create gaussian blur used by depth-of-field
  61094. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  61095. // Create depth-of-field post-process
  61096. this._createDepthOfFieldPostProcess(scene, ratio);
  61097. }
  61098. if (this._motionBlurEnabled) {
  61099. // Create motion blur post-process
  61100. this._createMotionBlurPostProcess(scene, ratio);
  61101. }
  61102. if (this._cameras !== null) {
  61103. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61104. }
  61105. };
  61106. // Down Sample X4 Post-Processs
  61107. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61108. var _this = this;
  61109. var downSampleX4Offsets = new Array(32);
  61110. 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);
  61111. this.downSampleX4PostProcess.onApply = function (effect) {
  61112. var id = 0;
  61113. var width = _this.downSampleX4PostProcess.width;
  61114. var height = _this.downSampleX4PostProcess.height;
  61115. for (var i = -2; i < 2; i++) {
  61116. for (var j = -2; j < 2; j++) {
  61117. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  61118. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  61119. id += 2;
  61120. }
  61121. }
  61122. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61123. };
  61124. // Add to pipeline
  61125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61126. };
  61127. // Brightpass Post-Process
  61128. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61129. var _this = this;
  61130. var brightOffsets = new Array(8);
  61131. 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);
  61132. this.brightPassPostProcess.onApply = function (effect) {
  61133. var sU = (1.0 / _this.brightPassPostProcess.width);
  61134. var sV = (1.0 / _this.brightPassPostProcess.height);
  61135. brightOffsets[0] = -0.5 * sU;
  61136. brightOffsets[1] = 0.5 * sV;
  61137. brightOffsets[2] = 0.5 * sU;
  61138. brightOffsets[3] = 0.5 * sV;
  61139. brightOffsets[4] = -0.5 * sU;
  61140. brightOffsets[5] = -0.5 * sV;
  61141. brightOffsets[6] = 0.5 * sU;
  61142. brightOffsets[7] = -0.5 * sV;
  61143. effect.setArray2("dsOffsets", brightOffsets);
  61144. effect.setFloat("brightThreshold", _this.brightThreshold);
  61145. };
  61146. // Add to pipeline
  61147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61148. };
  61149. // Create blur H&V post-processes
  61150. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61151. var _this = this;
  61152. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61153. var engine = scene.getEngine();
  61154. 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);
  61155. 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);
  61156. blurX.onActivateObservable.add(function () {
  61157. var dw = blurX.width / engine.getRenderWidth();
  61158. blurX.kernel = _this[blurWidthKey] * dw;
  61159. });
  61160. blurY.onActivateObservable.add(function () {
  61161. var dw = blurY.height / engine.getRenderHeight();
  61162. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61163. });
  61164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61166. this.blurHPostProcesses.push(blurX);
  61167. this.blurVPostProcesses.push(blurY);
  61168. };
  61169. // Create texture adder post-process
  61170. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61171. var _this = this;
  61172. 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);
  61173. this.textureAdderPostProcess.onApply = function (effect) {
  61174. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61175. effect.setTexture("lensSampler", _this.lensTexture);
  61176. effect.setFloat("exposure", _this.exposure);
  61177. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61178. };
  61179. // Add to pipeline
  61180. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61181. };
  61182. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61183. var _this = this;
  61184. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61185. geometryRenderer.enablePosition = true;
  61186. var geometry = geometryRenderer.getGBuffer();
  61187. // Base post-process
  61188. 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));
  61189. var depthValues = BABYLON.Vector2.Zero();
  61190. this.volumetricLightPostProcess.onApply = function (effect) {
  61191. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61192. var generator = _this.sourceLight.getShadowGenerator();
  61193. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61194. effect.setTexture("positionSampler", geometry.textures[2]);
  61195. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61196. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61197. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61198. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61199. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61200. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61201. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61202. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61203. effect.setVector2("depthValues", depthValues);
  61204. }
  61205. };
  61206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61207. // Smooth
  61208. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61209. // Merge
  61210. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61211. this.volumetricLightMergePostProces.onApply = function (effect) {
  61212. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61213. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61214. };
  61215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61216. };
  61217. // Create luminance
  61218. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61219. var _this = this;
  61220. // Create luminance
  61221. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61222. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61223. var offsets = [];
  61224. this.luminancePostProcess.onApply = function (effect) {
  61225. var sU = (1.0 / _this.luminancePostProcess.width);
  61226. var sV = (1.0 / _this.luminancePostProcess.height);
  61227. offsets[0] = -0.5 * sU;
  61228. offsets[1] = 0.5 * sV;
  61229. offsets[2] = 0.5 * sU;
  61230. offsets[3] = 0.5 * sV;
  61231. offsets[4] = -0.5 * sU;
  61232. offsets[5] = -0.5 * sV;
  61233. offsets[6] = 0.5 * sU;
  61234. offsets[7] = -0.5 * sV;
  61235. effect.setArray2("lumOffsets", offsets);
  61236. };
  61237. // Add to pipeline
  61238. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61239. // Create down sample luminance
  61240. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61241. var size = Math.pow(3, i);
  61242. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61243. if (i === 0) {
  61244. defines += "#define FINAL_DOWN_SAMPLER";
  61245. }
  61246. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61247. this.luminanceDownSamplePostProcesses.push(postProcess);
  61248. }
  61249. // Create callbacks and add effects
  61250. var lastLuminance = this.luminancePostProcess;
  61251. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61252. var downSampleOffsets = new Array(18);
  61253. pp.onApply = function (effect) {
  61254. if (!lastLuminance) {
  61255. return;
  61256. }
  61257. var id = 0;
  61258. for (var x = -1; x < 2; x++) {
  61259. for (var y = -1; y < 2; y++) {
  61260. downSampleOffsets[id] = x / lastLuminance.width;
  61261. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61262. id += 2;
  61263. }
  61264. }
  61265. effect.setArray2("dsOffsets", downSampleOffsets);
  61266. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61267. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61268. lastLuminance = _this.luminancePostProcess;
  61269. }
  61270. else {
  61271. lastLuminance = pp;
  61272. }
  61273. };
  61274. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61275. pp.onAfterRender = function (effect) {
  61276. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61277. 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);
  61278. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61279. };
  61280. }
  61281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61282. });
  61283. };
  61284. // Create HDR post-process
  61285. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61286. var _this = this;
  61287. 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);
  61288. var outputLiminance = 1;
  61289. var time = 0;
  61290. var lastTime = 0;
  61291. this.hdrPostProcess.onApply = function (effect) {
  61292. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61293. time += scene.getEngine().getDeltaTime();
  61294. if (outputLiminance < 0) {
  61295. outputLiminance = _this._hdrCurrentLuminance;
  61296. }
  61297. else {
  61298. var dt = (lastTime - time) / 1000.0;
  61299. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61300. outputLiminance += _this.hdrDecreaseRate * dt;
  61301. }
  61302. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61303. outputLiminance -= _this.hdrIncreaseRate * dt;
  61304. }
  61305. else {
  61306. outputLiminance = _this._hdrCurrentLuminance;
  61307. }
  61308. }
  61309. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61310. effect.setFloat("averageLuminance", outputLiminance);
  61311. lastTime = time;
  61312. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61313. };
  61314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61315. };
  61316. // Create lens flare post-process
  61317. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61318. var _this = this;
  61319. 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);
  61320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61321. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61322. 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);
  61323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61324. var resolution = new BABYLON.Vector2(0, 0);
  61325. // Lens flare
  61326. this.lensFlarePostProcess.onApply = function (effect) {
  61327. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61328. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61329. effect.setFloat("strength", _this.lensFlareStrength);
  61330. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61331. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61332. // Shift
  61333. resolution.x = _this.lensFlarePostProcess.width;
  61334. resolution.y = _this.lensFlarePostProcess.height;
  61335. effect.setVector2("resolution", resolution);
  61336. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61337. };
  61338. // Compose
  61339. 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);
  61340. 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);
  61341. this.lensFlareComposePostProcess.onApply = function (effect) {
  61342. if (!_this._scene.activeCamera) {
  61343. return;
  61344. }
  61345. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61346. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61347. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61348. // Lens start rotation matrix
  61349. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61350. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61351. 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));
  61352. camRot *= 4.0;
  61353. 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);
  61354. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61355. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61356. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61357. };
  61358. };
  61359. // Create depth-of-field post-process
  61360. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61361. var _this = this;
  61362. 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);
  61363. this.depthOfFieldPostProcess.onApply = function (effect) {
  61364. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61365. effect.setTexture("depthSampler", _this._getDepthTexture());
  61366. effect.setFloat("distance", _this.depthOfFieldDistance);
  61367. };
  61368. // Add to pipeline
  61369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61370. };
  61371. // Create motion blur post-process
  61372. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61373. var _this = this;
  61374. 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);
  61375. var motionScale = 0;
  61376. var prevViewProjection = BABYLON.Matrix.Identity();
  61377. var invViewProjection = BABYLON.Matrix.Identity();
  61378. var viewProjection = BABYLON.Matrix.Identity();
  61379. var screenSize = BABYLON.Vector2.Zero();
  61380. this.motionBlurPostProcess.onApply = function (effect) {
  61381. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61382. viewProjection.invertToRef(invViewProjection);
  61383. effect.setMatrix("inverseViewProjection", invViewProjection);
  61384. effect.setMatrix("prevViewProjection", prevViewProjection);
  61385. prevViewProjection = viewProjection;
  61386. screenSize.x = _this.motionBlurPostProcess.width;
  61387. screenSize.y = _this.motionBlurPostProcess.height;
  61388. effect.setVector2("screenSize", screenSize);
  61389. motionScale = scene.getEngine().getFps() / 60.0;
  61390. effect.setFloat("motionScale", motionScale);
  61391. effect.setFloat("motionStrength", _this.motionStrength);
  61392. effect.setTexture("depthSampler", _this._getDepthTexture());
  61393. };
  61394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61395. };
  61396. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61397. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61398. var renderer = this._scene.enableGeometryBufferRenderer();
  61399. return renderer.getGBuffer().textures[0];
  61400. }
  61401. return this._scene.enableDepthRenderer().getDepthMap();
  61402. };
  61403. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61404. for (var i = 0; i < this._cameras.length; i++) {
  61405. var camera = this._cameras[i];
  61406. if (this.originalPostProcess) {
  61407. this.originalPostProcess.dispose(camera);
  61408. }
  61409. if (this.downSampleX4PostProcess) {
  61410. this.downSampleX4PostProcess.dispose(camera);
  61411. }
  61412. if (this.brightPassPostProcess) {
  61413. this.brightPassPostProcess.dispose(camera);
  61414. }
  61415. if (this.textureAdderPostProcess) {
  61416. this.textureAdderPostProcess.dispose(camera);
  61417. }
  61418. if (this.textureAdderFinalPostProcess) {
  61419. this.textureAdderFinalPostProcess.dispose(camera);
  61420. }
  61421. if (this.volumetricLightPostProcess) {
  61422. this.volumetricLightPostProcess.dispose(camera);
  61423. }
  61424. if (this.volumetricLightSmoothXPostProcess) {
  61425. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61426. }
  61427. if (this.volumetricLightSmoothYPostProcess) {
  61428. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61429. }
  61430. if (this.volumetricLightMergePostProces) {
  61431. this.volumetricLightMergePostProces.dispose(camera);
  61432. }
  61433. if (this.volumetricLightFinalPostProcess) {
  61434. this.volumetricLightFinalPostProcess.dispose(camera);
  61435. }
  61436. if (this.lensFlarePostProcess) {
  61437. this.lensFlarePostProcess.dispose(camera);
  61438. }
  61439. if (this.lensFlareComposePostProcess) {
  61440. this.lensFlareComposePostProcess.dispose(camera);
  61441. }
  61442. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61443. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61444. }
  61445. if (this.luminancePostProcess) {
  61446. this.luminancePostProcess.dispose(camera);
  61447. }
  61448. if (this.hdrPostProcess) {
  61449. this.hdrPostProcess.dispose(camera);
  61450. }
  61451. if (this.hdrFinalPostProcess) {
  61452. this.hdrFinalPostProcess.dispose(camera);
  61453. }
  61454. if (this.depthOfFieldPostProcess) {
  61455. this.depthOfFieldPostProcess.dispose(camera);
  61456. }
  61457. if (this.motionBlurPostProcess) {
  61458. this.motionBlurPostProcess.dispose(camera);
  61459. }
  61460. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61461. this.blurHPostProcesses[j].dispose(camera);
  61462. }
  61463. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61464. this.blurVPostProcesses[j].dispose(camera);
  61465. }
  61466. }
  61467. this.originalPostProcess = null;
  61468. this.downSampleX4PostProcess = null;
  61469. this.brightPassPostProcess = null;
  61470. this.textureAdderPostProcess = null;
  61471. this.textureAdderFinalPostProcess = null;
  61472. this.volumetricLightPostProcess = null;
  61473. this.volumetricLightSmoothXPostProcess = null;
  61474. this.volumetricLightSmoothYPostProcess = null;
  61475. this.volumetricLightMergePostProces = null;
  61476. this.volumetricLightFinalPostProcess = null;
  61477. this.lensFlarePostProcess = null;
  61478. this.lensFlareComposePostProcess = null;
  61479. this.luminancePostProcess = null;
  61480. this.hdrPostProcess = null;
  61481. this.hdrFinalPostProcess = null;
  61482. this.depthOfFieldPostProcess = null;
  61483. this.motionBlurPostProcess = null;
  61484. this.luminanceDownSamplePostProcesses = [];
  61485. this.blurHPostProcesses = [];
  61486. this.blurVPostProcesses = [];
  61487. };
  61488. // Dispose
  61489. StandardRenderingPipeline.prototype.dispose = function () {
  61490. this._disposePostProcesses();
  61491. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61492. _super.prototype.dispose.call(this);
  61493. };
  61494. // Serialize rendering pipeline
  61495. StandardRenderingPipeline.prototype.serialize = function () {
  61496. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61497. serializationObject.customType = "StandardRenderingPipeline";
  61498. return serializationObject;
  61499. };
  61500. /**
  61501. * Static members
  61502. */
  61503. // Parse serialized pipeline
  61504. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61505. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61506. };
  61507. // Luminance steps
  61508. StandardRenderingPipeline.LuminanceSteps = 6;
  61509. __decorate([
  61510. BABYLON.serialize()
  61511. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61512. __decorate([
  61513. BABYLON.serialize()
  61514. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61515. __decorate([
  61516. BABYLON.serialize()
  61517. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61518. __decorate([
  61519. BABYLON.serialize()
  61520. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61521. __decorate([
  61522. BABYLON.serializeAsTexture("lensTexture")
  61523. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61524. __decorate([
  61525. BABYLON.serialize()
  61526. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61527. __decorate([
  61528. BABYLON.serialize()
  61529. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61530. __decorate([
  61531. BABYLON.serialize()
  61532. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61533. __decorate([
  61534. BABYLON.serialize()
  61535. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61536. __decorate([
  61537. BABYLON.serialize()
  61538. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61539. __decorate([
  61540. BABYLON.serialize()
  61541. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61542. __decorate([
  61543. BABYLON.serializeAsTexture("lensColorTexture")
  61544. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61545. __decorate([
  61546. BABYLON.serialize()
  61547. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61548. __decorate([
  61549. BABYLON.serialize()
  61550. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61551. __decorate([
  61552. BABYLON.serialize()
  61553. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61554. __decorate([
  61555. BABYLON.serialize()
  61556. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61557. __decorate([
  61558. BABYLON.serializeAsTexture("lensStarTexture")
  61559. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61560. __decorate([
  61561. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61562. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61563. __decorate([
  61564. BABYLON.serialize()
  61565. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61566. __decorate([
  61567. BABYLON.serialize()
  61568. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61569. __decorate([
  61570. BABYLON.serialize()
  61571. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61572. __decorate([
  61573. BABYLON.serialize()
  61574. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61575. __decorate([
  61576. BABYLON.serialize()
  61577. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61578. __decorate([
  61579. BABYLON.serialize()
  61580. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61581. __decorate([
  61582. BABYLON.serialize()
  61583. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61584. __decorate([
  61585. BABYLON.serialize()
  61586. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61587. __decorate([
  61588. BABYLON.serialize()
  61589. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61590. __decorate([
  61591. BABYLON.serialize()
  61592. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61593. __decorate([
  61594. BABYLON.serialize()
  61595. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61596. __decorate([
  61597. BABYLON.serialize()
  61598. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61599. return StandardRenderingPipeline;
  61600. }(BABYLON.PostProcessRenderPipeline));
  61601. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61602. })(BABYLON || (BABYLON = {}));
  61603. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61604. var BABYLON;
  61605. (function (BABYLON) {
  61606. var FxaaPostProcess = /** @class */ (function (_super) {
  61607. __extends(FxaaPostProcess, _super);
  61608. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61609. if (camera === void 0) { camera = null; }
  61610. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61611. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61612. _this.onApplyObservable.add(function (effect) {
  61613. var texelSize = _this.texelSize;
  61614. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61615. });
  61616. return _this;
  61617. }
  61618. return FxaaPostProcess;
  61619. }(BABYLON.PostProcess));
  61620. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61621. })(BABYLON || (BABYLON = {}));
  61622. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61623. var BABYLON;
  61624. (function (BABYLON) {
  61625. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61626. __extends(DefaultRenderingPipeline, _super);
  61627. /**
  61628. * @constructor
  61629. * @param {string} name - The rendering pipeline name
  61630. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61631. * @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)
  61632. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61633. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61634. */
  61635. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61636. if (automaticBuild === void 0) { automaticBuild = true; }
  61637. var _this = _super.call(this, scene.getEngine(), name) || this;
  61638. _this.PassPostProcessId = "PassPostProcessEffect";
  61639. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61640. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61641. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61642. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61643. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61644. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61645. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61646. // IAnimatable
  61647. _this.animations = [];
  61648. // Values
  61649. _this._bloomEnabled = false;
  61650. _this._fxaaEnabled = false;
  61651. _this._imageProcessingEnabled = true;
  61652. _this._bloomScale = 0.6;
  61653. _this._buildAllowed = true;
  61654. /**
  61655. * Specifies the size of the bloom blur kernel, relative to the final output size
  61656. */
  61657. _this.bloomKernel = 64;
  61658. /**
  61659. * Specifies the weight of the bloom in the final rendering
  61660. */
  61661. _this._bloomWeight = 0.15;
  61662. _this._cameras = cameras || [];
  61663. _this._buildAllowed = automaticBuild;
  61664. // Initialize
  61665. _this._scene = scene;
  61666. var caps = _this._scene.getEngine().getCaps();
  61667. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61668. // Misc
  61669. if (_this._hdr) {
  61670. if (caps.textureHalfFloatRender) {
  61671. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61672. }
  61673. else if (caps.textureFloatRender) {
  61674. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61675. }
  61676. }
  61677. else {
  61678. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61679. }
  61680. // Attach
  61681. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61682. _this._buildPipeline();
  61683. return _this;
  61684. }
  61685. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61686. get: function () {
  61687. return this._bloomWeight;
  61688. },
  61689. set: function (value) {
  61690. if (this._bloomWeight === value) {
  61691. return;
  61692. }
  61693. this._bloomWeight = value;
  61694. if (this._hdr && this.copyBack) {
  61695. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61696. }
  61697. },
  61698. enumerable: true,
  61699. configurable: true
  61700. });
  61701. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61702. get: function () {
  61703. return this._bloomScale;
  61704. },
  61705. set: function (value) {
  61706. if (this._bloomScale === value) {
  61707. return;
  61708. }
  61709. this._bloomScale = value;
  61710. this._buildPipeline();
  61711. },
  61712. enumerable: true,
  61713. configurable: true
  61714. });
  61715. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61716. get: function () {
  61717. return this._bloomEnabled;
  61718. },
  61719. set: function (enabled) {
  61720. if (this._bloomEnabled === enabled) {
  61721. return;
  61722. }
  61723. this._bloomEnabled = enabled;
  61724. this._buildPipeline();
  61725. },
  61726. enumerable: true,
  61727. configurable: true
  61728. });
  61729. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61730. get: function () {
  61731. return this._fxaaEnabled;
  61732. },
  61733. set: function (enabled) {
  61734. if (this._fxaaEnabled === enabled) {
  61735. return;
  61736. }
  61737. this._fxaaEnabled = enabled;
  61738. this._buildPipeline();
  61739. },
  61740. enumerable: true,
  61741. configurable: true
  61742. });
  61743. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61744. get: function () {
  61745. return this._imageProcessingEnabled;
  61746. },
  61747. set: function (enabled) {
  61748. if (this._imageProcessingEnabled === enabled) {
  61749. return;
  61750. }
  61751. this._imageProcessingEnabled = enabled;
  61752. this._buildPipeline();
  61753. },
  61754. enumerable: true,
  61755. configurable: true
  61756. });
  61757. /**
  61758. * Force the compilation of the entire pipeline.
  61759. */
  61760. DefaultRenderingPipeline.prototype.prepare = function () {
  61761. var previousState = this._buildAllowed;
  61762. this._buildAllowed = true;
  61763. this._buildPipeline();
  61764. this._buildAllowed = previousState;
  61765. };
  61766. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61767. var _this = this;
  61768. if (!this._buildAllowed) {
  61769. return;
  61770. }
  61771. var engine = this._scene.getEngine();
  61772. this._disposePostProcesses();
  61773. this._reset();
  61774. if (this.bloomEnabled) {
  61775. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61776. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61777. if (!this._hdr) {
  61778. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61779. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61780. this.highlights.autoClear = false;
  61781. this.highlights.alwaysForcePOT = true;
  61782. }
  61783. 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);
  61784. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61785. this.blurX.alwaysForcePOT = true;
  61786. this.blurX.autoClear = false;
  61787. this.blurX.onActivateObservable.add(function () {
  61788. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61789. _this.blurX.kernel = _this.bloomKernel * dw;
  61790. });
  61791. 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);
  61792. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61793. this.blurY.alwaysForcePOT = true;
  61794. this.blurY.autoClear = false;
  61795. this.blurY.onActivateObservable.add(function () {
  61796. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61797. _this.blurY.kernel = _this.bloomKernel * dh;
  61798. });
  61799. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61800. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61801. this.copyBack.alwaysForcePOT = true;
  61802. if (this._hdr) {
  61803. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61804. var w = this.bloomWeight;
  61805. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61806. }
  61807. else {
  61808. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61809. }
  61810. this.copyBack.autoClear = false;
  61811. }
  61812. if (this._imageProcessingEnabled) {
  61813. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61814. if (this._hdr) {
  61815. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61816. }
  61817. else {
  61818. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61819. }
  61820. }
  61821. if (this.fxaaEnabled) {
  61822. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61823. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61824. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61825. }
  61826. else if (this._hdr && this.imageProcessing) {
  61827. this.finalMerge = this.imageProcessing;
  61828. }
  61829. else {
  61830. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61831. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61832. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61833. }
  61834. if (this.bloomEnabled) {
  61835. if (this._hdr) {
  61836. this.copyBack.shareOutputWith(this.blurX);
  61837. if (this.imageProcessing) {
  61838. this.imageProcessing.shareOutputWith(this.pass);
  61839. this.imageProcessing.autoClear = false;
  61840. }
  61841. else if (this.fxaa) {
  61842. this.fxaa.shareOutputWith(this.pass);
  61843. }
  61844. else {
  61845. this.finalMerge.shareOutputWith(this.pass);
  61846. }
  61847. }
  61848. else {
  61849. if (this.fxaa) {
  61850. this.fxaa.shareOutputWith(this.pass);
  61851. }
  61852. else {
  61853. this.finalMerge.shareOutputWith(this.pass);
  61854. }
  61855. }
  61856. }
  61857. if (this._cameras !== null) {
  61858. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61859. }
  61860. };
  61861. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61862. for (var i = 0; i < this._cameras.length; i++) {
  61863. var camera = this._cameras[i];
  61864. if (this.pass) {
  61865. this.pass.dispose(camera);
  61866. }
  61867. if (this.highlights) {
  61868. this.highlights.dispose(camera);
  61869. }
  61870. if (this.blurX) {
  61871. this.blurX.dispose(camera);
  61872. }
  61873. if (this.blurY) {
  61874. this.blurY.dispose(camera);
  61875. }
  61876. if (this.copyBack) {
  61877. this.copyBack.dispose(camera);
  61878. }
  61879. if (this.imageProcessing) {
  61880. this.imageProcessing.dispose(camera);
  61881. }
  61882. if (this.fxaa) {
  61883. this.fxaa.dispose(camera);
  61884. }
  61885. if (this.finalMerge) {
  61886. this.finalMerge.dispose(camera);
  61887. }
  61888. }
  61889. this.pass = null;
  61890. this.highlights = null;
  61891. this.blurX = null;
  61892. this.blurY = null;
  61893. this.copyBack = null;
  61894. this.imageProcessing = null;
  61895. this.fxaa = null;
  61896. this.finalMerge = null;
  61897. };
  61898. // Dispose
  61899. DefaultRenderingPipeline.prototype.dispose = function () {
  61900. this._disposePostProcesses();
  61901. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61902. _super.prototype.dispose.call(this);
  61903. };
  61904. // Serialize rendering pipeline
  61905. DefaultRenderingPipeline.prototype.serialize = function () {
  61906. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61907. serializationObject.customType = "DefaultRenderingPipeline";
  61908. return serializationObject;
  61909. };
  61910. // Parse serialized pipeline
  61911. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61912. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61913. };
  61914. __decorate([
  61915. BABYLON.serialize()
  61916. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61917. __decorate([
  61918. BABYLON.serialize()
  61919. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61920. __decorate([
  61921. BABYLON.serialize()
  61922. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61923. __decorate([
  61924. BABYLON.serialize()
  61925. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61926. __decorate([
  61927. BABYLON.serialize()
  61928. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61929. __decorate([
  61930. BABYLON.serialize()
  61931. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61932. __decorate([
  61933. BABYLON.serialize()
  61934. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61935. __decorate([
  61936. BABYLON.serialize()
  61937. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61938. return DefaultRenderingPipeline;
  61939. }(BABYLON.PostProcessRenderPipeline));
  61940. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61941. })(BABYLON || (BABYLON = {}));
  61942. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61943. var BABYLON;
  61944. (function (BABYLON) {
  61945. var GeometryBufferRenderer = /** @class */ (function () {
  61946. function GeometryBufferRenderer(scene, ratio) {
  61947. if (ratio === void 0) { ratio = 1; }
  61948. this._enablePosition = false;
  61949. this._scene = scene;
  61950. this._ratio = ratio;
  61951. // Render target
  61952. this._createRenderTargets();
  61953. }
  61954. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61955. set: function (meshes) {
  61956. this._multiRenderTarget.renderList = meshes;
  61957. },
  61958. enumerable: true,
  61959. configurable: true
  61960. });
  61961. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61962. get: function () {
  61963. return this._multiRenderTarget.isSupported;
  61964. },
  61965. enumerable: true,
  61966. configurable: true
  61967. });
  61968. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61969. get: function () {
  61970. return this._enablePosition;
  61971. },
  61972. set: function (enable) {
  61973. this._enablePosition = enable;
  61974. this.dispose();
  61975. this._createRenderTargets();
  61976. },
  61977. enumerable: true,
  61978. configurable: true
  61979. });
  61980. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61981. var material = subMesh.getMaterial();
  61982. if (material && material.disableDepthWrite) {
  61983. return false;
  61984. }
  61985. var defines = [];
  61986. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61987. var mesh = subMesh.getMesh();
  61988. // Alpha test
  61989. if (material && material.needAlphaTesting()) {
  61990. defines.push("#define ALPHATEST");
  61991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61992. attribs.push(BABYLON.VertexBuffer.UVKind);
  61993. defines.push("#define UV1");
  61994. }
  61995. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61996. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61997. defines.push("#define UV2");
  61998. }
  61999. }
  62000. // Buffers
  62001. if (this._enablePosition) {
  62002. defines.push("#define POSITION");
  62003. }
  62004. // Bones
  62005. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62006. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62007. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62008. if (mesh.numBoneInfluencers > 4) {
  62009. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62010. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62011. }
  62012. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62013. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62014. }
  62015. else {
  62016. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62017. }
  62018. // Instances
  62019. if (useInstances) {
  62020. defines.push("#define INSTANCES");
  62021. attribs.push("world0");
  62022. attribs.push("world1");
  62023. attribs.push("world2");
  62024. attribs.push("world3");
  62025. }
  62026. // Get correct effect
  62027. var join = defines.join("\n");
  62028. if (this._cachedDefines !== join) {
  62029. this._cachedDefines = join;
  62030. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  62031. }
  62032. return this._effect.isReady();
  62033. };
  62034. GeometryBufferRenderer.prototype.getGBuffer = function () {
  62035. return this._multiRenderTarget;
  62036. };
  62037. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  62038. get: function () {
  62039. return this._multiRenderTarget.samples;
  62040. },
  62041. set: function (value) {
  62042. this._multiRenderTarget.samples = value;
  62043. },
  62044. enumerable: true,
  62045. configurable: true
  62046. });
  62047. // Methods
  62048. GeometryBufferRenderer.prototype.dispose = function () {
  62049. this.getGBuffer().dispose();
  62050. };
  62051. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  62052. var _this = this;
  62053. var engine = this._scene.getEngine();
  62054. var count = this._enablePosition ? 3 : 2;
  62055. 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 });
  62056. if (!this.isSupported) {
  62057. return;
  62058. }
  62059. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62060. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62061. this._multiRenderTarget.refreshRate = 1;
  62062. this._multiRenderTarget.renderParticles = false;
  62063. this._multiRenderTarget.renderList = null;
  62064. // set default depth value to 1.0 (far away)
  62065. this._multiRenderTarget.onClearObservable.add(function (engine) {
  62066. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  62067. });
  62068. // Custom render function
  62069. var renderSubMesh = function (subMesh) {
  62070. var mesh = subMesh.getRenderingMesh();
  62071. var scene = _this._scene;
  62072. var engine = scene.getEngine();
  62073. var material = subMesh.getMaterial();
  62074. if (!material) {
  62075. return;
  62076. }
  62077. // Culling
  62078. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62079. // Managing instances
  62080. var batch = mesh._getInstancesRenderList(subMesh._id);
  62081. if (batch.mustReturn) {
  62082. return;
  62083. }
  62084. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62085. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  62086. engine.enableEffect(_this._effect);
  62087. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62088. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62089. _this._effect.setMatrix("view", scene.getViewMatrix());
  62090. // Alpha test
  62091. if (material && material.needAlphaTesting()) {
  62092. var alphaTexture = material.getAlphaTestTexture();
  62093. if (alphaTexture) {
  62094. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62095. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62096. }
  62097. }
  62098. // Bones
  62099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62100. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62101. }
  62102. // Draw
  62103. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62104. }
  62105. };
  62106. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62107. var index;
  62108. if (depthOnlySubMeshes.length) {
  62109. engine.setColorWrite(false);
  62110. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62111. renderSubMesh(depthOnlySubMeshes.data[index]);
  62112. }
  62113. engine.setColorWrite(true);
  62114. }
  62115. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62116. renderSubMesh(opaqueSubMeshes.data[index]);
  62117. }
  62118. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62119. renderSubMesh(alphaTestSubMeshes.data[index]);
  62120. }
  62121. };
  62122. };
  62123. return GeometryBufferRenderer;
  62124. }());
  62125. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  62126. })(BABYLON || (BABYLON = {}));
  62127. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  62128. var BABYLON;
  62129. (function (BABYLON) {
  62130. var RefractionPostProcess = /** @class */ (function (_super) {
  62131. __extends(RefractionPostProcess, _super);
  62132. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  62133. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  62134. _this.color = color;
  62135. _this.depth = depth;
  62136. _this.colorLevel = colorLevel;
  62137. _this.onActivateObservable.add(function (cam) {
  62138. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  62139. });
  62140. _this.onApplyObservable.add(function (effect) {
  62141. effect.setColor3("baseColor", _this.color);
  62142. effect.setFloat("depth", _this.depth);
  62143. effect.setFloat("colorLevel", _this.colorLevel);
  62144. effect.setTexture("refractionSampler", _this._refRexture);
  62145. });
  62146. return _this;
  62147. }
  62148. // Methods
  62149. RefractionPostProcess.prototype.dispose = function (camera) {
  62150. if (this._refRexture) {
  62151. this._refRexture.dispose();
  62152. }
  62153. _super.prototype.dispose.call(this, camera);
  62154. };
  62155. return RefractionPostProcess;
  62156. }(BABYLON.PostProcess));
  62157. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62158. })(BABYLON || (BABYLON = {}));
  62159. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62160. var BABYLON;
  62161. (function (BABYLON) {
  62162. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62163. __extends(BlackAndWhitePostProcess, _super);
  62164. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62165. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62166. _this.degree = 1;
  62167. _this.onApplyObservable.add(function (effect) {
  62168. effect.setFloat("degree", _this.degree);
  62169. });
  62170. return _this;
  62171. }
  62172. return BlackAndWhitePostProcess;
  62173. }(BABYLON.PostProcess));
  62174. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62175. })(BABYLON || (BABYLON = {}));
  62176. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62177. var BABYLON;
  62178. (function (BABYLON) {
  62179. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62180. __extends(ConvolutionPostProcess, _super);
  62181. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62182. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62183. _this.kernel = kernel;
  62184. _this.onApply = function (effect) {
  62185. effect.setFloat2("screenSize", _this.width, _this.height);
  62186. effect.setArray("kernel", _this.kernel);
  62187. };
  62188. return _this;
  62189. }
  62190. // Statics
  62191. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62192. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62193. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62194. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62195. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62196. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62197. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62198. return ConvolutionPostProcess;
  62199. }(BABYLON.PostProcess));
  62200. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62201. })(BABYLON || (BABYLON = {}));
  62202. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62203. var BABYLON;
  62204. (function (BABYLON) {
  62205. var FilterPostProcess = /** @class */ (function (_super) {
  62206. __extends(FilterPostProcess, _super);
  62207. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62208. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62209. _this.kernelMatrix = kernelMatrix;
  62210. _this.onApply = function (effect) {
  62211. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62212. };
  62213. return _this;
  62214. }
  62215. return FilterPostProcess;
  62216. }(BABYLON.PostProcess));
  62217. BABYLON.FilterPostProcess = FilterPostProcess;
  62218. })(BABYLON || (BABYLON = {}));
  62219. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62220. var BABYLON;
  62221. (function (BABYLON) {
  62222. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62223. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62224. __extends(VolumetricLightScatteringPostProcess, _super);
  62225. /**
  62226. * @constructor
  62227. * @param {string} name - The post-process name
  62228. * @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)
  62229. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62230. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62231. * @param {number} samples - The post-process quality, default 100
  62232. * @param {number} samplingMode - The post-process filtering mode
  62233. * @param {BABYLON.Engine} engine - The babylon engine
  62234. * @param {boolean} reusable - If the post-process is reusable
  62235. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62236. */
  62237. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62238. if (samples === void 0) { samples = 100; }
  62239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62240. 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;
  62241. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62242. /**
  62243. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62244. * @type {Vector3}
  62245. */
  62246. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62247. /**
  62248. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62249. * @type {boolean}
  62250. */
  62251. _this.useCustomMeshPosition = false;
  62252. /**
  62253. * If the post-process should inverse the light scattering direction
  62254. * @type {boolean}
  62255. */
  62256. _this.invert = true;
  62257. /**
  62258. * Array containing the excluded meshes not rendered in the internal pass
  62259. */
  62260. _this.excludedMeshes = new Array();
  62261. /**
  62262. * Controls the overall intensity of the post-process
  62263. * @type {number}
  62264. */
  62265. _this.exposure = 0.3;
  62266. /**
  62267. * Dissipates each sample's contribution in range [0, 1]
  62268. * @type {number}
  62269. */
  62270. _this.decay = 0.96815;
  62271. /**
  62272. * Controls the overall intensity of each sample
  62273. * @type {number}
  62274. */
  62275. _this.weight = 0.58767;
  62276. /**
  62277. * Controls the density of each sample
  62278. * @type {number}
  62279. */
  62280. _this.density = 0.926;
  62281. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62282. engine = scene.getEngine();
  62283. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62284. // Configure mesh
  62285. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62286. // Configure
  62287. _this._createPass(scene, ratio.passRatio || ratio);
  62288. _this.onActivate = function (camera) {
  62289. if (!_this.isSupported) {
  62290. _this.dispose(camera);
  62291. }
  62292. _this.onActivate = null;
  62293. };
  62294. _this.onApplyObservable.add(function (effect) {
  62295. _this._updateMeshScreenCoordinates(scene);
  62296. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62297. effect.setFloat("exposure", _this.exposure);
  62298. effect.setFloat("decay", _this.decay);
  62299. effect.setFloat("weight", _this.weight);
  62300. effect.setFloat("density", _this.density);
  62301. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62302. });
  62303. return _this;
  62304. }
  62305. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62306. get: function () {
  62307. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62308. return false;
  62309. },
  62310. set: function (useDiffuseColor) {
  62311. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62312. },
  62313. enumerable: true,
  62314. configurable: true
  62315. });
  62316. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62317. return "VolumetricLightScatteringPostProcess";
  62318. };
  62319. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62320. var mesh = subMesh.getMesh();
  62321. // Render this.mesh as default
  62322. if (mesh === this.mesh && mesh.material) {
  62323. return mesh.material.isReady(mesh);
  62324. }
  62325. var defines = [];
  62326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62327. var material = subMesh.getMaterial();
  62328. // Alpha test
  62329. if (material) {
  62330. if (material.needAlphaTesting()) {
  62331. defines.push("#define ALPHATEST");
  62332. }
  62333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62334. attribs.push(BABYLON.VertexBuffer.UVKind);
  62335. defines.push("#define UV1");
  62336. }
  62337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62338. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62339. defines.push("#define UV2");
  62340. }
  62341. }
  62342. // Bones
  62343. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62344. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62345. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62346. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62347. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62348. }
  62349. else {
  62350. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62351. }
  62352. // Instances
  62353. if (useInstances) {
  62354. defines.push("#define INSTANCES");
  62355. attribs.push("world0");
  62356. attribs.push("world1");
  62357. attribs.push("world2");
  62358. attribs.push("world3");
  62359. }
  62360. // Get correct effect
  62361. var join = defines.join("\n");
  62362. if (this._cachedDefines !== join) {
  62363. this._cachedDefines = join;
  62364. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62365. }
  62366. return this._volumetricLightScatteringPass.isReady();
  62367. };
  62368. /**
  62369. * Sets the new light position for light scattering effect
  62370. * @param {BABYLON.Vector3} The new custom light position
  62371. */
  62372. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62373. this.customMeshPosition = position;
  62374. };
  62375. /**
  62376. * Returns the light position for light scattering effect
  62377. * @return {BABYLON.Vector3} The custom light position
  62378. */
  62379. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62380. return this.customMeshPosition;
  62381. };
  62382. /**
  62383. * Disposes the internal assets and detaches the post-process from the camera
  62384. */
  62385. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62386. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62387. if (rttIndex !== -1) {
  62388. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62389. }
  62390. this._volumetricLightScatteringRTT.dispose();
  62391. _super.prototype.dispose.call(this, camera);
  62392. };
  62393. /**
  62394. * Returns the render target texture used by the post-process
  62395. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62396. */
  62397. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62398. return this._volumetricLightScatteringRTT;
  62399. };
  62400. // Private methods
  62401. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62402. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62403. return true;
  62404. }
  62405. return false;
  62406. };
  62407. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62408. var _this = this;
  62409. var engine = scene.getEngine();
  62410. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62411. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62412. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62413. this._volumetricLightScatteringRTT.renderList = null;
  62414. this._volumetricLightScatteringRTT.renderParticles = false;
  62415. var camera = this.getCamera();
  62416. if (camera) {
  62417. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62418. }
  62419. else {
  62420. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62421. }
  62422. // Custom render function for submeshes
  62423. var renderSubMesh = function (subMesh) {
  62424. var mesh = subMesh.getRenderingMesh();
  62425. if (_this._meshExcluded(mesh)) {
  62426. return;
  62427. }
  62428. var material = subMesh.getMaterial();
  62429. if (!material) {
  62430. return;
  62431. }
  62432. var scene = mesh.getScene();
  62433. var engine = scene.getEngine();
  62434. // Culling
  62435. engine.setState(material.backFaceCulling);
  62436. // Managing instances
  62437. var batch = mesh._getInstancesRenderList(subMesh._id);
  62438. if (batch.mustReturn) {
  62439. return;
  62440. }
  62441. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62442. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62443. var effect = _this._volumetricLightScatteringPass;
  62444. if (mesh === _this.mesh) {
  62445. if (subMesh.effect) {
  62446. effect = subMesh.effect;
  62447. }
  62448. else {
  62449. effect = material.getEffect();
  62450. }
  62451. }
  62452. engine.enableEffect(effect);
  62453. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62454. if (mesh === _this.mesh) {
  62455. material.bind(mesh.getWorldMatrix(), mesh);
  62456. }
  62457. else {
  62458. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62459. // Alpha test
  62460. if (material && material.needAlphaTesting()) {
  62461. var alphaTexture = material.getAlphaTestTexture();
  62462. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62463. if (alphaTexture) {
  62464. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62465. }
  62466. }
  62467. // Bones
  62468. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62469. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62470. }
  62471. }
  62472. // Draw
  62473. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62474. }
  62475. };
  62476. // Render target texture callbacks
  62477. var savedSceneClearColor;
  62478. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62479. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62480. savedSceneClearColor = scene.clearColor;
  62481. scene.clearColor = sceneClearColor;
  62482. });
  62483. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62484. scene.clearColor = savedSceneClearColor;
  62485. });
  62486. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62487. var engine = scene.getEngine();
  62488. var index;
  62489. if (depthOnlySubMeshes.length) {
  62490. engine.setColorWrite(false);
  62491. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62492. renderSubMesh(depthOnlySubMeshes.data[index]);
  62493. }
  62494. engine.setColorWrite(true);
  62495. }
  62496. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62497. renderSubMesh(opaqueSubMeshes.data[index]);
  62498. }
  62499. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62500. renderSubMesh(alphaTestSubMeshes.data[index]);
  62501. }
  62502. if (transparentSubMeshes.length) {
  62503. // Sort sub meshes
  62504. for (index = 0; index < transparentSubMeshes.length; index++) {
  62505. var submesh = transparentSubMeshes.data[index];
  62506. var boundingInfo = submesh.getBoundingInfo();
  62507. if (boundingInfo && scene.activeCamera) {
  62508. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62509. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62510. }
  62511. }
  62512. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62513. sortedArray.sort(function (a, b) {
  62514. // Alpha index first
  62515. if (a._alphaIndex > b._alphaIndex) {
  62516. return 1;
  62517. }
  62518. if (a._alphaIndex < b._alphaIndex) {
  62519. return -1;
  62520. }
  62521. // Then distance to camera
  62522. if (a._distanceToCamera < b._distanceToCamera) {
  62523. return 1;
  62524. }
  62525. if (a._distanceToCamera > b._distanceToCamera) {
  62526. return -1;
  62527. }
  62528. return 0;
  62529. });
  62530. // Render sub meshes
  62531. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62532. for (index = 0; index < sortedArray.length; index++) {
  62533. renderSubMesh(sortedArray[index]);
  62534. }
  62535. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62536. }
  62537. };
  62538. };
  62539. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62540. var transform = scene.getTransformMatrix();
  62541. var meshPosition;
  62542. if (this.useCustomMeshPosition) {
  62543. meshPosition = this.customMeshPosition;
  62544. }
  62545. else if (this.attachedNode) {
  62546. meshPosition = this.attachedNode.position;
  62547. }
  62548. else {
  62549. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62550. }
  62551. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62552. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62553. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62554. if (this.invert)
  62555. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62556. };
  62557. // Static methods
  62558. /**
  62559. * Creates a default mesh for the Volumeric Light Scattering post-process
  62560. * @param {string} The mesh name
  62561. * @param {BABYLON.Scene} The scene where to create the mesh
  62562. * @return {BABYLON.Mesh} the default mesh
  62563. */
  62564. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62565. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62566. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62567. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62568. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62569. mesh.material = material;
  62570. return mesh;
  62571. };
  62572. __decorate([
  62573. BABYLON.serializeAsVector3()
  62574. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62575. __decorate([
  62576. BABYLON.serialize()
  62577. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62578. __decorate([
  62579. BABYLON.serialize()
  62580. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62581. __decorate([
  62582. BABYLON.serializeAsMeshReference()
  62583. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62584. __decorate([
  62585. BABYLON.serialize()
  62586. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62587. __decorate([
  62588. BABYLON.serialize()
  62589. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62590. __decorate([
  62591. BABYLON.serialize()
  62592. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62593. __decorate([
  62594. BABYLON.serialize()
  62595. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62596. __decorate([
  62597. BABYLON.serialize()
  62598. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62599. return VolumetricLightScatteringPostProcess;
  62600. }(BABYLON.PostProcess));
  62601. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62602. })(BABYLON || (BABYLON = {}));
  62603. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62604. //
  62605. // This post-process allows the modification of rendered colors by using
  62606. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62607. //
  62608. // The object needs to be provided an url to a texture containing the color
  62609. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62610. // Use an image editing software to tweak the LUT to match your needs.
  62611. //
  62612. // For an example of a color LUT, see here:
  62613. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62614. // For explanations on color grading, see here:
  62615. // http://udn.epicgames.com/Three/ColorGrading.html
  62616. //
  62617. var BABYLON;
  62618. (function (BABYLON) {
  62619. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62620. __extends(ColorCorrectionPostProcess, _super);
  62621. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62622. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62623. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62624. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62625. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62626. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62627. _this.onApply = function (effect) {
  62628. effect.setTexture("colorTable", _this._colorTableTexture);
  62629. };
  62630. return _this;
  62631. }
  62632. return ColorCorrectionPostProcess;
  62633. }(BABYLON.PostProcess));
  62634. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62635. })(BABYLON || (BABYLON = {}));
  62636. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62637. var BABYLON;
  62638. (function (BABYLON) {
  62639. var TonemappingOperator;
  62640. (function (TonemappingOperator) {
  62641. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62642. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62643. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62644. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62645. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62646. ;
  62647. var TonemapPostProcess = /** @class */ (function (_super) {
  62648. __extends(TonemapPostProcess, _super);
  62649. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62651. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62652. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62653. _this._operator = _operator;
  62654. _this.exposureAdjustment = exposureAdjustment;
  62655. var defines = "#define ";
  62656. if (_this._operator === TonemappingOperator.Hable)
  62657. defines += "HABLE_TONEMAPPING";
  62658. else if (_this._operator === TonemappingOperator.Reinhard)
  62659. defines += "REINHARD_TONEMAPPING";
  62660. else if (_this._operator === TonemappingOperator.HejiDawson)
  62661. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62662. else if (_this._operator === TonemappingOperator.Photographic)
  62663. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62664. //sadly a second call to create the effect.
  62665. _this.updateEffect(defines);
  62666. _this.onApply = function (effect) {
  62667. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62668. };
  62669. return _this;
  62670. }
  62671. return TonemapPostProcess;
  62672. }(BABYLON.PostProcess));
  62673. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62674. })(BABYLON || (BABYLON = {}));
  62675. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62676. var BABYLON;
  62677. (function (BABYLON) {
  62678. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62679. __extends(DisplayPassPostProcess, _super);
  62680. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62681. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62682. }
  62683. return DisplayPassPostProcess;
  62684. }(BABYLON.PostProcess));
  62685. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62686. })(BABYLON || (BABYLON = {}));
  62687. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62688. var BABYLON;
  62689. (function (BABYLON) {
  62690. var HighlightsPostProcess = /** @class */ (function (_super) {
  62691. __extends(HighlightsPostProcess, _super);
  62692. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62693. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62694. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62695. }
  62696. return HighlightsPostProcess;
  62697. }(BABYLON.PostProcess));
  62698. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62699. })(BABYLON || (BABYLON = {}));
  62700. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62701. var BABYLON;
  62702. (function (BABYLON) {
  62703. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62704. __extends(ImageProcessingPostProcess, _super);
  62705. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62706. if (camera === void 0) { camera = null; }
  62707. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62708. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62709. _this._fromLinearSpace = true;
  62710. /**
  62711. * Defines cache preventing GC.
  62712. */
  62713. _this._defines = {
  62714. IMAGEPROCESSING: false,
  62715. VIGNETTE: false,
  62716. VIGNETTEBLENDMODEMULTIPLY: false,
  62717. VIGNETTEBLENDMODEOPAQUE: false,
  62718. TONEMAPPING: false,
  62719. CONTRAST: false,
  62720. COLORCURVES: false,
  62721. COLORGRADING: false,
  62722. COLORGRADING3D: false,
  62723. FROMLINEARSPACE: false,
  62724. SAMPLER3DGREENDEPTH: false,
  62725. SAMPLER3DBGRMAP: false,
  62726. IMAGEPROCESSINGPOSTPROCESS: false,
  62727. EXPOSURE: false,
  62728. };
  62729. // Setup the configuration as forced by the constructor. This would then not force the
  62730. // scene materials output in linear space and let untouched the default forward pass.
  62731. if (imageProcessingConfiguration) {
  62732. imageProcessingConfiguration.applyByPostProcess = true;
  62733. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62734. // This will cause the shader to be compiled
  62735. _this.fromLinearSpace = false;
  62736. }
  62737. else {
  62738. _this._attachImageProcessingConfiguration(null, true);
  62739. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62740. }
  62741. _this.onApply = function (effect) {
  62742. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62743. };
  62744. return _this;
  62745. }
  62746. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62747. /**
  62748. * Gets the image processing configuration used either in this material.
  62749. */
  62750. get: function () {
  62751. return this._imageProcessingConfiguration;
  62752. },
  62753. /**
  62754. * Sets the Default image processing configuration used either in the this material.
  62755. *
  62756. * If sets to null, the scene one is in use.
  62757. */
  62758. set: function (value) {
  62759. this._attachImageProcessingConfiguration(value);
  62760. },
  62761. enumerable: true,
  62762. configurable: true
  62763. });
  62764. /**
  62765. * Attaches a new image processing configuration to the PBR Material.
  62766. * @param configuration
  62767. */
  62768. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62769. var _this = this;
  62770. if (doNotBuild === void 0) { doNotBuild = false; }
  62771. if (configuration === this._imageProcessingConfiguration) {
  62772. return;
  62773. }
  62774. // Detaches observer.
  62775. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62776. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62777. }
  62778. // Pick the scene configuration if needed.
  62779. if (!configuration) {
  62780. var scene = null;
  62781. var engine = this.getEngine();
  62782. var camera = this.getCamera();
  62783. if (camera) {
  62784. scene = camera.getScene();
  62785. }
  62786. else if (engine && engine.scenes) {
  62787. var scenes = engine.scenes;
  62788. scene = scenes[scenes.length - 1];
  62789. }
  62790. else {
  62791. scene = BABYLON.Engine.LastCreatedScene;
  62792. }
  62793. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62794. }
  62795. else {
  62796. this._imageProcessingConfiguration = configuration;
  62797. }
  62798. // Attaches observer.
  62799. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62800. _this._updateParameters();
  62801. });
  62802. // Ensure the effect will be rebuilt.
  62803. if (!doNotBuild) {
  62804. this._updateParameters();
  62805. }
  62806. };
  62807. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62808. /**
  62809. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62810. */
  62811. get: function () {
  62812. return this.imageProcessingConfiguration.colorCurves;
  62813. },
  62814. /**
  62815. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62816. */
  62817. set: function (value) {
  62818. this.imageProcessingConfiguration.colorCurves = value;
  62819. },
  62820. enumerable: true,
  62821. configurable: true
  62822. });
  62823. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62824. /**
  62825. * Gets wether the color curves effect is enabled.
  62826. */
  62827. get: function () {
  62828. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62829. },
  62830. /**
  62831. * Sets wether the color curves effect is enabled.
  62832. */
  62833. set: function (value) {
  62834. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62835. },
  62836. enumerable: true,
  62837. configurable: true
  62838. });
  62839. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62840. /**
  62841. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62842. */
  62843. get: function () {
  62844. return this.imageProcessingConfiguration.colorGradingTexture;
  62845. },
  62846. /**
  62847. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62848. */
  62849. set: function (value) {
  62850. this.imageProcessingConfiguration.colorGradingTexture = value;
  62851. },
  62852. enumerable: true,
  62853. configurable: true
  62854. });
  62855. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62856. /**
  62857. * Gets wether the color grading effect is enabled.
  62858. */
  62859. get: function () {
  62860. return this.imageProcessingConfiguration.colorGradingEnabled;
  62861. },
  62862. /**
  62863. * Gets wether the color grading effect is enabled.
  62864. */
  62865. set: function (value) {
  62866. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62867. },
  62868. enumerable: true,
  62869. configurable: true
  62870. });
  62871. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62872. /**
  62873. * Gets exposure used in the effect.
  62874. */
  62875. get: function () {
  62876. return this.imageProcessingConfiguration.exposure;
  62877. },
  62878. /**
  62879. * Sets exposure used in the effect.
  62880. */
  62881. set: function (value) {
  62882. this.imageProcessingConfiguration.exposure = value;
  62883. },
  62884. enumerable: true,
  62885. configurable: true
  62886. });
  62887. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62888. /**
  62889. * Gets wether tonemapping is enabled or not.
  62890. */
  62891. get: function () {
  62892. return this._imageProcessingConfiguration.toneMappingEnabled;
  62893. },
  62894. /**
  62895. * Sets wether tonemapping is enabled or not
  62896. */
  62897. set: function (value) {
  62898. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62899. },
  62900. enumerable: true,
  62901. configurable: true
  62902. });
  62903. ;
  62904. ;
  62905. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62906. /**
  62907. * Gets contrast used in the effect.
  62908. */
  62909. get: function () {
  62910. return this.imageProcessingConfiguration.contrast;
  62911. },
  62912. /**
  62913. * Sets contrast used in the effect.
  62914. */
  62915. set: function (value) {
  62916. this.imageProcessingConfiguration.contrast = value;
  62917. },
  62918. enumerable: true,
  62919. configurable: true
  62920. });
  62921. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62922. /**
  62923. * Gets Vignette stretch size.
  62924. */
  62925. get: function () {
  62926. return this.imageProcessingConfiguration.vignetteStretch;
  62927. },
  62928. /**
  62929. * Sets Vignette stretch size.
  62930. */
  62931. set: function (value) {
  62932. this.imageProcessingConfiguration.vignetteStretch = value;
  62933. },
  62934. enumerable: true,
  62935. configurable: true
  62936. });
  62937. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62938. /**
  62939. * Gets Vignette centre X Offset.
  62940. */
  62941. get: function () {
  62942. return this.imageProcessingConfiguration.vignetteCentreX;
  62943. },
  62944. /**
  62945. * Sets Vignette centre X Offset.
  62946. */
  62947. set: function (value) {
  62948. this.imageProcessingConfiguration.vignetteCentreX = value;
  62949. },
  62950. enumerable: true,
  62951. configurable: true
  62952. });
  62953. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62954. /**
  62955. * Gets Vignette centre Y Offset.
  62956. */
  62957. get: function () {
  62958. return this.imageProcessingConfiguration.vignetteCentreY;
  62959. },
  62960. /**
  62961. * Sets Vignette centre Y Offset.
  62962. */
  62963. set: function (value) {
  62964. this.imageProcessingConfiguration.vignetteCentreY = value;
  62965. },
  62966. enumerable: true,
  62967. configurable: true
  62968. });
  62969. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62970. /**
  62971. * Gets Vignette weight or intensity of the vignette effect.
  62972. */
  62973. get: function () {
  62974. return this.imageProcessingConfiguration.vignetteWeight;
  62975. },
  62976. /**
  62977. * Sets Vignette weight or intensity of the vignette effect.
  62978. */
  62979. set: function (value) {
  62980. this.imageProcessingConfiguration.vignetteWeight = value;
  62981. },
  62982. enumerable: true,
  62983. configurable: true
  62984. });
  62985. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62986. /**
  62987. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62988. * if vignetteEnabled is set to true.
  62989. */
  62990. get: function () {
  62991. return this.imageProcessingConfiguration.vignetteColor;
  62992. },
  62993. /**
  62994. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62995. * if vignetteEnabled is set to true.
  62996. */
  62997. set: function (value) {
  62998. this.imageProcessingConfiguration.vignetteColor = value;
  62999. },
  63000. enumerable: true,
  63001. configurable: true
  63002. });
  63003. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  63004. /**
  63005. * Gets Camera field of view used by the Vignette effect.
  63006. */
  63007. get: function () {
  63008. return this.imageProcessingConfiguration.vignetteCameraFov;
  63009. },
  63010. /**
  63011. * Sets Camera field of view used by the Vignette effect.
  63012. */
  63013. set: function (value) {
  63014. this.imageProcessingConfiguration.vignetteCameraFov = value;
  63015. },
  63016. enumerable: true,
  63017. configurable: true
  63018. });
  63019. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  63020. /**
  63021. * Gets the vignette blend mode allowing different kind of effect.
  63022. */
  63023. get: function () {
  63024. return this.imageProcessingConfiguration.vignetteBlendMode;
  63025. },
  63026. /**
  63027. * Sets the vignette blend mode allowing different kind of effect.
  63028. */
  63029. set: function (value) {
  63030. this.imageProcessingConfiguration.vignetteBlendMode = value;
  63031. },
  63032. enumerable: true,
  63033. configurable: true
  63034. });
  63035. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  63036. /**
  63037. * Gets wether the vignette effect is enabled.
  63038. */
  63039. get: function () {
  63040. return this.imageProcessingConfiguration.vignetteEnabled;
  63041. },
  63042. /**
  63043. * Sets wether the vignette effect is enabled.
  63044. */
  63045. set: function (value) {
  63046. this.imageProcessingConfiguration.vignetteEnabled = value;
  63047. },
  63048. enumerable: true,
  63049. configurable: true
  63050. });
  63051. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  63052. /**
  63053. * Gets wether the input of the processing is in Gamma or Linear Space.
  63054. */
  63055. get: function () {
  63056. return this._fromLinearSpace;
  63057. },
  63058. /**
  63059. * Sets wether the input of the processing is in Gamma or Linear Space.
  63060. */
  63061. set: function (value) {
  63062. if (this._fromLinearSpace === value) {
  63063. return;
  63064. }
  63065. this._fromLinearSpace = value;
  63066. this._updateParameters();
  63067. },
  63068. enumerable: true,
  63069. configurable: true
  63070. });
  63071. ImageProcessingPostProcess.prototype.getClassName = function () {
  63072. return "ImageProcessingPostProcess";
  63073. };
  63074. ImageProcessingPostProcess.prototype._updateParameters = function () {
  63075. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  63076. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  63077. var defines = "";
  63078. for (var define in this._defines) {
  63079. if (this._defines[define]) {
  63080. defines += "#define " + define + ";\r\n";
  63081. }
  63082. }
  63083. var samplers = ["textureSampler"];
  63084. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  63085. var uniforms = ["scale"];
  63086. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  63087. this.updateEffect(defines, uniforms, samplers);
  63088. };
  63089. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  63090. _super.prototype.dispose.call(this, camera);
  63091. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  63092. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  63093. }
  63094. this.imageProcessingConfiguration.applyByPostProcess = false;
  63095. };
  63096. __decorate([
  63097. BABYLON.serialize()
  63098. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  63099. return ImageProcessingPostProcess;
  63100. }(BABYLON.PostProcess));
  63101. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  63102. })(BABYLON || (BABYLON = {}));
  63103. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  63104. var BABYLON;
  63105. (function (BABYLON) {
  63106. var BlurPostProcess = /** @class */ (function (_super) {
  63107. __extends(BlurPostProcess, _super);
  63108. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  63109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63110. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63111. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  63112. _this.direction = direction;
  63113. _this._packedFloat = false;
  63114. _this.onApplyObservable.add(function (effect) {
  63115. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  63116. });
  63117. _this.kernel = kernel;
  63118. return _this;
  63119. }
  63120. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  63121. /**
  63122. * Gets the length in pixels of the blur sample region
  63123. */
  63124. get: function () {
  63125. return this._idealKernel;
  63126. },
  63127. /**
  63128. * Sets the length in pixels of the blur sample region
  63129. */
  63130. set: function (v) {
  63131. if (this._idealKernel === v) {
  63132. return;
  63133. }
  63134. v = Math.max(v, 1);
  63135. this._idealKernel = v;
  63136. this._kernel = this._nearestBestKernel(v);
  63137. this._updateParameters();
  63138. },
  63139. enumerable: true,
  63140. configurable: true
  63141. });
  63142. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  63143. /**
  63144. * Gets wether or not the blur is unpacking/repacking floats
  63145. */
  63146. get: function () {
  63147. return this._packedFloat;
  63148. },
  63149. /**
  63150. * Sets wether or not the blur needs to unpack/repack floats
  63151. */
  63152. set: function (v) {
  63153. if (this._packedFloat === v) {
  63154. return;
  63155. }
  63156. this._packedFloat = v;
  63157. this._updateParameters();
  63158. },
  63159. enumerable: true,
  63160. configurable: true
  63161. });
  63162. BlurPostProcess.prototype._updateParameters = function () {
  63163. // Generate sampling offsets and weights
  63164. var N = this._kernel;
  63165. var centerIndex = (N - 1) / 2;
  63166. // Generate Gaussian sampling weights over kernel
  63167. var offsets = [];
  63168. var weights = [];
  63169. var totalWeight = 0;
  63170. for (var i = 0; i < N; i++) {
  63171. var u = i / (N - 1);
  63172. var w = this._gaussianWeight(u * 2.0 - 1);
  63173. offsets[i] = (i - centerIndex);
  63174. weights[i] = w;
  63175. totalWeight += w;
  63176. }
  63177. // Normalize weights
  63178. for (var i = 0; i < weights.length; i++) {
  63179. weights[i] /= totalWeight;
  63180. }
  63181. // Optimize: combine samples to take advantage of hardware linear sampling
  63182. // Walk from left to center, combining pairs (symmetrically)
  63183. var linearSamplingWeights = [];
  63184. var linearSamplingOffsets = [];
  63185. var linearSamplingMap = [];
  63186. for (var i = 0; i <= centerIndex; i += 2) {
  63187. var j = Math.min(i + 1, Math.floor(centerIndex));
  63188. var singleCenterSample = i === j;
  63189. if (singleCenterSample) {
  63190. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63191. }
  63192. else {
  63193. var sharedCell = j === centerIndex;
  63194. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63195. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63196. if (offsetLinear === 0) {
  63197. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63198. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63199. }
  63200. else {
  63201. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63202. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63203. }
  63204. }
  63205. }
  63206. for (var i = 0; i < linearSamplingMap.length; i++) {
  63207. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63208. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63209. }
  63210. // Replace with optimized
  63211. offsets = linearSamplingOffsets;
  63212. weights = linearSamplingWeights;
  63213. // Generate shaders
  63214. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63215. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63216. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63217. var defines = "";
  63218. for (var i = 0; i < varyingCount; i++) {
  63219. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63220. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63221. }
  63222. var depCount = 0;
  63223. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63224. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63225. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63226. depCount++;
  63227. }
  63228. if (this.packedFloat) {
  63229. defines += "#define PACKEDFLOAT 1";
  63230. }
  63231. this.updateEffect(defines, null, null, {
  63232. varyingCount: varyingCount,
  63233. depCount: depCount
  63234. });
  63235. };
  63236. /**
  63237. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63238. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63239. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63240. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63241. * The gaps between physical kernels are compensated for in the weighting of the samples
  63242. * @param idealKernel Ideal blur kernel.
  63243. * @return Nearest best kernel.
  63244. */
  63245. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63246. var v = Math.round(idealKernel);
  63247. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63248. var k = _a[_i];
  63249. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63250. return Math.max(k, 3);
  63251. }
  63252. }
  63253. return Math.max(v, 3);
  63254. };
  63255. /**
  63256. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63257. * @param x The point on the Gaussian distribution to sample.
  63258. * @return the value of the Gaussian function at x.
  63259. */
  63260. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63261. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63262. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63263. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63264. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63265. // truncated at around 1.3% of peak strength.
  63266. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63267. var sigma = (1 / 3);
  63268. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63269. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63270. var weight = (1.0 / denominator) * Math.exp(exponent);
  63271. return weight;
  63272. };
  63273. /**
  63274. * Generates a string that can be used as a floating point number in GLSL.
  63275. * @param x Value to print.
  63276. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63277. * @return GLSL float string.
  63278. */
  63279. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63280. if (decimalFigures === void 0) { decimalFigures = 8; }
  63281. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63282. };
  63283. return BlurPostProcess;
  63284. }(BABYLON.PostProcess));
  63285. BABYLON.BlurPostProcess = BlurPostProcess;
  63286. })(BABYLON || (BABYLON = {}));
  63287. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63288. var BABYLON;
  63289. (function (BABYLON) {
  63290. var Bone = /** @class */ (function (_super) {
  63291. __extends(Bone, _super);
  63292. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63293. if (parentBone === void 0) { parentBone = null; }
  63294. if (localMatrix === void 0) { localMatrix = null; }
  63295. if (restPose === void 0) { restPose = null; }
  63296. if (baseMatrix === void 0) { baseMatrix = null; }
  63297. if (index === void 0) { index = null; }
  63298. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63299. _this.name = name;
  63300. _this.children = new Array();
  63301. _this.animations = new Array();
  63302. // Set this value to map this bone to a different index in the transform matrices.
  63303. // Set this value to -1 to exclude the bone from the transform matrices.
  63304. _this._index = null;
  63305. _this._worldTransform = new BABYLON.Matrix();
  63306. _this._absoluteTransform = new BABYLON.Matrix();
  63307. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63308. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63309. _this._scaleVector = BABYLON.Vector3.One();
  63310. _this._negateScaleChildren = BABYLON.Vector3.One();
  63311. _this._scalingDeterminant = 1;
  63312. _this._skeleton = skeleton;
  63313. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63314. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63315. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63316. _this._index = index;
  63317. skeleton.bones.push(_this);
  63318. _this.setParent(parentBone, false);
  63319. _this._updateDifferenceMatrix();
  63320. return _this;
  63321. }
  63322. Object.defineProperty(Bone.prototype, "_matrix", {
  63323. get: function () {
  63324. return this._localMatrix;
  63325. },
  63326. set: function (val) {
  63327. if (this._localMatrix) {
  63328. this._localMatrix.copyFrom(val);
  63329. }
  63330. else {
  63331. this._localMatrix = val;
  63332. }
  63333. },
  63334. enumerable: true,
  63335. configurable: true
  63336. });
  63337. // Members
  63338. Bone.prototype.getSkeleton = function () {
  63339. return this._skeleton;
  63340. };
  63341. Bone.prototype.getParent = function () {
  63342. return this._parent;
  63343. };
  63344. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63345. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63346. if (this._parent === parent) {
  63347. return;
  63348. }
  63349. if (this._parent) {
  63350. var index = this._parent.children.indexOf(this);
  63351. if (index !== -1) {
  63352. this._parent.children.splice(index, 1);
  63353. }
  63354. }
  63355. this._parent = parent;
  63356. if (this._parent) {
  63357. this._parent.children.push(this);
  63358. }
  63359. if (updateDifferenceMatrix) {
  63360. this._updateDifferenceMatrix();
  63361. }
  63362. };
  63363. Bone.prototype.getLocalMatrix = function () {
  63364. return this._localMatrix;
  63365. };
  63366. Bone.prototype.getBaseMatrix = function () {
  63367. return this._baseMatrix;
  63368. };
  63369. Bone.prototype.getRestPose = function () {
  63370. return this._restPose;
  63371. };
  63372. Bone.prototype.returnToRest = function () {
  63373. this.updateMatrix(this._restPose.clone());
  63374. };
  63375. Bone.prototype.getWorldMatrix = function () {
  63376. return this._worldTransform;
  63377. };
  63378. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63379. return this._invertedAbsoluteTransform;
  63380. };
  63381. Bone.prototype.getAbsoluteTransform = function () {
  63382. return this._absoluteTransform;
  63383. };
  63384. Object.defineProperty(Bone.prototype, "position", {
  63385. // Properties (matches AbstractMesh properties)
  63386. get: function () {
  63387. return this.getPosition();
  63388. },
  63389. set: function (newPosition) {
  63390. this.setPosition(newPosition);
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(Bone.prototype, "rotation", {
  63396. get: function () {
  63397. return this.getRotation();
  63398. },
  63399. set: function (newRotation) {
  63400. this.setRotation(newRotation);
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63406. get: function () {
  63407. return this.getRotationQuaternion();
  63408. },
  63409. set: function (newRotation) {
  63410. this.setRotationQuaternion(newRotation);
  63411. },
  63412. enumerable: true,
  63413. configurable: true
  63414. });
  63415. Object.defineProperty(Bone.prototype, "scaling", {
  63416. get: function () {
  63417. return this.getScale();
  63418. },
  63419. set: function (newScaling) {
  63420. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63421. },
  63422. enumerable: true,
  63423. configurable: true
  63424. });
  63425. // Methods
  63426. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63427. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63428. this._baseMatrix = matrix.clone();
  63429. this._localMatrix = matrix.clone();
  63430. this._skeleton._markAsDirty();
  63431. if (updateDifferenceMatrix) {
  63432. this._updateDifferenceMatrix();
  63433. }
  63434. };
  63435. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63436. if (!rootMatrix) {
  63437. rootMatrix = this._baseMatrix;
  63438. }
  63439. if (this._parent) {
  63440. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63441. }
  63442. else {
  63443. this._absoluteTransform.copyFrom(rootMatrix);
  63444. }
  63445. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63446. for (var index = 0; index < this.children.length; index++) {
  63447. this.children[index]._updateDifferenceMatrix();
  63448. }
  63449. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63450. };
  63451. Bone.prototype.markAsDirty = function () {
  63452. this._currentRenderId++;
  63453. this._skeleton._markAsDirty();
  63454. };
  63455. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63456. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63457. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63458. // all animation may be coming from a library skeleton, so may need to create animation
  63459. if (this.animations.length === 0) {
  63460. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63461. this.animations[0].setKeys([]);
  63462. }
  63463. // get animation info / verify there is such a range from the source bone
  63464. var sourceRange = source.animations[0].getRange(rangeName);
  63465. if (!sourceRange) {
  63466. return false;
  63467. }
  63468. var from = sourceRange.from;
  63469. var to = sourceRange.to;
  63470. var sourceKeys = source.animations[0].getKeys();
  63471. // rescaling prep
  63472. var sourceBoneLength = source.length;
  63473. var sourceParent = source.getParent();
  63474. var parent = this.getParent();
  63475. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63476. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63477. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63478. var destKeys = this.animations[0].getKeys();
  63479. // loop vars declaration
  63480. var orig;
  63481. var origTranslation;
  63482. var mat;
  63483. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63484. orig = sourceKeys[key];
  63485. if (orig.frame >= from && orig.frame <= to) {
  63486. if (rescaleAsRequired) {
  63487. mat = orig.value.clone();
  63488. // scale based on parent ratio, when bone has parent
  63489. if (parentScalingReqd) {
  63490. origTranslation = mat.getTranslation();
  63491. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63492. // scale based on skeleton dimension ratio when root bone, and value is passed
  63493. }
  63494. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63495. origTranslation = mat.getTranslation();
  63496. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63497. // use original when root bone, and no data for skelDimensionsRatio
  63498. }
  63499. else {
  63500. mat = orig.value;
  63501. }
  63502. }
  63503. else {
  63504. mat = orig.value;
  63505. }
  63506. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63507. }
  63508. }
  63509. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63510. return true;
  63511. };
  63512. /**
  63513. * Translate the bone in local or world space.
  63514. * @param vec The amount to translate the bone.
  63515. * @param space The space that the translation is in.
  63516. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63517. */
  63518. Bone.prototype.translate = function (vec, space, mesh) {
  63519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63520. var lm = this.getLocalMatrix();
  63521. if (space == BABYLON.Space.LOCAL) {
  63522. lm.m[12] += vec.x;
  63523. lm.m[13] += vec.y;
  63524. lm.m[14] += vec.z;
  63525. }
  63526. else {
  63527. var wm = null;
  63528. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63529. if (mesh) {
  63530. wm = mesh.getWorldMatrix();
  63531. }
  63532. this._skeleton.computeAbsoluteTransforms();
  63533. var tmat = Bone._tmpMats[0];
  63534. var tvec = Bone._tmpVecs[0];
  63535. if (this._parent) {
  63536. if (mesh && wm) {
  63537. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63538. tmat.multiplyToRef(wm, tmat);
  63539. }
  63540. else {
  63541. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63542. }
  63543. }
  63544. tmat.m[12] = 0;
  63545. tmat.m[13] = 0;
  63546. tmat.m[14] = 0;
  63547. tmat.invert();
  63548. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63549. lm.m[12] += tvec.x;
  63550. lm.m[13] += tvec.y;
  63551. lm.m[14] += tvec.z;
  63552. }
  63553. this.markAsDirty();
  63554. };
  63555. /**
  63556. * Set the postion of the bone in local or world space.
  63557. * @param position The position to set the bone.
  63558. * @param space The space that the position is in.
  63559. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63560. */
  63561. Bone.prototype.setPosition = function (position, space, mesh) {
  63562. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63563. var lm = this.getLocalMatrix();
  63564. if (space == BABYLON.Space.LOCAL) {
  63565. lm.m[12] = position.x;
  63566. lm.m[13] = position.y;
  63567. lm.m[14] = position.z;
  63568. }
  63569. else {
  63570. var wm = null;
  63571. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63572. if (mesh) {
  63573. wm = mesh.getWorldMatrix();
  63574. }
  63575. this._skeleton.computeAbsoluteTransforms();
  63576. var tmat = Bone._tmpMats[0];
  63577. var vec = Bone._tmpVecs[0];
  63578. if (this._parent) {
  63579. if (mesh && wm) {
  63580. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63581. tmat.multiplyToRef(wm, tmat);
  63582. }
  63583. else {
  63584. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63585. }
  63586. }
  63587. tmat.invert();
  63588. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63589. lm.m[12] = vec.x;
  63590. lm.m[13] = vec.y;
  63591. lm.m[14] = vec.z;
  63592. }
  63593. this.markAsDirty();
  63594. };
  63595. /**
  63596. * Set the absolute postion of the bone (world space).
  63597. * @param position The position to set the bone.
  63598. * @param mesh The mesh that this bone is attached to.
  63599. */
  63600. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63601. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63602. };
  63603. /**
  63604. * Set the scale of the bone on the x, y and z axes.
  63605. * @param x The scale of the bone on the x axis.
  63606. * @param x The scale of the bone on the y axis.
  63607. * @param z The scale of the bone on the z axis.
  63608. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63609. */
  63610. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63611. if (scaleChildren === void 0) { scaleChildren = false; }
  63612. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63613. if (!scaleChildren) {
  63614. this._negateScaleChildren.x = 1 / x;
  63615. this._negateScaleChildren.y = 1 / y;
  63616. this._negateScaleChildren.z = 1 / z;
  63617. }
  63618. this._syncScaleVector();
  63619. }
  63620. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63621. };
  63622. /**
  63623. * Scale the bone on the x, y and z axes.
  63624. * @param x The amount to scale the bone on the x axis.
  63625. * @param x The amount to scale the bone on the y axis.
  63626. * @param z The amount to scale the bone on the z axis.
  63627. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63628. */
  63629. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63630. if (scaleChildren === void 0) { scaleChildren = false; }
  63631. var locMat = this.getLocalMatrix();
  63632. var origLocMat = Bone._tmpMats[0];
  63633. origLocMat.copyFrom(locMat);
  63634. var origLocMatInv = Bone._tmpMats[1];
  63635. origLocMatInv.copyFrom(origLocMat);
  63636. origLocMatInv.invert();
  63637. var scaleMat = Bone._tmpMats[2];
  63638. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63639. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63640. this._scaleVector.x *= x;
  63641. this._scaleVector.y *= y;
  63642. this._scaleVector.z *= z;
  63643. locMat.multiplyToRef(origLocMatInv, locMat);
  63644. locMat.multiplyToRef(scaleMat, locMat);
  63645. locMat.multiplyToRef(origLocMat, locMat);
  63646. var parent = this.getParent();
  63647. if (parent) {
  63648. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63649. }
  63650. else {
  63651. this.getAbsoluteTransform().copyFrom(locMat);
  63652. }
  63653. var len = this.children.length;
  63654. scaleMat.invert();
  63655. for (var i = 0; i < len; i++) {
  63656. var child = this.children[i];
  63657. var cm = child.getLocalMatrix();
  63658. cm.multiplyToRef(scaleMat, cm);
  63659. var lm = child.getLocalMatrix();
  63660. lm.m[12] *= x;
  63661. lm.m[13] *= y;
  63662. lm.m[14] *= z;
  63663. }
  63664. this.computeAbsoluteTransforms();
  63665. if (scaleChildren) {
  63666. for (var i = 0; i < len; i++) {
  63667. this.children[i].scale(x, y, z, scaleChildren);
  63668. }
  63669. }
  63670. this.markAsDirty();
  63671. };
  63672. /**
  63673. * Set the yaw, pitch, and roll of the bone in local or world space.
  63674. * @param yaw The rotation of the bone on the y axis.
  63675. * @param pitch The rotation of the bone on the x axis.
  63676. * @param roll The rotation of the bone on the z axis.
  63677. * @param space The space that the axes of rotation are in.
  63678. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63679. */
  63680. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63682. var rotMat = Bone._tmpMats[0];
  63683. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63684. var rotMatInv = Bone._tmpMats[1];
  63685. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63686. rotMatInv.multiplyToRef(rotMat, rotMat);
  63687. this._rotateWithMatrix(rotMat, space, mesh);
  63688. };
  63689. /**
  63690. * Rotate the bone on an axis in local or world space.
  63691. * @param axis The axis to rotate the bone on.
  63692. * @param amount The amount to rotate the bone.
  63693. * @param space The space that the axis is in.
  63694. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63695. */
  63696. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63698. var rmat = Bone._tmpMats[0];
  63699. rmat.m[12] = 0;
  63700. rmat.m[13] = 0;
  63701. rmat.m[14] = 0;
  63702. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63703. this._rotateWithMatrix(rmat, space, mesh);
  63704. };
  63705. /**
  63706. * Set the rotation of the bone to a particular axis angle in local or world space.
  63707. * @param axis The axis to rotate the bone on.
  63708. * @param angle The angle that the bone should be rotated to.
  63709. * @param space The space that the axis is in.
  63710. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63711. */
  63712. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63713. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63714. var rotMat = Bone._tmpMats[0];
  63715. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63716. var rotMatInv = Bone._tmpMats[1];
  63717. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63718. rotMatInv.multiplyToRef(rotMat, rotMat);
  63719. this._rotateWithMatrix(rotMat, space, mesh);
  63720. };
  63721. /**
  63722. * Set the euler rotation of the bone in local of world space.
  63723. * @param rotation The euler rotation that the bone should be set to.
  63724. * @param space The space that the rotation is in.
  63725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63726. */
  63727. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63729. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63730. };
  63731. /**
  63732. * Set the quaternion rotation of the bone in local of world space.
  63733. * @param quat The quaternion rotation that the bone should be set to.
  63734. * @param space The space that the rotation is in.
  63735. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63736. */
  63737. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63739. var rotMatInv = Bone._tmpMats[0];
  63740. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63741. var rotMat = Bone._tmpMats[1];
  63742. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63743. rotMatInv.multiplyToRef(rotMat, rotMat);
  63744. this._rotateWithMatrix(rotMat, space, mesh);
  63745. };
  63746. /**
  63747. * Set the rotation matrix of the bone in local of world space.
  63748. * @param rotMat The rotation matrix that the bone should be set to.
  63749. * @param space The space that the rotation is in.
  63750. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63751. */
  63752. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63753. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63754. var rotMatInv = Bone._tmpMats[0];
  63755. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63756. var rotMat2 = Bone._tmpMats[1];
  63757. rotMat2.copyFrom(rotMat);
  63758. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63759. this._rotateWithMatrix(rotMat2, space, mesh);
  63760. };
  63761. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63762. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63763. var lmat = this.getLocalMatrix();
  63764. var lx = lmat.m[12];
  63765. var ly = lmat.m[13];
  63766. var lz = lmat.m[14];
  63767. var parent = this.getParent();
  63768. var parentScale = Bone._tmpMats[3];
  63769. var parentScaleInv = Bone._tmpMats[4];
  63770. if (parent) {
  63771. if (space == BABYLON.Space.WORLD) {
  63772. if (mesh) {
  63773. parentScale.copyFrom(mesh.getWorldMatrix());
  63774. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63775. }
  63776. else {
  63777. parentScale.copyFrom(parent.getAbsoluteTransform());
  63778. }
  63779. }
  63780. else {
  63781. parentScale = parent._scaleMatrix;
  63782. }
  63783. parentScaleInv.copyFrom(parentScale);
  63784. parentScaleInv.invert();
  63785. lmat.multiplyToRef(parentScale, lmat);
  63786. lmat.multiplyToRef(rmat, lmat);
  63787. lmat.multiplyToRef(parentScaleInv, lmat);
  63788. }
  63789. else {
  63790. if (space == BABYLON.Space.WORLD && mesh) {
  63791. parentScale.copyFrom(mesh.getWorldMatrix());
  63792. parentScaleInv.copyFrom(parentScale);
  63793. parentScaleInv.invert();
  63794. lmat.multiplyToRef(parentScale, lmat);
  63795. lmat.multiplyToRef(rmat, lmat);
  63796. lmat.multiplyToRef(parentScaleInv, lmat);
  63797. }
  63798. else {
  63799. lmat.multiplyToRef(rmat, lmat);
  63800. }
  63801. }
  63802. lmat.m[12] = lx;
  63803. lmat.m[13] = ly;
  63804. lmat.m[14] = lz;
  63805. this.computeAbsoluteTransforms();
  63806. this.markAsDirty();
  63807. };
  63808. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63810. if (space == BABYLON.Space.WORLD) {
  63811. var scaleMatrix = Bone._tmpMats[2];
  63812. scaleMatrix.copyFrom(this._scaleMatrix);
  63813. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63814. if (mesh) {
  63815. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63816. var meshScale = Bone._tmpMats[3];
  63817. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63818. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63819. }
  63820. rotMatInv.invert();
  63821. scaleMatrix.m[0] *= this._scalingDeterminant;
  63822. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63823. }
  63824. else {
  63825. rotMatInv.copyFrom(this.getLocalMatrix());
  63826. rotMatInv.invert();
  63827. var scaleMatrix = Bone._tmpMats[2];
  63828. scaleMatrix.copyFrom(this._scaleMatrix);
  63829. if (this._parent) {
  63830. var pscaleMatrix = Bone._tmpMats[3];
  63831. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63832. pscaleMatrix.invert();
  63833. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63834. }
  63835. else {
  63836. scaleMatrix.m[0] *= this._scalingDeterminant;
  63837. }
  63838. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63839. }
  63840. };
  63841. /**
  63842. * Get the scale of the bone
  63843. * @returns the scale of the bone
  63844. */
  63845. Bone.prototype.getScale = function () {
  63846. return this._scaleVector.clone();
  63847. };
  63848. /**
  63849. * Copy the scale of the bone to a vector3.
  63850. * @param result The vector3 to copy the scale to
  63851. */
  63852. Bone.prototype.getScaleToRef = function (result) {
  63853. result.copyFrom(this._scaleVector);
  63854. };
  63855. /**
  63856. * Get the position of the bone in local or world space.
  63857. * @param space The space that the returned position is in.
  63858. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63859. * @returns The position of the bone
  63860. */
  63861. Bone.prototype.getPosition = function (space, mesh) {
  63862. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63863. if (mesh === void 0) { mesh = null; }
  63864. var pos = BABYLON.Vector3.Zero();
  63865. this.getPositionToRef(space, mesh, pos);
  63866. return pos;
  63867. };
  63868. /**
  63869. * Copy the position of the bone to a vector3 in local or world space.
  63870. * @param space The space that the returned position is in.
  63871. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63872. * @param result The vector3 to copy the position to.
  63873. */
  63874. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63876. if (space == BABYLON.Space.LOCAL) {
  63877. var lm = this.getLocalMatrix();
  63878. result.x = lm.m[12];
  63879. result.y = lm.m[13];
  63880. result.z = lm.m[14];
  63881. }
  63882. else {
  63883. var wm = null;
  63884. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63885. if (mesh) {
  63886. wm = mesh.getWorldMatrix();
  63887. }
  63888. this._skeleton.computeAbsoluteTransforms();
  63889. var tmat = Bone._tmpMats[0];
  63890. if (mesh && wm) {
  63891. tmat.copyFrom(this.getAbsoluteTransform());
  63892. tmat.multiplyToRef(wm, tmat);
  63893. }
  63894. else {
  63895. tmat = this.getAbsoluteTransform();
  63896. }
  63897. result.x = tmat.m[12];
  63898. result.y = tmat.m[13];
  63899. result.z = tmat.m[14];
  63900. }
  63901. };
  63902. /**
  63903. * Get the absolute position of the bone (world space).
  63904. * @param mesh The mesh that this bone is attached to.
  63905. * @returns The absolute position of the bone
  63906. */
  63907. Bone.prototype.getAbsolutePosition = function (mesh) {
  63908. if (mesh === void 0) { mesh = null; }
  63909. var pos = BABYLON.Vector3.Zero();
  63910. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63911. return pos;
  63912. };
  63913. /**
  63914. * Copy the absolute position of the bone (world space) to the result param.
  63915. * @param mesh The mesh that this bone is attached to.
  63916. * @param result The vector3 to copy the absolute position to.
  63917. */
  63918. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63919. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63920. };
  63921. /**
  63922. * Compute the absolute transforms of this bone and its children.
  63923. */
  63924. Bone.prototype.computeAbsoluteTransforms = function () {
  63925. if (this._parent) {
  63926. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63927. }
  63928. else {
  63929. this._absoluteTransform.copyFrom(this._localMatrix);
  63930. var poseMatrix = this._skeleton.getPoseMatrix();
  63931. if (poseMatrix) {
  63932. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63933. }
  63934. }
  63935. var children = this.children;
  63936. var len = children.length;
  63937. for (var i = 0; i < len; i++) {
  63938. children[i].computeAbsoluteTransforms();
  63939. }
  63940. };
  63941. Bone.prototype._syncScaleVector = function () {
  63942. var lm = this.getLocalMatrix();
  63943. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63944. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63945. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63946. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63947. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63948. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63949. this._scaleVector.x = xs * Math.sqrt(xsq);
  63950. this._scaleVector.y = ys * Math.sqrt(ysq);
  63951. this._scaleVector.z = zs * Math.sqrt(zsq);
  63952. if (this._parent) {
  63953. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63954. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63955. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63956. }
  63957. 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);
  63958. };
  63959. /**
  63960. * Get the world direction from an axis that is in the local space of the bone.
  63961. * @param localAxis The local direction that is used to compute the world direction.
  63962. * @param mesh The mesh that this bone is attached to.
  63963. * @returns The world direction
  63964. */
  63965. Bone.prototype.getDirection = function (localAxis, mesh) {
  63966. if (mesh === void 0) { mesh = null; }
  63967. var result = BABYLON.Vector3.Zero();
  63968. this.getDirectionToRef(localAxis, mesh, result);
  63969. return result;
  63970. };
  63971. /**
  63972. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63973. * @param localAxis The local direction that is used to compute the world direction.
  63974. * @param mesh The mesh that this bone is attached to.
  63975. * @param result The vector3 that the world direction will be copied to.
  63976. */
  63977. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63978. if (mesh === void 0) { mesh = null; }
  63979. var wm = null;
  63980. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63981. if (mesh) {
  63982. wm = mesh.getWorldMatrix();
  63983. }
  63984. this._skeleton.computeAbsoluteTransforms();
  63985. var mat = Bone._tmpMats[0];
  63986. mat.copyFrom(this.getAbsoluteTransform());
  63987. if (mesh && wm) {
  63988. mat.multiplyToRef(wm, mat);
  63989. }
  63990. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63991. result.normalize();
  63992. };
  63993. /**
  63994. * Get the euler rotation of the bone in local or world space.
  63995. * @param space The space that the rotation should be in.
  63996. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63997. * @returns The euler rotation
  63998. */
  63999. Bone.prototype.getRotation = function (space, mesh) {
  64000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64001. if (mesh === void 0) { mesh = null; }
  64002. var result = BABYLON.Vector3.Zero();
  64003. this.getRotationToRef(space, mesh, result);
  64004. return result;
  64005. };
  64006. /**
  64007. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  64008. * @param space The space that the rotation should be in.
  64009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64010. * @param result The vector3 that the rotation should be copied to.
  64011. */
  64012. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  64013. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64014. if (mesh === void 0) { mesh = null; }
  64015. var quat = Bone._tmpQuat;
  64016. this.getRotationQuaternionToRef(space, mesh, quat);
  64017. quat.toEulerAnglesToRef(result);
  64018. };
  64019. /**
  64020. * Get the quaternion rotation of the bone in either local or world space.
  64021. * @param space The space that the rotation should be in.
  64022. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64023. * @returns The quaternion rotation
  64024. */
  64025. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  64026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64027. if (mesh === void 0) { mesh = null; }
  64028. var result = BABYLON.Quaternion.Identity();
  64029. this.getRotationQuaternionToRef(space, mesh, result);
  64030. return result;
  64031. };
  64032. /**
  64033. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  64034. * @param space The space that the rotation should be in.
  64035. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64036. * @param result The quaternion that the rotation should be copied to.
  64037. */
  64038. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  64039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64040. if (mesh === void 0) { mesh = null; }
  64041. if (space == BABYLON.Space.LOCAL) {
  64042. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  64043. }
  64044. else {
  64045. var mat = Bone._tmpMats[0];
  64046. var amat = this.getAbsoluteTransform();
  64047. if (mesh) {
  64048. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  64049. }
  64050. else {
  64051. mat.copyFrom(amat);
  64052. }
  64053. mat.m[0] *= this._scalingDeterminant;
  64054. mat.m[1] *= this._scalingDeterminant;
  64055. mat.m[2] *= this._scalingDeterminant;
  64056. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  64057. }
  64058. };
  64059. /**
  64060. * Get the rotation matrix of the bone in local or world space.
  64061. * @param space The space that the rotation should be in.
  64062. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64063. * @returns The rotation matrix
  64064. */
  64065. Bone.prototype.getRotationMatrix = function (space, mesh) {
  64066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64067. var result = BABYLON.Matrix.Identity();
  64068. this.getRotationMatrixToRef(space, mesh, result);
  64069. return result;
  64070. };
  64071. /**
  64072. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  64073. * @param space The space that the rotation should be in.
  64074. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  64075. * @param result The quaternion that the rotation should be copied to.
  64076. */
  64077. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  64078. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  64079. if (space == BABYLON.Space.LOCAL) {
  64080. this.getLocalMatrix().getRotationMatrixToRef(result);
  64081. }
  64082. else {
  64083. var mat = Bone._tmpMats[0];
  64084. var amat = this.getAbsoluteTransform();
  64085. if (mesh) {
  64086. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  64087. }
  64088. else {
  64089. mat.copyFrom(amat);
  64090. }
  64091. mat.m[0] *= this._scalingDeterminant;
  64092. mat.m[1] *= this._scalingDeterminant;
  64093. mat.m[2] *= this._scalingDeterminant;
  64094. mat.getRotationMatrixToRef(result);
  64095. }
  64096. };
  64097. /**
  64098. * Get the world position of a point that is in the local space of the bone.
  64099. * @param position The local position
  64100. * @param mesh The mesh that this bone is attached to.
  64101. * @returns The world position
  64102. */
  64103. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  64104. if (mesh === void 0) { mesh = null; }
  64105. var result = BABYLON.Vector3.Zero();
  64106. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  64107. return result;
  64108. };
  64109. /**
  64110. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  64111. * @param position The local position
  64112. * @param mesh The mesh that this bone is attached to.
  64113. * @param result The vector3 that the world position should be copied to.
  64114. */
  64115. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  64116. if (mesh === void 0) { mesh = null; }
  64117. var wm = null;
  64118. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64119. if (mesh) {
  64120. wm = mesh.getWorldMatrix();
  64121. }
  64122. this._skeleton.computeAbsoluteTransforms();
  64123. var tmat = Bone._tmpMats[0];
  64124. if (mesh && wm) {
  64125. tmat.copyFrom(this.getAbsoluteTransform());
  64126. tmat.multiplyToRef(wm, tmat);
  64127. }
  64128. else {
  64129. tmat = this.getAbsoluteTransform();
  64130. }
  64131. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64132. };
  64133. /**
  64134. * Get the local position of a point that is in world space.
  64135. * @param position The world position
  64136. * @param mesh The mesh that this bone is attached to.
  64137. * @returns The local position
  64138. */
  64139. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  64140. if (mesh === void 0) { mesh = null; }
  64141. var result = BABYLON.Vector3.Zero();
  64142. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  64143. return result;
  64144. };
  64145. /**
  64146. * Get the local position of a point that is in world space and copy it to the result param.
  64147. * @param position The world position
  64148. * @param mesh The mesh that this bone is attached to.
  64149. * @param result The vector3 that the local position should be copied to.
  64150. */
  64151. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64152. if (mesh === void 0) { mesh = null; }
  64153. var wm = null;
  64154. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64155. if (mesh) {
  64156. wm = mesh.getWorldMatrix();
  64157. }
  64158. this._skeleton.computeAbsoluteTransforms();
  64159. var tmat = Bone._tmpMats[0];
  64160. tmat.copyFrom(this.getAbsoluteTransform());
  64161. if (mesh && wm) {
  64162. tmat.multiplyToRef(wm, tmat);
  64163. }
  64164. tmat.invert();
  64165. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64166. };
  64167. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64168. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64169. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64170. return Bone;
  64171. }(BABYLON.Node));
  64172. BABYLON.Bone = Bone;
  64173. })(BABYLON || (BABYLON = {}));
  64174. //# sourceMappingURL=babylon.bone.js.map
  64175. var BABYLON;
  64176. (function (BABYLON) {
  64177. var BoneIKController = /** @class */ (function () {
  64178. function BoneIKController(mesh, bone, options) {
  64179. this.targetPosition = BABYLON.Vector3.Zero();
  64180. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64181. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64182. this.poleAngle = 0;
  64183. this.slerpAmount = 1;
  64184. this._bone1Quat = BABYLON.Quaternion.Identity();
  64185. this._bone1Mat = BABYLON.Matrix.Identity();
  64186. this._bone2Ang = Math.PI;
  64187. this._maxAngle = Math.PI;
  64188. this._rightHandedSystem = false;
  64189. this._bendAxis = BABYLON.Vector3.Right();
  64190. this._slerping = false;
  64191. this._adjustRoll = 0;
  64192. this._bone2 = bone;
  64193. this._bone1 = bone.getParent();
  64194. if (!this._bone1) {
  64195. return;
  64196. }
  64197. this.mesh = mesh;
  64198. var bonePos = bone.getPosition();
  64199. if (bone.getAbsoluteTransform().determinant() > 0) {
  64200. this._rightHandedSystem = true;
  64201. this._bendAxis.x = 0;
  64202. this._bendAxis.y = 0;
  64203. this._bendAxis.z = -1;
  64204. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64205. this._adjustRoll = Math.PI * .5;
  64206. this._bendAxis.z = 1;
  64207. }
  64208. }
  64209. if (this._bone1.length) {
  64210. var boneScale1 = this._bone1.getScale();
  64211. var boneScale2 = this._bone2.getScale();
  64212. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64213. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64214. }
  64215. else if (this._bone1.children[0]) {
  64216. mesh.computeWorldMatrix(true);
  64217. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64218. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64219. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64220. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64221. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64222. }
  64223. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64224. this.maxAngle = Math.PI;
  64225. if (options) {
  64226. if (options.targetMesh) {
  64227. this.targetMesh = options.targetMesh;
  64228. this.targetMesh.computeWorldMatrix(true);
  64229. }
  64230. if (options.poleTargetMesh) {
  64231. this.poleTargetMesh = options.poleTargetMesh;
  64232. this.poleTargetMesh.computeWorldMatrix(true);
  64233. }
  64234. else if (options.poleTargetBone) {
  64235. this.poleTargetBone = options.poleTargetBone;
  64236. }
  64237. else if (this._bone1.getParent()) {
  64238. this.poleTargetBone = this._bone1.getParent();
  64239. }
  64240. if (options.poleTargetLocalOffset) {
  64241. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64242. }
  64243. if (options.poleAngle) {
  64244. this.poleAngle = options.poleAngle;
  64245. }
  64246. if (options.bendAxis) {
  64247. this._bendAxis.copyFrom(options.bendAxis);
  64248. }
  64249. if (options.maxAngle) {
  64250. this.maxAngle = options.maxAngle;
  64251. }
  64252. if (options.slerpAmount) {
  64253. this.slerpAmount = options.slerpAmount;
  64254. }
  64255. }
  64256. }
  64257. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64258. get: function () {
  64259. return this._maxAngle;
  64260. },
  64261. set: function (value) {
  64262. this._setMaxAngle(value);
  64263. },
  64264. enumerable: true,
  64265. configurable: true
  64266. });
  64267. BoneIKController.prototype._setMaxAngle = function (ang) {
  64268. if (ang < 0) {
  64269. ang = 0;
  64270. }
  64271. if (ang > Math.PI || ang == undefined) {
  64272. ang = Math.PI;
  64273. }
  64274. this._maxAngle = ang;
  64275. var a = this._bone1Length;
  64276. var b = this._bone2Length;
  64277. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64278. };
  64279. BoneIKController.prototype.update = function () {
  64280. var bone1 = this._bone1;
  64281. if (!bone1) {
  64282. return;
  64283. }
  64284. var target = this.targetPosition;
  64285. var poleTarget = this.poleTargetPosition;
  64286. var mat1 = BoneIKController._tmpMats[0];
  64287. var mat2 = BoneIKController._tmpMats[1];
  64288. if (this.targetMesh) {
  64289. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64290. }
  64291. if (this.poleTargetBone) {
  64292. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64293. }
  64294. else if (this.poleTargetMesh) {
  64295. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64296. }
  64297. var bonePos = BoneIKController._tmpVecs[0];
  64298. var zaxis = BoneIKController._tmpVecs[1];
  64299. var xaxis = BoneIKController._tmpVecs[2];
  64300. var yaxis = BoneIKController._tmpVecs[3];
  64301. var upAxis = BoneIKController._tmpVecs[4];
  64302. var _tmpQuat = BoneIKController._tmpQuat;
  64303. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64304. poleTarget.subtractToRef(bonePos, upAxis);
  64305. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64306. upAxis.y = 1;
  64307. }
  64308. else {
  64309. upAxis.normalize();
  64310. }
  64311. target.subtractToRef(bonePos, yaxis);
  64312. yaxis.normalize();
  64313. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64314. zaxis.normalize();
  64315. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64316. xaxis.normalize();
  64317. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64318. var a = this._bone1Length;
  64319. var b = this._bone2Length;
  64320. var c = BABYLON.Vector3.Distance(bonePos, target);
  64321. if (this._maxReach > 0) {
  64322. c = Math.min(this._maxReach, c);
  64323. }
  64324. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64325. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64326. if (acosa > 1) {
  64327. acosa = 1;
  64328. }
  64329. if (acosb > 1) {
  64330. acosb = 1;
  64331. }
  64332. if (acosa < -1) {
  64333. acosa = -1;
  64334. }
  64335. if (acosb < -1) {
  64336. acosb = -1;
  64337. }
  64338. var angA = Math.acos(acosa);
  64339. var angB = Math.acos(acosb);
  64340. var angC = -angA - angB;
  64341. if (this._rightHandedSystem) {
  64342. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64343. mat2.multiplyToRef(mat1, mat1);
  64344. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64345. mat2.multiplyToRef(mat1, mat1);
  64346. }
  64347. else {
  64348. var _tmpVec = BoneIKController._tmpVecs[5];
  64349. _tmpVec.copyFrom(this._bendAxis);
  64350. _tmpVec.x *= -1;
  64351. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64352. mat2.multiplyToRef(mat1, mat1);
  64353. }
  64354. if (this.poleAngle) {
  64355. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64356. mat1.multiplyToRef(mat2, mat1);
  64357. }
  64358. if (this._bone1) {
  64359. if (this.slerpAmount < 1) {
  64360. if (!this._slerping) {
  64361. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64362. }
  64363. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64364. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64365. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64366. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64367. this._slerping = true;
  64368. }
  64369. else {
  64370. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64371. this._bone1Mat.copyFrom(mat1);
  64372. this._slerping = false;
  64373. }
  64374. }
  64375. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64376. this._bone2Ang = angC;
  64377. };
  64378. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64379. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64380. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64381. return BoneIKController;
  64382. }());
  64383. BABYLON.BoneIKController = BoneIKController;
  64384. })(BABYLON || (BABYLON = {}));
  64385. //# sourceMappingURL=babylon.boneIKController.js.map
  64386. var BABYLON;
  64387. (function (BABYLON) {
  64388. var BoneLookController = /** @class */ (function () {
  64389. /**
  64390. * Create a BoneLookController
  64391. * @param mesh the mesh that the bone belongs to
  64392. * @param bone the bone that will be looking to the target
  64393. * @param target the target Vector3 to look at
  64394. * @param settings optional settings:
  64395. * - maxYaw: the maximum angle the bone will yaw to
  64396. * - minYaw: the minimum angle the bone will yaw to
  64397. * - maxPitch: the maximum angle the bone will pitch to
  64398. * - minPitch: the minimum angle the bone will yaw to
  64399. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64400. * - upAxis: the up axis of the coordinate system
  64401. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64402. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64403. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64404. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64405. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64406. * - adjustRoll: used to make an adjustment to the roll of the bone
  64407. **/
  64408. function BoneLookController(mesh, bone, target, options) {
  64409. /**
  64410. * The up axis of the coordinate system that is used when the bone is rotated.
  64411. */
  64412. this.upAxis = BABYLON.Vector3.Up();
  64413. /**
  64414. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64415. */
  64416. this.upAxisSpace = BABYLON.Space.LOCAL;
  64417. /**
  64418. * Used to make an adjustment to the yaw of the bone.
  64419. */
  64420. this.adjustYaw = 0;
  64421. /**
  64422. * Used to make an adjustment to the pitch of the bone.
  64423. */
  64424. this.adjustPitch = 0;
  64425. /**
  64426. * Used to make an adjustment to the roll of the bone.
  64427. */
  64428. this.adjustRoll = 0;
  64429. /**
  64430. * 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).
  64431. */
  64432. this.slerpAmount = 1;
  64433. this._boneQuat = BABYLON.Quaternion.Identity();
  64434. this._slerping = false;
  64435. this._firstFrameSkipped = false;
  64436. this._fowardAxis = BABYLON.Vector3.Forward();
  64437. this.mesh = mesh;
  64438. this.bone = bone;
  64439. this.target = target;
  64440. if (options) {
  64441. if (options.adjustYaw) {
  64442. this.adjustYaw = options.adjustYaw;
  64443. }
  64444. if (options.adjustPitch) {
  64445. this.adjustPitch = options.adjustPitch;
  64446. }
  64447. if (options.adjustRoll) {
  64448. this.adjustRoll = options.adjustRoll;
  64449. }
  64450. if (options.maxYaw != null) {
  64451. this.maxYaw = options.maxYaw;
  64452. }
  64453. else {
  64454. this.maxYaw = Math.PI;
  64455. }
  64456. if (options.minYaw != null) {
  64457. this.minYaw = options.minYaw;
  64458. }
  64459. else {
  64460. this.minYaw = -Math.PI;
  64461. }
  64462. if (options.maxPitch != null) {
  64463. this.maxPitch = options.maxPitch;
  64464. }
  64465. else {
  64466. this.maxPitch = Math.PI;
  64467. }
  64468. if (options.minPitch != null) {
  64469. this.minPitch = options.minPitch;
  64470. }
  64471. else {
  64472. this.minPitch = -Math.PI;
  64473. }
  64474. if (options.slerpAmount != null) {
  64475. this.slerpAmount = options.slerpAmount;
  64476. }
  64477. if (options.upAxis != null) {
  64478. this.upAxis = options.upAxis;
  64479. }
  64480. if (options.upAxisSpace != null) {
  64481. this.upAxisSpace = options.upAxisSpace;
  64482. }
  64483. if (options.yawAxis != null || options.pitchAxis != null) {
  64484. var newYawAxis = BABYLON.Axis.Y;
  64485. var newPitchAxis = BABYLON.Axis.X;
  64486. if (options.yawAxis != null) {
  64487. newYawAxis = options.yawAxis.clone();
  64488. newYawAxis.normalize();
  64489. }
  64490. if (options.pitchAxis != null) {
  64491. newPitchAxis = options.pitchAxis.clone();
  64492. newPitchAxis.normalize();
  64493. }
  64494. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64495. this._transformYawPitch = BABYLON.Matrix.Identity();
  64496. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64497. this._transformYawPitchInv = this._transformYawPitch.clone();
  64498. this._transformYawPitch.invert();
  64499. }
  64500. }
  64501. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64502. this.upAxisSpace = BABYLON.Space.LOCAL;
  64503. }
  64504. }
  64505. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64506. /**
  64507. * Get/set the minimum yaw angle that the bone can look to.
  64508. */
  64509. get: function () {
  64510. return this._minYaw;
  64511. },
  64512. set: function (value) {
  64513. this._minYaw = value;
  64514. this._minYawSin = Math.sin(value);
  64515. this._minYawCos = Math.cos(value);
  64516. if (this._maxYaw != null) {
  64517. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64518. this._yawRange = this._maxYaw - this._minYaw;
  64519. }
  64520. },
  64521. enumerable: true,
  64522. configurable: true
  64523. });
  64524. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64525. /**
  64526. * Get/set the maximum yaw angle that the bone can look to.
  64527. */
  64528. get: function () {
  64529. return this._maxYaw;
  64530. },
  64531. set: function (value) {
  64532. this._maxYaw = value;
  64533. this._maxYawSin = Math.sin(value);
  64534. this._maxYawCos = Math.cos(value);
  64535. if (this._minYaw != null) {
  64536. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64537. this._yawRange = this._maxYaw - this._minYaw;
  64538. }
  64539. },
  64540. enumerable: true,
  64541. configurable: true
  64542. });
  64543. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64544. /**
  64545. * Get/set the minimum pitch angle that the bone can look to.
  64546. */
  64547. get: function () {
  64548. return this._minPitch;
  64549. },
  64550. set: function (value) {
  64551. this._minPitch = value;
  64552. this._minPitchTan = Math.tan(value);
  64553. },
  64554. enumerable: true,
  64555. configurable: true
  64556. });
  64557. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64558. /**
  64559. * Get/set the maximum pitch angle that the bone can look to.
  64560. */
  64561. get: function () {
  64562. return this._maxPitch;
  64563. },
  64564. set: function (value) {
  64565. this._maxPitch = value;
  64566. this._maxPitchTan = Math.tan(value);
  64567. },
  64568. enumerable: true,
  64569. configurable: true
  64570. });
  64571. /**
  64572. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64573. */
  64574. BoneLookController.prototype.update = function () {
  64575. //skip the first frame when slerping so that the mesh rotation is correct
  64576. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64577. this._firstFrameSkipped = true;
  64578. return;
  64579. }
  64580. var bone = this.bone;
  64581. var bonePos = BoneLookController._tmpVecs[0];
  64582. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64583. var target = this.target;
  64584. var _tmpMat1 = BoneLookController._tmpMats[0];
  64585. var _tmpMat2 = BoneLookController._tmpMats[1];
  64586. var mesh = this.mesh;
  64587. var parentBone = bone.getParent();
  64588. var upAxis = BoneLookController._tmpVecs[1];
  64589. upAxis.copyFrom(this.upAxis);
  64590. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64591. if (this._transformYawPitch) {
  64592. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64593. }
  64594. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64595. }
  64596. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64597. mesh.getDirectionToRef(upAxis, upAxis);
  64598. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64599. upAxis.normalize();
  64600. }
  64601. }
  64602. var checkYaw = false;
  64603. var checkPitch = false;
  64604. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64605. checkYaw = true;
  64606. }
  64607. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64608. checkPitch = true;
  64609. }
  64610. if (checkYaw || checkPitch) {
  64611. var spaceMat = BoneLookController._tmpMats[2];
  64612. var spaceMatInv = BoneLookController._tmpMats[3];
  64613. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64614. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64615. }
  64616. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64617. spaceMat.copyFrom(mesh.getWorldMatrix());
  64618. }
  64619. else {
  64620. var forwardAxis = BoneLookController._tmpVecs[2];
  64621. forwardAxis.copyFrom(this._fowardAxis);
  64622. if (this._transformYawPitch) {
  64623. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64624. }
  64625. if (parentBone) {
  64626. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64627. }
  64628. else {
  64629. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64630. }
  64631. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64632. rightAxis.normalize();
  64633. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64634. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64635. }
  64636. spaceMat.invertToRef(spaceMatInv);
  64637. var xzlen = null;
  64638. if (checkPitch) {
  64639. var localTarget = BoneLookController._tmpVecs[3];
  64640. target.subtractToRef(bonePos, localTarget);
  64641. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64642. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64643. var pitch = Math.atan2(localTarget.y, xzlen);
  64644. var newPitch = pitch;
  64645. if (pitch > this._maxPitch) {
  64646. localTarget.y = this._maxPitchTan * xzlen;
  64647. newPitch = this._maxPitch;
  64648. }
  64649. else if (pitch < this._minPitch) {
  64650. localTarget.y = this._minPitchTan * xzlen;
  64651. newPitch = this._minPitch;
  64652. }
  64653. if (pitch != newPitch) {
  64654. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64655. localTarget.addInPlace(bonePos);
  64656. target = localTarget;
  64657. }
  64658. }
  64659. if (checkYaw) {
  64660. var localTarget = BoneLookController._tmpVecs[4];
  64661. target.subtractToRef(bonePos, localTarget);
  64662. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64663. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64664. var newYaw = yaw;
  64665. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64666. if (xzlen == null) {
  64667. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64668. }
  64669. if (this._yawRange > Math.PI) {
  64670. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64671. localTarget.z = this._maxYawCos * xzlen;
  64672. localTarget.x = this._maxYawSin * xzlen;
  64673. newYaw = this._maxYaw;
  64674. }
  64675. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64676. localTarget.z = this._minYawCos * xzlen;
  64677. localTarget.x = this._minYawSin * xzlen;
  64678. newYaw = this._minYaw;
  64679. }
  64680. }
  64681. else {
  64682. if (yaw > this._maxYaw) {
  64683. localTarget.z = this._maxYawCos * xzlen;
  64684. localTarget.x = this._maxYawSin * xzlen;
  64685. newYaw = this._maxYaw;
  64686. }
  64687. else if (yaw < this._minYaw) {
  64688. localTarget.z = this._minYawCos * xzlen;
  64689. localTarget.x = this._minYawSin * xzlen;
  64690. newYaw = this._minYaw;
  64691. }
  64692. }
  64693. }
  64694. if (this._slerping && this._yawRange > Math.PI) {
  64695. //are we going to be crossing into the min/max region?
  64696. var boneFwd = BoneLookController._tmpVecs[8];
  64697. boneFwd.copyFrom(BABYLON.Axis.Z);
  64698. if (this._transformYawPitch) {
  64699. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64700. }
  64701. var boneRotMat = BoneLookController._tmpMats[4];
  64702. this._boneQuat.toRotationMatrix(boneRotMat);
  64703. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64704. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64705. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64706. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64707. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64708. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64709. if (angBtwTar > angBtwMidYaw) {
  64710. if (xzlen == null) {
  64711. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64712. }
  64713. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64714. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64715. if (angBtwMin < angBtwMax) {
  64716. newYaw = boneYaw + Math.PI * .75;
  64717. localTarget.z = Math.cos(newYaw) * xzlen;
  64718. localTarget.x = Math.sin(newYaw) * xzlen;
  64719. }
  64720. else {
  64721. newYaw = boneYaw - Math.PI * .75;
  64722. localTarget.z = Math.cos(newYaw) * xzlen;
  64723. localTarget.x = Math.sin(newYaw) * xzlen;
  64724. }
  64725. }
  64726. }
  64727. if (yaw != newYaw) {
  64728. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64729. localTarget.addInPlace(bonePos);
  64730. target = localTarget;
  64731. }
  64732. }
  64733. }
  64734. var zaxis = BoneLookController._tmpVecs[5];
  64735. var xaxis = BoneLookController._tmpVecs[6];
  64736. var yaxis = BoneLookController._tmpVecs[7];
  64737. var _tmpQuat = BoneLookController._tmpQuat;
  64738. target.subtractToRef(bonePos, zaxis);
  64739. zaxis.normalize();
  64740. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64741. xaxis.normalize();
  64742. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64743. yaxis.normalize();
  64744. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64745. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64746. return;
  64747. }
  64748. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64749. return;
  64750. }
  64751. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64752. return;
  64753. }
  64754. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64755. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64756. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64757. }
  64758. if (this.slerpAmount < 1) {
  64759. if (!this._slerping) {
  64760. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64761. }
  64762. if (this._transformYawPitch) {
  64763. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64764. }
  64765. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64766. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64767. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64768. this._slerping = true;
  64769. }
  64770. else {
  64771. if (this._transformYawPitch) {
  64772. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64773. }
  64774. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64775. this._slerping = false;
  64776. }
  64777. };
  64778. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64779. var angDiff = ang2 - ang1;
  64780. angDiff %= Math.PI * 2;
  64781. if (angDiff > Math.PI) {
  64782. angDiff -= Math.PI * 2;
  64783. }
  64784. else if (angDiff < -Math.PI) {
  64785. angDiff += Math.PI * 2;
  64786. }
  64787. return angDiff;
  64788. };
  64789. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64790. ang1 %= (2 * Math.PI);
  64791. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64792. ang2 %= (2 * Math.PI);
  64793. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64794. var ab = 0;
  64795. if (ang1 < ang2) {
  64796. ab = ang2 - ang1;
  64797. }
  64798. else {
  64799. ab = ang1 - ang2;
  64800. }
  64801. if (ab > Math.PI) {
  64802. ab = Math.PI * 2 - ab;
  64803. }
  64804. return ab;
  64805. };
  64806. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64807. ang %= (2 * Math.PI);
  64808. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64809. ang1 %= (2 * Math.PI);
  64810. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64811. ang2 %= (2 * Math.PI);
  64812. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64813. if (ang1 < ang2) {
  64814. if (ang > ang1 && ang < ang2) {
  64815. return true;
  64816. }
  64817. }
  64818. else {
  64819. if (ang > ang2 && ang < ang1) {
  64820. return true;
  64821. }
  64822. }
  64823. return false;
  64824. };
  64825. 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()];
  64826. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64827. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64828. return BoneLookController;
  64829. }());
  64830. BABYLON.BoneLookController = BoneLookController;
  64831. })(BABYLON || (BABYLON = {}));
  64832. //# sourceMappingURL=babylon.boneLookController.js.map
  64833. var BABYLON;
  64834. (function (BABYLON) {
  64835. var Skeleton = /** @class */ (function () {
  64836. function Skeleton(name, id, scene) {
  64837. this.name = name;
  64838. this.id = id;
  64839. this.bones = new Array();
  64840. this.needInitialSkinMatrix = false;
  64841. this._isDirty = true;
  64842. this._meshesWithPoseMatrix = new Array();
  64843. this._identity = BABYLON.Matrix.Identity();
  64844. this._ranges = {};
  64845. this._lastAbsoluteTransformsUpdateId = -1;
  64846. // Events
  64847. /**
  64848. * An event triggered before computing the skeleton's matrices
  64849. * @type {BABYLON.Observable}
  64850. */
  64851. this.onBeforeComputeObservable = new BABYLON.Observable();
  64852. this.bones = [];
  64853. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64854. scene.skeletons.push(this);
  64855. //make sure it will recalculate the matrix next time prepare is called.
  64856. this._isDirty = true;
  64857. }
  64858. // Members
  64859. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64860. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64861. return mesh._bonesTransformMatrices;
  64862. }
  64863. if (!this._transformMatrices) {
  64864. this.prepare();
  64865. }
  64866. return this._transformMatrices;
  64867. };
  64868. Skeleton.prototype.getScene = function () {
  64869. return this._scene;
  64870. };
  64871. // Methods
  64872. /**
  64873. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64874. */
  64875. Skeleton.prototype.toString = function (fullDetails) {
  64876. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64877. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64878. if (fullDetails) {
  64879. ret += ", Ranges: {";
  64880. var first = true;
  64881. for (var name_1 in this._ranges) {
  64882. if (first) {
  64883. ret += ", ";
  64884. first = false;
  64885. }
  64886. ret += name_1;
  64887. }
  64888. ret += "}";
  64889. }
  64890. return ret;
  64891. };
  64892. /**
  64893. * Get bone's index searching by name
  64894. * @param {string} name is bone's name to search for
  64895. * @return {number} Indice of the bone. Returns -1 if not found
  64896. */
  64897. Skeleton.prototype.getBoneIndexByName = function (name) {
  64898. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64899. if (this.bones[boneIndex].name === name) {
  64900. return boneIndex;
  64901. }
  64902. }
  64903. return -1;
  64904. };
  64905. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64906. // check name not already in use
  64907. if (!this._ranges[name]) {
  64908. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64909. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64910. if (this.bones[i].animations[0]) {
  64911. this.bones[i].animations[0].createRange(name, from, to);
  64912. }
  64913. }
  64914. }
  64915. };
  64916. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64917. if (deleteFrames === void 0) { deleteFrames = true; }
  64918. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64919. if (this.bones[i].animations[0]) {
  64920. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64921. }
  64922. }
  64923. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64924. };
  64925. Skeleton.prototype.getAnimationRange = function (name) {
  64926. return this._ranges[name];
  64927. };
  64928. /**
  64929. * Returns as an Array, all AnimationRanges defined on this skeleton
  64930. */
  64931. Skeleton.prototype.getAnimationRanges = function () {
  64932. var animationRanges = [];
  64933. var name;
  64934. var i = 0;
  64935. for (name in this._ranges) {
  64936. animationRanges[i] = this._ranges[name];
  64937. i++;
  64938. }
  64939. return animationRanges;
  64940. };
  64941. /**
  64942. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64943. */
  64944. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64945. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64946. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64947. return false;
  64948. }
  64949. var ret = true;
  64950. var frameOffset = this._getHighestAnimationFrame() + 1;
  64951. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64952. var boneDict = {};
  64953. var sourceBones = source.bones;
  64954. var nBones;
  64955. var i;
  64956. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64957. boneDict[sourceBones[i].name] = sourceBones[i];
  64958. }
  64959. if (this.bones.length !== sourceBones.length) {
  64960. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64961. ret = false;
  64962. }
  64963. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64964. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64965. var boneName = this.bones[i].name;
  64966. var sourceBone = boneDict[boneName];
  64967. if (sourceBone) {
  64968. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64969. }
  64970. else {
  64971. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64972. ret = false;
  64973. }
  64974. }
  64975. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64976. var range = source.getAnimationRange(name);
  64977. if (range) {
  64978. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64979. }
  64980. return ret;
  64981. };
  64982. Skeleton.prototype.returnToRest = function () {
  64983. for (var index = 0; index < this.bones.length; index++) {
  64984. this.bones[index].returnToRest();
  64985. }
  64986. };
  64987. Skeleton.prototype._getHighestAnimationFrame = function () {
  64988. var ret = 0;
  64989. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64990. if (this.bones[i].animations[0]) {
  64991. var highest = this.bones[i].animations[0].getHighestFrame();
  64992. if (ret < highest) {
  64993. ret = highest;
  64994. }
  64995. }
  64996. }
  64997. return ret;
  64998. };
  64999. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  65000. var range = this.getAnimationRange(name);
  65001. if (!range) {
  65002. return null;
  65003. }
  65004. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  65005. };
  65006. Skeleton.prototype._markAsDirty = function () {
  65007. this._isDirty = true;
  65008. };
  65009. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  65010. this._meshesWithPoseMatrix.push(mesh);
  65011. };
  65012. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  65013. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  65014. if (index > -1) {
  65015. this._meshesWithPoseMatrix.splice(index, 1);
  65016. }
  65017. };
  65018. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  65019. this.onBeforeComputeObservable.notifyObservers(this);
  65020. for (var index = 0; index < this.bones.length; index++) {
  65021. var bone = this.bones[index];
  65022. var parentBone = bone.getParent();
  65023. if (parentBone) {
  65024. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  65025. }
  65026. else {
  65027. if (initialSkinMatrix) {
  65028. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  65029. }
  65030. else {
  65031. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  65032. }
  65033. }
  65034. if (bone._index !== -1) {
  65035. var mappedIndex = bone._index === null ? index : bone._index;
  65036. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  65037. }
  65038. }
  65039. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  65040. };
  65041. Skeleton.prototype.prepare = function () {
  65042. if (!this._isDirty) {
  65043. return;
  65044. }
  65045. if (this.needInitialSkinMatrix) {
  65046. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  65047. var mesh = this._meshesWithPoseMatrix[index];
  65048. var poseMatrix = mesh.getPoseMatrix();
  65049. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  65050. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  65051. }
  65052. if (this._synchronizedWithMesh !== mesh) {
  65053. this._synchronizedWithMesh = mesh;
  65054. // Prepare bones
  65055. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  65056. var bone = this.bones[boneIndex];
  65057. if (!bone.getParent()) {
  65058. var matrix = bone.getBaseMatrix();
  65059. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  65060. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  65061. }
  65062. }
  65063. }
  65064. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  65065. }
  65066. }
  65067. else {
  65068. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  65069. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  65070. }
  65071. this._computeTransformMatrices(this._transformMatrices, null);
  65072. }
  65073. this._isDirty = false;
  65074. this._scene._activeBones.addCount(this.bones.length, false);
  65075. };
  65076. Skeleton.prototype.getAnimatables = function () {
  65077. if (!this._animatables || this._animatables.length !== this.bones.length) {
  65078. this._animatables = [];
  65079. for (var index = 0; index < this.bones.length; index++) {
  65080. this._animatables.push(this.bones[index]);
  65081. }
  65082. }
  65083. return this._animatables;
  65084. };
  65085. Skeleton.prototype.clone = function (name, id) {
  65086. var result = new Skeleton(name, id || name, this._scene);
  65087. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65088. for (var index = 0; index < this.bones.length; index++) {
  65089. var source = this.bones[index];
  65090. var parentBone = null;
  65091. var parent_1 = source.getParent();
  65092. if (parent_1) {
  65093. var parentIndex = this.bones.indexOf(parent_1);
  65094. parentBone = result.bones[parentIndex];
  65095. }
  65096. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  65097. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  65098. }
  65099. if (this._ranges) {
  65100. result._ranges = {};
  65101. for (var rangeName in this._ranges) {
  65102. var range = this._ranges[rangeName];
  65103. if (range) {
  65104. result._ranges[rangeName] = range.clone();
  65105. }
  65106. }
  65107. }
  65108. this._isDirty = true;
  65109. return result;
  65110. };
  65111. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  65112. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  65113. this.bones.forEach(function (bone) {
  65114. bone.animations.forEach(function (animation) {
  65115. animation.enableBlending = true;
  65116. animation.blendingSpeed = blendingSpeed;
  65117. });
  65118. });
  65119. };
  65120. Skeleton.prototype.dispose = function () {
  65121. this._meshesWithPoseMatrix = [];
  65122. // Animations
  65123. this.getScene().stopAnimation(this);
  65124. // Remove from scene
  65125. this.getScene().removeSkeleton(this);
  65126. };
  65127. Skeleton.prototype.serialize = function () {
  65128. var serializationObject = {};
  65129. serializationObject.name = this.name;
  65130. serializationObject.id = this.id;
  65131. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  65132. serializationObject.bones = [];
  65133. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65134. for (var index = 0; index < this.bones.length; index++) {
  65135. var bone = this.bones[index];
  65136. var parent_2 = bone.getParent();
  65137. var serializedBone = {
  65138. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  65139. name: bone.name,
  65140. matrix: bone.getBaseMatrix().toArray(),
  65141. rest: bone.getRestPose().toArray()
  65142. };
  65143. serializationObject.bones.push(serializedBone);
  65144. if (bone.length) {
  65145. serializedBone.length = bone.length;
  65146. }
  65147. if (bone.animations && bone.animations.length > 0) {
  65148. serializedBone.animation = bone.animations[0].serialize();
  65149. }
  65150. serializationObject.ranges = [];
  65151. for (var name in this._ranges) {
  65152. var source = this._ranges[name];
  65153. if (!source) {
  65154. continue;
  65155. }
  65156. var range = {};
  65157. range.name = name;
  65158. range.from = source.from;
  65159. range.to = source.to;
  65160. serializationObject.ranges.push(range);
  65161. }
  65162. }
  65163. return serializationObject;
  65164. };
  65165. Skeleton.Parse = function (parsedSkeleton, scene) {
  65166. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65167. if (parsedSkeleton.dimensionsAtRest) {
  65168. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65169. }
  65170. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65171. var index;
  65172. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65173. var parsedBone = parsedSkeleton.bones[index];
  65174. var parentBone = null;
  65175. if (parsedBone.parentBoneIndex > -1) {
  65176. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65177. }
  65178. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65179. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65180. if (parsedBone.length) {
  65181. bone.length = parsedBone.length;
  65182. }
  65183. if (parsedBone.animation) {
  65184. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65185. }
  65186. }
  65187. // placed after bones, so createAnimationRange can cascade down
  65188. if (parsedSkeleton.ranges) {
  65189. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65190. var data = parsedSkeleton.ranges[index];
  65191. skeleton.createAnimationRange(data.name, data.from, data.to);
  65192. }
  65193. }
  65194. return skeleton;
  65195. };
  65196. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65197. if (forceUpdate === void 0) { forceUpdate = false; }
  65198. var renderId = this._scene.getRenderId();
  65199. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65200. this.bones[0].computeAbsoluteTransforms();
  65201. this._lastAbsoluteTransformsUpdateId = renderId;
  65202. }
  65203. };
  65204. Skeleton.prototype.getPoseMatrix = function () {
  65205. var poseMatrix = null;
  65206. if (this._meshesWithPoseMatrix.length > 0) {
  65207. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65208. }
  65209. return poseMatrix;
  65210. };
  65211. Skeleton.prototype.sortBones = function () {
  65212. var bones = new Array();
  65213. var visited = new Array(this.bones.length);
  65214. for (var index = 0; index < this.bones.length; index++) {
  65215. this._sortBones(index, bones, visited);
  65216. }
  65217. this.bones = bones;
  65218. };
  65219. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65220. if (visited[index]) {
  65221. return;
  65222. }
  65223. visited[index] = true;
  65224. var bone = this.bones[index];
  65225. if (bone._index === undefined) {
  65226. bone._index = index;
  65227. }
  65228. var parentBone = bone.getParent();
  65229. if (parentBone) {
  65230. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65231. }
  65232. bones.push(bone);
  65233. };
  65234. return Skeleton;
  65235. }());
  65236. BABYLON.Skeleton = Skeleton;
  65237. })(BABYLON || (BABYLON = {}));
  65238. //# sourceMappingURL=babylon.skeleton.js.map
  65239. var BABYLON;
  65240. (function (BABYLON) {
  65241. var SphericalPolynomial = /** @class */ (function () {
  65242. function SphericalPolynomial() {
  65243. this.x = BABYLON.Vector3.Zero();
  65244. this.y = BABYLON.Vector3.Zero();
  65245. this.z = BABYLON.Vector3.Zero();
  65246. this.xx = BABYLON.Vector3.Zero();
  65247. this.yy = BABYLON.Vector3.Zero();
  65248. this.zz = BABYLON.Vector3.Zero();
  65249. this.xy = BABYLON.Vector3.Zero();
  65250. this.yz = BABYLON.Vector3.Zero();
  65251. this.zx = BABYLON.Vector3.Zero();
  65252. }
  65253. SphericalPolynomial.prototype.addAmbient = function (color) {
  65254. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65255. this.xx = this.xx.add(colorVector);
  65256. this.yy = this.yy.add(colorVector);
  65257. this.zz = this.zz.add(colorVector);
  65258. };
  65259. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65260. var result = new SphericalPolynomial();
  65261. result.x = harmonics.L11.scale(1.02333);
  65262. result.y = harmonics.L1_1.scale(1.02333);
  65263. result.z = harmonics.L10.scale(1.02333);
  65264. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65265. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65266. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65267. result.yz = harmonics.L2_1.scale(0.858086);
  65268. result.zx = harmonics.L21.scale(0.858086);
  65269. result.xy = harmonics.L2_2.scale(0.858086);
  65270. result.scale(1.0 / Math.PI);
  65271. return result;
  65272. };
  65273. SphericalPolynomial.prototype.scale = function (scale) {
  65274. this.x = this.x.scale(scale);
  65275. this.y = this.y.scale(scale);
  65276. this.z = this.z.scale(scale);
  65277. this.xx = this.xx.scale(scale);
  65278. this.yy = this.yy.scale(scale);
  65279. this.zz = this.zz.scale(scale);
  65280. this.yz = this.yz.scale(scale);
  65281. this.zx = this.zx.scale(scale);
  65282. this.xy = this.xy.scale(scale);
  65283. };
  65284. return SphericalPolynomial;
  65285. }());
  65286. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65287. var SphericalHarmonics = /** @class */ (function () {
  65288. function SphericalHarmonics() {
  65289. this.L00 = BABYLON.Vector3.Zero();
  65290. this.L1_1 = BABYLON.Vector3.Zero();
  65291. this.L10 = BABYLON.Vector3.Zero();
  65292. this.L11 = BABYLON.Vector3.Zero();
  65293. this.L2_2 = BABYLON.Vector3.Zero();
  65294. this.L2_1 = BABYLON.Vector3.Zero();
  65295. this.L20 = BABYLON.Vector3.Zero();
  65296. this.L21 = BABYLON.Vector3.Zero();
  65297. this.L22 = BABYLON.Vector3.Zero();
  65298. }
  65299. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65300. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65301. var c = colorVector.scale(deltaSolidAngle);
  65302. this.L00 = this.L00.add(c.scale(0.282095));
  65303. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65304. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65305. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65306. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65307. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65308. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65309. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65310. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65311. };
  65312. SphericalHarmonics.prototype.scale = function (scale) {
  65313. this.L00 = this.L00.scale(scale);
  65314. this.L1_1 = this.L1_1.scale(scale);
  65315. this.L10 = this.L10.scale(scale);
  65316. this.L11 = this.L11.scale(scale);
  65317. this.L2_2 = this.L2_2.scale(scale);
  65318. this.L2_1 = this.L2_1.scale(scale);
  65319. this.L20 = this.L20.scale(scale);
  65320. this.L21 = this.L21.scale(scale);
  65321. this.L22 = this.L22.scale(scale);
  65322. };
  65323. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65324. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65325. //
  65326. // E_lm = A_l * L_lm
  65327. //
  65328. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65329. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65330. // the scaling factors are given in equation 9.
  65331. // Constant (Band 0)
  65332. this.L00 = this.L00.scale(3.141593);
  65333. // Linear (Band 1)
  65334. this.L1_1 = this.L1_1.scale(2.094395);
  65335. this.L10 = this.L10.scale(2.094395);
  65336. this.L11 = this.L11.scale(2.094395);
  65337. // Quadratic (Band 2)
  65338. this.L2_2 = this.L2_2.scale(0.785398);
  65339. this.L2_1 = this.L2_1.scale(0.785398);
  65340. this.L20 = this.L20.scale(0.785398);
  65341. this.L21 = this.L21.scale(0.785398);
  65342. this.L22 = this.L22.scale(0.785398);
  65343. };
  65344. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65345. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65346. // L = (1/pi) * E * rho
  65347. //
  65348. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65349. this.scale(1.0 / Math.PI);
  65350. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65351. // (The pixel shader must apply albedo after texture fetches, etc).
  65352. };
  65353. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65354. var result = new SphericalHarmonics();
  65355. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65356. result.L1_1 = polynomial.y.scale(0.977204);
  65357. result.L10 = polynomial.z.scale(0.977204);
  65358. result.L11 = polynomial.x.scale(0.977204);
  65359. result.L2_2 = polynomial.xy.scale(1.16538);
  65360. result.L2_1 = polynomial.yz.scale(1.16538);
  65361. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65362. result.L21 = polynomial.zx.scale(1.16538);
  65363. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65364. result.scale(Math.PI);
  65365. return result;
  65366. };
  65367. return SphericalHarmonics;
  65368. }());
  65369. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65370. })(BABYLON || (BABYLON = {}));
  65371. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65372. var BABYLON;
  65373. (function (BABYLON) {
  65374. var FileFaceOrientation = /** @class */ (function () {
  65375. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65376. this.name = name;
  65377. this.worldAxisForNormal = worldAxisForNormal;
  65378. this.worldAxisForFileX = worldAxisForFileX;
  65379. this.worldAxisForFileY = worldAxisForFileY;
  65380. }
  65381. return FileFaceOrientation;
  65382. }());
  65383. ;
  65384. /**
  65385. * Helper class dealing with the extraction of spherical polynomial dataArray
  65386. * from a cube map.
  65387. */
  65388. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65389. function CubeMapToSphericalPolynomialTools() {
  65390. }
  65391. /**
  65392. * Converts a texture to the according Spherical Polynomial data.
  65393. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65394. *
  65395. * @param texture The texture to extract the information from.
  65396. * @return The Spherical Polynomial data.
  65397. */
  65398. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65399. if (!texture.isCube) {
  65400. // Only supports cube Textures currently.
  65401. return null;
  65402. }
  65403. var size = texture.getSize().width;
  65404. var right = texture.readPixels(0);
  65405. var left = texture.readPixels(1);
  65406. var up;
  65407. var down;
  65408. if (texture.isRenderTarget) {
  65409. up = texture.readPixels(3);
  65410. down = texture.readPixels(2);
  65411. }
  65412. else {
  65413. up = texture.readPixels(2);
  65414. down = texture.readPixels(3);
  65415. }
  65416. var front = texture.readPixels(4);
  65417. var back = texture.readPixels(5);
  65418. var gammaSpace = texture.gammaSpace;
  65419. // Always read as RGBA.
  65420. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65421. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65422. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65423. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65424. }
  65425. var cubeInfo = {
  65426. size: size,
  65427. right: right,
  65428. left: left,
  65429. up: up,
  65430. down: down,
  65431. front: front,
  65432. back: back,
  65433. format: format,
  65434. type: type,
  65435. gammaSpace: gammaSpace,
  65436. };
  65437. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65438. };
  65439. /**
  65440. * Converts a cubemap to the according Spherical Polynomial data.
  65441. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65442. *
  65443. * @param cubeInfo The Cube map to extract the information from.
  65444. * @return The Spherical Polynomial data.
  65445. */
  65446. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65447. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65448. var totalSolidAngle = 0.0;
  65449. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65450. var du = 2.0 / cubeInfo.size;
  65451. var dv = du;
  65452. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65453. var minUV = du * 0.5 - 1.0;
  65454. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65455. var fileFace = this.FileFaces[faceIndex];
  65456. var dataArray = cubeInfo[fileFace.name];
  65457. var v = minUV;
  65458. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65459. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65460. // Because SP is still linear, so summation is fine in that basis.
  65461. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65462. for (var y = 0; y < cubeInfo.size; y++) {
  65463. var u = minUV;
  65464. for (var x = 0; x < cubeInfo.size; x++) {
  65465. // World direction (not normalised)
  65466. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65467. worldDirection.normalize();
  65468. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65469. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65470. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65471. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65472. // Handle Integer types.
  65473. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65474. r /= 255;
  65475. g /= 255;
  65476. b /= 255;
  65477. }
  65478. // Handle Gamma space textures.
  65479. if (cubeInfo.gammaSpace) {
  65480. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65481. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65482. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65483. }
  65484. var color = new BABYLON.Color3(r, g, b);
  65485. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65486. totalSolidAngle += deltaSolidAngle;
  65487. u += du;
  65488. }
  65489. v += dv;
  65490. }
  65491. }
  65492. // Solid angle for entire sphere is 4*pi
  65493. var sphereSolidAngle = 4.0 * Math.PI;
  65494. // Adjust the solid angle to allow for how many faces we processed.
  65495. var facesProcessed = 6.0;
  65496. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65497. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65498. // This is needed because the numerical integration over the cube uses a
  65499. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65500. // and also to compensate for accumulative error due to float precision in the summation.
  65501. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65502. sphericalHarmonics.scale(correctionFactor);
  65503. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65504. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65505. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65506. };
  65507. CubeMapToSphericalPolynomialTools.FileFaces = [
  65508. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65509. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65510. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65511. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65512. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65513. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65514. ];
  65515. return CubeMapToSphericalPolynomialTools;
  65516. }());
  65517. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. /**
  65523. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65524. */
  65525. var PanoramaToCubeMapTools = /** @class */ (function () {
  65526. function PanoramaToCubeMapTools() {
  65527. }
  65528. /**
  65529. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65530. *
  65531. * @param float32Array The source data.
  65532. * @param inputWidth The width of the input panorama.
  65533. * @param inputhHeight The height of the input panorama.
  65534. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65535. * @return The cubemap data
  65536. */
  65537. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65538. if (!float32Array) {
  65539. throw "ConvertPanoramaToCubemap: input cannot be null";
  65540. }
  65541. if (float32Array.length != inputWidth * inputHeight * 3) {
  65542. throw "ConvertPanoramaToCubemap: input size is wrong";
  65543. }
  65544. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65545. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65546. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65547. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65548. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65549. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65550. return {
  65551. front: textureFront,
  65552. back: textureBack,
  65553. left: textureLeft,
  65554. right: textureRight,
  65555. up: textureUp,
  65556. down: textureDown,
  65557. size: size,
  65558. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65559. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65560. gammaSpace: false,
  65561. };
  65562. };
  65563. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65564. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65565. var textureArray = new Float32Array(buffer);
  65566. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65567. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65568. var dy = 1 / texSize;
  65569. var fy = 0;
  65570. for (var y = 0; y < texSize; y++) {
  65571. var xv1 = faceData[0];
  65572. var xv2 = faceData[2];
  65573. for (var x = 0; x < texSize; x++) {
  65574. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65575. v.normalize();
  65576. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65577. // 3 channels per pixels
  65578. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65579. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65580. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65581. xv1 = xv1.add(rotDX1);
  65582. xv2 = xv2.add(rotDX2);
  65583. }
  65584. fy += dy;
  65585. }
  65586. return textureArray;
  65587. };
  65588. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65589. var theta = Math.atan2(vDir.z, vDir.x);
  65590. var phi = Math.acos(vDir.y);
  65591. while (theta < -Math.PI)
  65592. theta += 2 * Math.PI;
  65593. while (theta > Math.PI)
  65594. theta -= 2 * Math.PI;
  65595. var dx = theta / Math.PI;
  65596. var dy = phi / Math.PI;
  65597. // recenter.
  65598. dx = dx * 0.5 + 0.5;
  65599. var px = Math.round(dx * inputWidth);
  65600. if (px < 0)
  65601. px = 0;
  65602. else if (px >= inputWidth)
  65603. px = inputWidth - 1;
  65604. var py = Math.round(dy * inputHeight);
  65605. if (py < 0)
  65606. py = 0;
  65607. else if (py >= inputHeight)
  65608. py = inputHeight - 1;
  65609. var inputY = (inputHeight - py - 1);
  65610. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65611. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65612. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65613. return {
  65614. r: r,
  65615. g: g,
  65616. b: b
  65617. };
  65618. };
  65619. PanoramaToCubeMapTools.FACE_FRONT = [
  65620. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65621. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65622. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65623. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65624. ];
  65625. PanoramaToCubeMapTools.FACE_BACK = [
  65626. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65627. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65628. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65629. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65630. ];
  65631. PanoramaToCubeMapTools.FACE_RIGHT = [
  65632. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65633. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65634. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65635. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65636. ];
  65637. PanoramaToCubeMapTools.FACE_LEFT = [
  65638. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65639. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65640. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65641. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65642. ];
  65643. PanoramaToCubeMapTools.FACE_DOWN = [
  65644. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65645. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65646. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65647. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65648. ];
  65649. PanoramaToCubeMapTools.FACE_UP = [
  65650. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65651. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65652. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65653. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65654. ];
  65655. return PanoramaToCubeMapTools;
  65656. }());
  65657. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65658. })(BABYLON || (BABYLON = {}));
  65659. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65660. var BABYLON;
  65661. (function (BABYLON) {
  65662. ;
  65663. /**
  65664. * This groups tools to convert HDR texture to native colors array.
  65665. */
  65666. var HDRTools = /** @class */ (function () {
  65667. function HDRTools() {
  65668. }
  65669. HDRTools.Ldexp = function (mantissa, exponent) {
  65670. if (exponent > 1023) {
  65671. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65672. }
  65673. if (exponent < -1074) {
  65674. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65675. }
  65676. return mantissa * Math.pow(2, exponent);
  65677. };
  65678. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65679. if (exponent > 0) {
  65680. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65681. float32array[index + 0] = red * exponent;
  65682. float32array[index + 1] = green * exponent;
  65683. float32array[index + 2] = blue * exponent;
  65684. }
  65685. else {
  65686. float32array[index + 0] = 0;
  65687. float32array[index + 1] = 0;
  65688. float32array[index + 2] = 0;
  65689. }
  65690. };
  65691. HDRTools.readStringLine = function (uint8array, startIndex) {
  65692. var line = "";
  65693. var character = "";
  65694. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65695. character = String.fromCharCode(uint8array[i]);
  65696. if (character == "\n") {
  65697. break;
  65698. }
  65699. line += character;
  65700. }
  65701. return line;
  65702. };
  65703. /**
  65704. * Reads header information from an RGBE texture stored in a native array.
  65705. * More information on this format are available here:
  65706. * https://en.wikipedia.org/wiki/RGBE_image_format
  65707. *
  65708. * @param uint8array The binary file stored in native array.
  65709. * @return The header information.
  65710. */
  65711. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65712. var height = 0;
  65713. var width = 0;
  65714. var line = this.readStringLine(uint8array, 0);
  65715. if (line[0] != '#' || line[1] != '?') {
  65716. throw "Bad HDR Format.";
  65717. }
  65718. var endOfHeader = false;
  65719. var findFormat = false;
  65720. var lineIndex = 0;
  65721. do {
  65722. lineIndex += (line.length + 1);
  65723. line = this.readStringLine(uint8array, lineIndex);
  65724. if (line == "FORMAT=32-bit_rle_rgbe") {
  65725. findFormat = true;
  65726. }
  65727. else if (line.length == 0) {
  65728. endOfHeader = true;
  65729. }
  65730. } while (!endOfHeader);
  65731. if (!findFormat) {
  65732. throw "HDR Bad header format, unsupported FORMAT";
  65733. }
  65734. lineIndex += (line.length + 1);
  65735. line = this.readStringLine(uint8array, lineIndex);
  65736. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65737. var match = sizeRegexp.exec(line);
  65738. // TODO. Support +Y and -X if needed.
  65739. if (!match || match.length < 3) {
  65740. throw "HDR Bad header format, no size";
  65741. }
  65742. width = parseInt(match[2]);
  65743. height = parseInt(match[1]);
  65744. if (width < 8 || width > 0x7fff) {
  65745. throw "HDR Bad header format, unsupported size";
  65746. }
  65747. lineIndex += (line.length + 1);
  65748. return {
  65749. height: height,
  65750. width: width,
  65751. dataPosition: lineIndex
  65752. };
  65753. };
  65754. /**
  65755. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65756. * This RGBE texture needs to store the information as a panorama.
  65757. *
  65758. * More information on this format are available here:
  65759. * https://en.wikipedia.org/wiki/RGBE_image_format
  65760. *
  65761. * @param buffer The binary file stored in an array buffer.
  65762. * @param size The expected size of the extracted cubemap.
  65763. * @return The Cube Map information.
  65764. */
  65765. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65766. var uint8array = new Uint8Array(buffer);
  65767. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65768. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65769. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65770. return cubeMapData;
  65771. };
  65772. /**
  65773. * Returns the pixels data extracted from an RGBE texture.
  65774. * This pixels will be stored left to right up to down in the R G B order in one array.
  65775. *
  65776. * More information on this format are available here:
  65777. * https://en.wikipedia.org/wiki/RGBE_image_format
  65778. *
  65779. * @param uint8array The binary file stored in an array buffer.
  65780. * @param hdrInfo The header information of the file.
  65781. * @return The pixels data in RGB right to left up to down order.
  65782. */
  65783. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65784. // Keep for multi format supports.
  65785. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65786. };
  65787. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65788. var num_scanlines = hdrInfo.height;
  65789. var scanline_width = hdrInfo.width;
  65790. var a, b, c, d, count;
  65791. var dataIndex = hdrInfo.dataPosition;
  65792. var index = 0, endIndex = 0, i = 0;
  65793. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65794. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65795. // 3 channels of 4 bytes per pixel in float.
  65796. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65797. var resultArray = new Float32Array(resultBuffer);
  65798. // read in each successive scanline
  65799. while (num_scanlines > 0) {
  65800. a = uint8array[dataIndex++];
  65801. b = uint8array[dataIndex++];
  65802. c = uint8array[dataIndex++];
  65803. d = uint8array[dataIndex++];
  65804. if (a != 2 || b != 2 || (c & 0x80)) {
  65805. // this file is not run length encoded
  65806. throw "HDR Bad header format, not RLE";
  65807. }
  65808. if (((c << 8) | d) != scanline_width) {
  65809. throw "HDR Bad header format, wrong scan line width";
  65810. }
  65811. index = 0;
  65812. // read each of the four channels for the scanline into the buffer
  65813. for (i = 0; i < 4; i++) {
  65814. endIndex = (i + 1) * scanline_width;
  65815. while (index < endIndex) {
  65816. a = uint8array[dataIndex++];
  65817. b = uint8array[dataIndex++];
  65818. if (a > 128) {
  65819. // a run of the same value
  65820. count = a - 128;
  65821. if ((count == 0) || (count > endIndex - index)) {
  65822. throw "HDR Bad Format, bad scanline data (run)";
  65823. }
  65824. while (count-- > 0) {
  65825. scanLineArray[index++] = b;
  65826. }
  65827. }
  65828. else {
  65829. // a non-run
  65830. count = a;
  65831. if ((count == 0) || (count > endIndex - index)) {
  65832. throw "HDR Bad Format, bad scanline data (non-run)";
  65833. }
  65834. scanLineArray[index++] = b;
  65835. if (--count > 0) {
  65836. for (var j = 0; j < count; j++) {
  65837. scanLineArray[index++] = uint8array[dataIndex++];
  65838. }
  65839. }
  65840. }
  65841. }
  65842. }
  65843. // now convert data from buffer into floats
  65844. for (i = 0; i < scanline_width; i++) {
  65845. a = scanLineArray[i];
  65846. b = scanLineArray[i + scanline_width];
  65847. c = scanLineArray[i + 2 * scanline_width];
  65848. d = scanLineArray[i + 3 * scanline_width];
  65849. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65850. }
  65851. num_scanlines--;
  65852. }
  65853. return resultArray;
  65854. };
  65855. return HDRTools;
  65856. }());
  65857. BABYLON.HDRTools = HDRTools;
  65858. })(BABYLON || (BABYLON = {}));
  65859. //# sourceMappingURL=babylon.hdr.js.map
  65860. var BABYLON;
  65861. (function (BABYLON) {
  65862. /**
  65863. * This represents a texture coming from an HDR input.
  65864. *
  65865. * The only supported format is currently panorama picture stored in RGBE format.
  65866. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65867. */
  65868. var HDRCubeTexture = /** @class */ (function (_super) {
  65869. __extends(HDRCubeTexture, _super);
  65870. /**
  65871. * Instantiates an HDRTexture from the following parameters.
  65872. *
  65873. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65874. * @param scene The scene the texture will be used in
  65875. * @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.
  65876. * @param noMipmap Forces to not generate the mipmap if true
  65877. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  65878. * @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)
  65879. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65880. */
  65881. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65882. if (noMipmap === void 0) { noMipmap = false; }
  65883. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65884. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65885. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65886. if (onLoad === void 0) { onLoad = null; }
  65887. if (onError === void 0) { onError = null; }
  65888. var _this = _super.call(this, scene) || this;
  65889. _this._useInGammaSpace = false;
  65890. _this._generateHarmonics = true;
  65891. _this._isBABYLONPreprocessed = false;
  65892. _this._onLoad = null;
  65893. _this._onError = null;
  65894. /**
  65895. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65896. */
  65897. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65898. /**
  65899. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65900. * This is usefull at run time to apply the good shader.
  65901. */
  65902. _this.isPMREM = false;
  65903. _this._isBlocking = true;
  65904. if (!url) {
  65905. return _this;
  65906. }
  65907. _this.name = url;
  65908. _this.url = url;
  65909. _this.hasAlpha = false;
  65910. _this.isCube = true;
  65911. _this._textureMatrix = BABYLON.Matrix.Identity();
  65912. _this._onLoad = onLoad;
  65913. _this._onError = onError;
  65914. _this.gammaSpace = false;
  65915. var caps = scene.getEngine().getCaps();
  65916. if (size) {
  65917. _this._isBABYLONPreprocessed = false;
  65918. _this._noMipmap = noMipmap;
  65919. _this._size = size;
  65920. _this._useInGammaSpace = useInGammaSpace;
  65921. _this._usePMREMGenerator = usePMREMGenerator &&
  65922. caps.textureLOD &&
  65923. caps.textureFloat &&
  65924. !_this._useInGammaSpace;
  65925. }
  65926. else {
  65927. _this._isBABYLONPreprocessed = true;
  65928. _this._noMipmap = false;
  65929. _this._useInGammaSpace = false;
  65930. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65931. !_this._useInGammaSpace;
  65932. }
  65933. _this.isPMREM = _this._usePMREMGenerator;
  65934. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65935. if (!_this._texture) {
  65936. if (!scene.useDelayedTextureLoading) {
  65937. _this.loadTexture();
  65938. }
  65939. else {
  65940. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65941. }
  65942. }
  65943. return _this;
  65944. }
  65945. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65946. /**
  65947. * Gets wether or not the texture is blocking during loading.
  65948. */
  65949. get: function () {
  65950. return this._isBlocking;
  65951. },
  65952. /**
  65953. * Sets wether or not the texture is blocking during loading.
  65954. */
  65955. set: function (value) {
  65956. this._isBlocking = value;
  65957. },
  65958. enumerable: true,
  65959. configurable: true
  65960. });
  65961. /**
  65962. * Occurs when the file is a preprocessed .babylon.hdr file.
  65963. */
  65964. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65965. var _this = this;
  65966. var mipLevels = 0;
  65967. var floatArrayView = null;
  65968. var scene = this.getScene();
  65969. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65970. var mips = new Array();
  65971. if (!floatArrayView) {
  65972. return mips;
  65973. }
  65974. var startIndex = 30;
  65975. for (var level = 0; level < mipLevels; level++) {
  65976. mips.push([]);
  65977. // Fill each pixel of the mip level.
  65978. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65979. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65980. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65981. mips[level].push(faceData);
  65982. startIndex += faceSize;
  65983. }
  65984. }
  65985. return mips;
  65986. } : null;
  65987. var callback = function (buffer) {
  65988. var scene = _this.getScene();
  65989. if (!scene) {
  65990. return null;
  65991. }
  65992. // Create Native Array Views
  65993. var intArrayView = new Int32Array(buffer);
  65994. floatArrayView = new Float32Array(buffer);
  65995. // Fill header.
  65996. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65997. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65998. // Update Texture Information.
  65999. if (!_this._texture) {
  66000. return null;
  66001. }
  66002. _this._texture.updateSize(_this._size, _this._size);
  66003. // Fill polynomial information.
  66004. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  66005. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  66006. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  66007. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  66008. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  66009. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  66010. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  66011. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  66012. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  66013. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  66014. _this.sphericalPolynomial = sphericalPolynomial;
  66015. // Fill pixel data.
  66016. mipLevels = intArrayView[29]; // Number of mip levels.
  66017. var startIndex = 30;
  66018. var data = [];
  66019. var faceSize = Math.pow(_this._size, 2) * 3;
  66020. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  66021. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  66022. startIndex += faceSize;
  66023. }
  66024. var results = [];
  66025. var byteArray = null;
  66026. // Push each faces.
  66027. for (var k = 0; k < 6; k++) {
  66028. var dataFace = null;
  66029. // To be deprecated.
  66030. if (version === 1) {
  66031. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  66032. dataFace = data[j];
  66033. }
  66034. // If special cases.
  66035. if (!mipmapGenerator && dataFace) {
  66036. if (!scene.getEngine().getCaps().textureFloat) {
  66037. // 3 channels of 1 bytes per pixel in bytes.
  66038. var byteBuffer = new ArrayBuffer(faceSize);
  66039. byteArray = new Uint8Array(byteBuffer);
  66040. }
  66041. for (var i = 0; i < _this._size * _this._size; i++) {
  66042. // Put in gamma space if requested.
  66043. if (_this._useInGammaSpace) {
  66044. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  66045. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  66046. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  66047. }
  66048. // Convert to int texture for fallback.
  66049. if (byteArray) {
  66050. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66051. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66052. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66053. // May use luminance instead if the result is not accurate.
  66054. var max = Math.max(Math.max(r, g), b);
  66055. if (max > 255) {
  66056. var scale = 255 / max;
  66057. r *= scale;
  66058. g *= scale;
  66059. b *= scale;
  66060. }
  66061. byteArray[(i * 3) + 0] = r;
  66062. byteArray[(i * 3) + 1] = g;
  66063. byteArray[(i * 3) + 2] = b;
  66064. }
  66065. }
  66066. }
  66067. // Fill the array accordingly.
  66068. if (byteArray) {
  66069. results.push(byteArray);
  66070. }
  66071. else {
  66072. results.push(dataFace);
  66073. }
  66074. }
  66075. return results;
  66076. };
  66077. if (scene) {
  66078. 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);
  66079. }
  66080. };
  66081. /**
  66082. * Occurs when the file is raw .hdr file.
  66083. */
  66084. HDRCubeTexture.prototype.loadHDRTexture = function () {
  66085. var _this = this;
  66086. var callback = function (buffer) {
  66087. var scene = _this.getScene();
  66088. if (!scene) {
  66089. return null;
  66090. }
  66091. // Extract the raw linear data.
  66092. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  66093. // Generate harmonics if needed.
  66094. if (_this._generateHarmonics) {
  66095. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  66096. _this.sphericalPolynomial = sphericalPolynomial;
  66097. }
  66098. var results = [];
  66099. var byteArray = null;
  66100. // Push each faces.
  66101. for (var j = 0; j < 6; j++) {
  66102. // Create uintarray fallback.
  66103. if (!scene.getEngine().getCaps().textureFloat) {
  66104. // 3 channels of 1 bytes per pixel in bytes.
  66105. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  66106. byteArray = new Uint8Array(byteBuffer);
  66107. }
  66108. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  66109. // If special cases.
  66110. if (_this._useInGammaSpace || byteArray) {
  66111. for (var i = 0; i < _this._size * _this._size; i++) {
  66112. // Put in gamma space if requested.
  66113. if (_this._useInGammaSpace) {
  66114. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  66115. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  66116. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  66117. }
  66118. // Convert to int texture for fallback.
  66119. if (byteArray) {
  66120. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66121. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66122. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66123. // May use luminance instead if the result is not accurate.
  66124. var max = Math.max(Math.max(r, g), b);
  66125. if (max > 255) {
  66126. var scale = 255 / max;
  66127. r *= scale;
  66128. g *= scale;
  66129. b *= scale;
  66130. }
  66131. byteArray[(i * 3) + 0] = r;
  66132. byteArray[(i * 3) + 1] = g;
  66133. byteArray[(i * 3) + 2] = b;
  66134. }
  66135. }
  66136. }
  66137. if (byteArray) {
  66138. results.push(byteArray);
  66139. }
  66140. else {
  66141. results.push(dataFace);
  66142. }
  66143. }
  66144. return results;
  66145. };
  66146. var mipmapGenerator = null;
  66147. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66148. // if (!this._noMipmap &&
  66149. // this._usePMREMGenerator) {
  66150. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66151. // // Custom setup of the generator matching with the PBR shader values.
  66152. // var generator = new BABYLON.PMREMGenerator(data,
  66153. // this._size,
  66154. // this._size,
  66155. // 0,
  66156. // 3,
  66157. // this.getScene().getEngine().getCaps().textureFloat,
  66158. // 2048,
  66159. // 0.25,
  66160. // false,
  66161. // true);
  66162. // return generator.filterCubeMap();
  66163. // };
  66164. // }
  66165. var scene = this.getScene();
  66166. if (scene) {
  66167. 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);
  66168. }
  66169. };
  66170. /**
  66171. * Starts the loading process of the texture.
  66172. */
  66173. HDRCubeTexture.prototype.loadTexture = function () {
  66174. if (this._isBABYLONPreprocessed) {
  66175. this.loadBabylonTexture();
  66176. }
  66177. else {
  66178. this.loadHDRTexture();
  66179. }
  66180. };
  66181. HDRCubeTexture.prototype.clone = function () {
  66182. var scene = this.getScene();
  66183. if (!scene) {
  66184. return this;
  66185. }
  66186. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66187. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66188. // Base texture
  66189. newTexture.level = this.level;
  66190. newTexture.wrapU = this.wrapU;
  66191. newTexture.wrapV = this.wrapV;
  66192. newTexture.coordinatesIndex = this.coordinatesIndex;
  66193. newTexture.coordinatesMode = this.coordinatesMode;
  66194. return newTexture;
  66195. };
  66196. // Methods
  66197. HDRCubeTexture.prototype.delayLoad = function () {
  66198. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66199. return;
  66200. }
  66201. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66202. this._texture = this._getFromCache(this.url, this._noMipmap);
  66203. if (!this._texture) {
  66204. this.loadTexture();
  66205. }
  66206. };
  66207. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66208. return this._textureMatrix;
  66209. };
  66210. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66211. this._textureMatrix = value;
  66212. };
  66213. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66214. var texture = null;
  66215. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66216. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66217. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66218. texture.name = parsedTexture.name;
  66219. texture.hasAlpha = parsedTexture.hasAlpha;
  66220. texture.level = parsedTexture.level;
  66221. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66222. texture.isBlocking = parsedTexture.isBlocking;
  66223. }
  66224. return texture;
  66225. };
  66226. HDRCubeTexture.prototype.serialize = function () {
  66227. if (!this.name) {
  66228. return null;
  66229. }
  66230. var serializationObject = {};
  66231. serializationObject.name = this.name;
  66232. serializationObject.hasAlpha = this.hasAlpha;
  66233. serializationObject.isCube = true;
  66234. serializationObject.level = this.level;
  66235. serializationObject.size = this._size;
  66236. serializationObject.coordinatesMode = this.coordinatesMode;
  66237. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66238. serializationObject.generateHarmonics = this._generateHarmonics;
  66239. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66240. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66241. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66242. serializationObject.noMipmap = this._noMipmap;
  66243. serializationObject.isBlocking = this._isBlocking;
  66244. return serializationObject;
  66245. };
  66246. /**
  66247. * Saves as a file the data contained in the texture in a binary format.
  66248. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66249. * as the spherical used in the lighting.
  66250. * @param url The HDR file url.
  66251. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66252. * @param onError Method called if any error happens during download.
  66253. * @return The packed binary data.
  66254. */
  66255. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66256. if (onError === void 0) { onError = null; }
  66257. var callback = function (buffer) {
  66258. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66259. // Returns a URL you can use as a href.
  66260. var objUrl = window.URL.createObjectURL(data);
  66261. // Simulates a link to it and click to dowload.
  66262. var a = document.createElement("a");
  66263. document.body.appendChild(a);
  66264. a.style.display = "none";
  66265. a.href = objUrl;
  66266. a.download = "envmap.babylon.hdr";
  66267. a.click();
  66268. };
  66269. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66270. };
  66271. /**
  66272. * Serializes the data contained in the texture in a binary format.
  66273. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66274. * as the spherical used in the lighting.
  66275. * @param url The HDR file url.
  66276. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66277. * @param onError Method called if any error happens during download.
  66278. * @return The packed binary data.
  66279. */
  66280. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66281. if (onError === void 0) { onError = null; }
  66282. // Needs the url tho create the texture.
  66283. if (!url) {
  66284. return;
  66285. }
  66286. // Check Power of two size.
  66287. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66288. return;
  66289. }
  66290. // Coming Back in 3.x.
  66291. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66292. };
  66293. HDRCubeTexture._facesMapping = [
  66294. "right",
  66295. "left",
  66296. "up",
  66297. "down",
  66298. "front",
  66299. "back"
  66300. ];
  66301. return HDRCubeTexture;
  66302. }(BABYLON.BaseTexture));
  66303. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66304. })(BABYLON || (BABYLON = {}));
  66305. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66306. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66307. // Huge respect for a such great lib.
  66308. // Earcut license:
  66309. // Copyright (c) 2016, Mapbox
  66310. //
  66311. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66312. // with or without fee is hereby granted, provided that the above copyright notice
  66313. // and this permission notice appear in all copies.
  66314. //
  66315. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66316. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66317. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66318. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66319. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66320. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66321. // THIS SOFTWARE.
  66322. var Earcut;
  66323. (function (Earcut) {
  66324. /**
  66325. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66326. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66327. * @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).
  66328. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66329. */
  66330. function earcut(data, holeIndices, dim) {
  66331. dim = dim || 2;
  66332. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66333. if (!outerNode)
  66334. return triangles;
  66335. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66336. if (hasHoles)
  66337. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66338. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66339. if (data.length > 80 * dim) {
  66340. minX = maxX = data[0];
  66341. minY = maxY = data[1];
  66342. for (var i = dim; i < outerLen; i += dim) {
  66343. x = data[i];
  66344. y = data[i + 1];
  66345. if (x < minX)
  66346. minX = x;
  66347. if (y < minY)
  66348. minY = y;
  66349. if (x > maxX)
  66350. maxX = x;
  66351. if (y > maxY)
  66352. maxY = y;
  66353. }
  66354. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66355. size = Math.max(maxX - minX, maxY - minY);
  66356. }
  66357. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66358. return triangles;
  66359. }
  66360. Earcut.earcut = earcut;
  66361. var Node = /** @class */ (function () {
  66362. function Node(i, x, y) {
  66363. this.i = i;
  66364. this.x = x;
  66365. this.y = y;
  66366. this.prev = null;
  66367. this.next = null;
  66368. this.z = null;
  66369. this.prevZ = null;
  66370. this.nextZ = null;
  66371. this.steiner = false;
  66372. }
  66373. return Node;
  66374. }());
  66375. // create a circular doubly linked list from polygon points in the specified winding order
  66376. function linkedList(data, start, end, dim, clockwise) {
  66377. var i, last = null;
  66378. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66379. for (i = start; i < end; i += dim)
  66380. last = insertNode(i, data[i], data[i + 1], last);
  66381. }
  66382. else {
  66383. for (i = end - dim; i >= start; i -= dim)
  66384. last = insertNode(i, data[i], data[i + 1], last);
  66385. }
  66386. if (last && equals(last, last.next)) {
  66387. removeNode(last);
  66388. last = last.next;
  66389. }
  66390. return last;
  66391. }
  66392. // eliminate colinear or duplicate points
  66393. function filterPoints(start, end) {
  66394. if (!start)
  66395. return start;
  66396. if (!end)
  66397. end = start;
  66398. var p = start, again;
  66399. do {
  66400. again = false;
  66401. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66402. removeNode(p);
  66403. p = end = p.prev;
  66404. if (p === p.next)
  66405. return undefined;
  66406. again = true;
  66407. }
  66408. else {
  66409. p = p.next;
  66410. }
  66411. } while (again || p !== end);
  66412. return end;
  66413. }
  66414. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66415. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66416. if (!ear)
  66417. return;
  66418. // interlink polygon nodes in z-order
  66419. if (!pass && size)
  66420. indexCurve(ear, minX, minY, size);
  66421. var stop = ear, prev, next;
  66422. // iterate through ears, slicing them one by one
  66423. while (ear.prev !== ear.next) {
  66424. prev = ear.prev;
  66425. next = ear.next;
  66426. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66427. // cut off the triangle
  66428. triangles.push(prev.i / dim);
  66429. triangles.push(ear.i / dim);
  66430. triangles.push(next.i / dim);
  66431. removeNode(ear);
  66432. // skipping the next vertice leads to less sliver triangles
  66433. ear = next.next;
  66434. stop = next.next;
  66435. continue;
  66436. }
  66437. ear = next;
  66438. // if we looped through the whole remaining polygon and can't find any more ears
  66439. if (ear === stop) {
  66440. // try filtering points and slicing again
  66441. if (!pass) {
  66442. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66443. // if this didn't work, try curing all small self-intersections locally
  66444. }
  66445. else if (pass === 1) {
  66446. ear = cureLocalIntersections(ear, triangles, dim);
  66447. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66448. // as a last resort, try splitting the remaining polygon into two
  66449. }
  66450. else if (pass === 2) {
  66451. splitEarcut(ear, triangles, dim, minX, minY, size);
  66452. }
  66453. break;
  66454. }
  66455. }
  66456. }
  66457. // check whether a polygon node forms a valid ear with adjacent nodes
  66458. function isEar(ear) {
  66459. var a = ear.prev, b = ear, c = ear.next;
  66460. if (area(a, b, c) >= 0)
  66461. return false; // reflex, can't be an ear
  66462. // now make sure we don't have other points inside the potential ear
  66463. var p = ear.next.next;
  66464. while (p !== ear.prev) {
  66465. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66466. area(p.prev, p, p.next) >= 0)
  66467. return false;
  66468. p = p.next;
  66469. }
  66470. return true;
  66471. }
  66472. function isEarHashed(ear, minX, minY, size) {
  66473. var a = ear.prev, b = ear, c = ear.next;
  66474. if (area(a, b, c) >= 0)
  66475. return false; // reflex, can't be an ear
  66476. // triangle bbox; min & max are calculated like this for speed
  66477. 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);
  66478. // z-order range for the current triangle bbox;
  66479. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66480. // first look for points inside the triangle in increasing z-order
  66481. var p = ear.nextZ;
  66482. while (p && p.z <= maxZ) {
  66483. if (p !== ear.prev &&
  66484. p !== ear.next &&
  66485. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66486. area(p.prev, p, p.next) >= 0)
  66487. return false;
  66488. p = p.nextZ;
  66489. }
  66490. // then look for points in decreasing z-order
  66491. p = ear.prevZ;
  66492. while (p && p.z >= minZ) {
  66493. if (p !== ear.prev &&
  66494. p !== ear.next &&
  66495. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66496. area(p.prev, p, p.next) >= 0)
  66497. return false;
  66498. p = p.prevZ;
  66499. }
  66500. return true;
  66501. }
  66502. // go through all polygon nodes and cure small local self-intersections
  66503. function cureLocalIntersections(start, triangles, dim) {
  66504. var p = start;
  66505. do {
  66506. var a = p.prev, b = p.next.next;
  66507. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66508. triangles.push(a.i / dim);
  66509. triangles.push(p.i / dim);
  66510. triangles.push(b.i / dim);
  66511. // remove two nodes involved
  66512. removeNode(p);
  66513. removeNode(p.next);
  66514. p = start = b;
  66515. }
  66516. p = p.next;
  66517. } while (p !== start);
  66518. return p;
  66519. }
  66520. // try splitting polygon into two and triangulate them independently
  66521. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66522. // look for a valid diagonal that divides the polygon into two
  66523. var a = start;
  66524. do {
  66525. var b = a.next.next;
  66526. while (b !== a.prev) {
  66527. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66528. // split the polygon in two by the diagonal
  66529. var c = splitPolygon(a, b);
  66530. // filter colinear points around the cuts
  66531. a = filterPoints(a, a.next);
  66532. c = filterPoints(c, c.next);
  66533. // run earcut on each half
  66534. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66535. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66536. return;
  66537. }
  66538. b = b.next;
  66539. }
  66540. a = a.next;
  66541. } while (a !== start);
  66542. }
  66543. // link every hole into the outer loop, producing a single-ring polygon without holes
  66544. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66545. var queue = [], i, len, start, end, list;
  66546. for (i = 0, len = holeIndices.length; i < len; i++) {
  66547. start = holeIndices[i] * dim;
  66548. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66549. list = linkedList(data, start, end, dim, false);
  66550. if (list === list.next)
  66551. list.steiner = true;
  66552. queue.push(getLeftmost(list));
  66553. }
  66554. queue.sort(compareX);
  66555. // process holes from left to right
  66556. for (i = 0; i < queue.length; i++) {
  66557. eliminateHole(queue[i], outerNode);
  66558. outerNode = filterPoints(outerNode, outerNode.next);
  66559. }
  66560. return outerNode;
  66561. }
  66562. function compareX(a, b) {
  66563. return a.x - b.x;
  66564. }
  66565. // find a bridge between vertices that connects hole with an outer ring and and link it
  66566. function eliminateHole(hole, outerNode) {
  66567. outerNode = findHoleBridge(hole, outerNode);
  66568. if (outerNode) {
  66569. var b = splitPolygon(outerNode, hole);
  66570. filterPoints(b, b.next);
  66571. }
  66572. }
  66573. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66574. function findHoleBridge(hole, outerNode) {
  66575. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66576. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66577. // segment's endpoint with lesser x will be potential connection point
  66578. do {
  66579. if (hy <= p.y && hy >= p.next.y) {
  66580. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66581. if (x <= hx && x > qx) {
  66582. qx = x;
  66583. if (x === hx) {
  66584. if (hy === p.y)
  66585. return p;
  66586. if (hy === p.next.y)
  66587. return p.next;
  66588. }
  66589. m = p.x < p.next.x ? p : p.next;
  66590. }
  66591. }
  66592. p = p.next;
  66593. } while (p !== outerNode);
  66594. if (!m)
  66595. return null;
  66596. if (hx === qx)
  66597. return m.prev; // hole touches outer segment; pick lower endpoint
  66598. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66599. // if there are no points found, we have a valid connection;
  66600. // otherwise choose the point of the minimum angle with the ray as connection point
  66601. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66602. p = m.next;
  66603. while (p !== stop) {
  66604. if (hx >= p.x &&
  66605. p.x >= mx &&
  66606. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66607. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66608. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66609. m = p;
  66610. tanMin = tan;
  66611. }
  66612. }
  66613. p = p.next;
  66614. }
  66615. return m;
  66616. }
  66617. // interlink polygon nodes in z-order
  66618. function indexCurve(start, minX, minY, size) {
  66619. var p = start;
  66620. do {
  66621. if (p.z === null)
  66622. p.z = zOrder(p.x, p.y, minX, minY, size);
  66623. p.prevZ = p.prev;
  66624. p.nextZ = p.next;
  66625. p = p.next;
  66626. } while (p !== start);
  66627. p.prevZ.nextZ = null;
  66628. p.prevZ = null;
  66629. sortLinked(p);
  66630. }
  66631. // Simon Tatham's linked list merge sort algorithm
  66632. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66633. function sortLinked(list) {
  66634. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66635. do {
  66636. p = list;
  66637. list = null;
  66638. tail = null;
  66639. numMerges = 0;
  66640. while (p) {
  66641. numMerges++;
  66642. q = p;
  66643. pSize = 0;
  66644. for (i = 0; i < inSize; i++) {
  66645. pSize++;
  66646. q = q.nextZ;
  66647. if (!q)
  66648. break;
  66649. }
  66650. qSize = inSize;
  66651. while (pSize > 0 || (qSize > 0 && q)) {
  66652. if (pSize === 0) {
  66653. e = q;
  66654. q = q.nextZ;
  66655. qSize--;
  66656. }
  66657. else if (qSize === 0 || !q) {
  66658. e = p;
  66659. p = p.nextZ;
  66660. pSize--;
  66661. }
  66662. else if (p.z <= q.z) {
  66663. e = p;
  66664. p = p.nextZ;
  66665. pSize--;
  66666. }
  66667. else {
  66668. e = q;
  66669. q = q.nextZ;
  66670. qSize--;
  66671. }
  66672. if (tail)
  66673. tail.nextZ = e;
  66674. else
  66675. list = e;
  66676. e.prevZ = tail;
  66677. tail = e;
  66678. }
  66679. p = q;
  66680. }
  66681. tail.nextZ = null;
  66682. inSize *= 2;
  66683. } while (numMerges > 1);
  66684. return list;
  66685. }
  66686. // z-order of a point given coords and size of the data bounding box
  66687. function zOrder(x, y, minX, minY, size) {
  66688. // coords are transformed into non-negative 15-bit integer range
  66689. x = 32767 * (x - minX) / size;
  66690. y = 32767 * (y - minY) / size;
  66691. x = (x | (x << 8)) & 0x00FF00FF;
  66692. x = (x | (x << 4)) & 0x0F0F0F0F;
  66693. x = (x | (x << 2)) & 0x33333333;
  66694. x = (x | (x << 1)) & 0x55555555;
  66695. y = (y | (y << 8)) & 0x00FF00FF;
  66696. y = (y | (y << 4)) & 0x0F0F0F0F;
  66697. y = (y | (y << 2)) & 0x33333333;
  66698. y = (y | (y << 1)) & 0x55555555;
  66699. return x | (y << 1);
  66700. }
  66701. // find the leftmost node of a polygon ring
  66702. function getLeftmost(start) {
  66703. var p = start, leftmost = start;
  66704. do {
  66705. if (p.x < leftmost.x)
  66706. leftmost = p;
  66707. p = p.next;
  66708. } while (p !== start);
  66709. return leftmost;
  66710. }
  66711. // check if a point lies within a convex triangle
  66712. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66713. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66714. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66715. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66716. }
  66717. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66718. function isValidDiagonal(a, b) {
  66719. return a.next.i !== b.i &&
  66720. a.prev.i !== b.i &&
  66721. !intersectsPolygon(a, b) &&
  66722. locallyInside(a, b) &&
  66723. locallyInside(b, a) &&
  66724. middleInside(a, b);
  66725. }
  66726. // signed area of a triangle
  66727. function area(p, q, r) {
  66728. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66729. }
  66730. // check if two points are equal
  66731. function equals(p1, p2) {
  66732. return p1.x === p2.x && p1.y === p2.y;
  66733. }
  66734. // check if two segments intersect
  66735. function intersects(p1, q1, p2, q2) {
  66736. if ((equals(p1, q1) && equals(p2, q2)) ||
  66737. (equals(p1, q2) && equals(p2, q1)))
  66738. return true;
  66739. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66740. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66741. }
  66742. // check if a polygon diagonal intersects any polygon segments
  66743. function intersectsPolygon(a, b) {
  66744. var p = a;
  66745. do {
  66746. if (p.i !== a.i &&
  66747. p.next.i !== a.i &&
  66748. p.i !== b.i &&
  66749. p.next.i !== b.i &&
  66750. intersects(p, p.next, a, b))
  66751. return true;
  66752. p = p.next;
  66753. } while (p !== a);
  66754. return false;
  66755. }
  66756. // check if a polygon diagonal is locally inside the polygon
  66757. function locallyInside(a, b) {
  66758. return area(a.prev, a, a.next) < 0
  66759. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66760. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66761. }
  66762. // check if the middle point of a polygon diagonal is inside the polygon
  66763. function middleInside(a, b) {
  66764. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66765. do {
  66766. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66767. inside = !inside;
  66768. p = p.next;
  66769. } while (p !== a);
  66770. return inside;
  66771. }
  66772. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66773. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66774. function splitPolygon(a, b) {
  66775. 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;
  66776. a.next = b;
  66777. b.prev = a;
  66778. a2.next = an;
  66779. an.prev = a2;
  66780. b2.next = a2;
  66781. a2.prev = b2;
  66782. bp.next = b2;
  66783. b2.prev = bp;
  66784. return b2;
  66785. }
  66786. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66787. function insertNode(i, x, y, last) {
  66788. var p = new Node(i, x, y);
  66789. if (!last) {
  66790. p.prev = p;
  66791. p.next = p;
  66792. }
  66793. else {
  66794. p.next = last.next;
  66795. p.prev = last;
  66796. last.next.prev = p;
  66797. last.next = p;
  66798. }
  66799. return p;
  66800. }
  66801. function removeNode(p) {
  66802. p.next.prev = p.prev;
  66803. p.prev.next = p.next;
  66804. if (p.prevZ)
  66805. p.prevZ.nextZ = p.nextZ;
  66806. if (p.nextZ)
  66807. p.nextZ.prevZ = p.prevZ;
  66808. }
  66809. /**
  66810. * return a percentage difference between the polygon area and its triangulation area;
  66811. * used to verify correctness of triangulation
  66812. */
  66813. function deviation(data, holeIndices, dim, triangles) {
  66814. var hasHoles = holeIndices && holeIndices.length;
  66815. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66816. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66817. if (hasHoles) {
  66818. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66819. var start = holeIndices[i] * dim;
  66820. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66821. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66822. }
  66823. }
  66824. var trianglesArea = 0;
  66825. for (i = 0; i < triangles.length; i += 3) {
  66826. var a = triangles[i] * dim;
  66827. var b = triangles[i + 1] * dim;
  66828. var c = triangles[i + 2] * dim;
  66829. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66830. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66831. }
  66832. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66833. }
  66834. Earcut.deviation = deviation;
  66835. ;
  66836. function signedArea(data, start, end, dim) {
  66837. var sum = 0;
  66838. for (var i = start, j = end - dim; i < end; i += dim) {
  66839. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66840. j = i;
  66841. }
  66842. return sum;
  66843. }
  66844. /**
  66845. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66846. */
  66847. function flatten(data) {
  66848. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66849. for (var i = 0; i < data.length; i++) {
  66850. for (var j = 0; j < data[i].length; j++) {
  66851. for (var d = 0; d < dim; d++)
  66852. result.vertices.push(data[i][j][d]);
  66853. }
  66854. if (i > 0) {
  66855. holeIndex += data[i - 1].length;
  66856. result.holes.push(holeIndex);
  66857. }
  66858. }
  66859. return result;
  66860. }
  66861. Earcut.flatten = flatten;
  66862. ;
  66863. })(Earcut || (Earcut = {}));
  66864. //# sourceMappingURL=babylon.earcut.js.map
  66865. var BABYLON;
  66866. (function (BABYLON) {
  66867. var IndexedVector2 = /** @class */ (function (_super) {
  66868. __extends(IndexedVector2, _super);
  66869. function IndexedVector2(original, index) {
  66870. var _this = _super.call(this, original.x, original.y) || this;
  66871. _this.index = index;
  66872. return _this;
  66873. }
  66874. return IndexedVector2;
  66875. }(BABYLON.Vector2));
  66876. var PolygonPoints = /** @class */ (function () {
  66877. function PolygonPoints() {
  66878. this.elements = new Array();
  66879. }
  66880. PolygonPoints.prototype.add = function (originalPoints) {
  66881. var _this = this;
  66882. var result = new Array();
  66883. originalPoints.forEach(function (point) {
  66884. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66885. var newPoint = new IndexedVector2(point, _this.elements.length);
  66886. result.push(newPoint);
  66887. _this.elements.push(newPoint);
  66888. }
  66889. });
  66890. return result;
  66891. };
  66892. PolygonPoints.prototype.computeBounds = function () {
  66893. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66894. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66895. this.elements.forEach(function (point) {
  66896. // x
  66897. if (point.x < lmin.x) {
  66898. lmin.x = point.x;
  66899. }
  66900. else if (point.x > lmax.x) {
  66901. lmax.x = point.x;
  66902. }
  66903. // y
  66904. if (point.y < lmin.y) {
  66905. lmin.y = point.y;
  66906. }
  66907. else if (point.y > lmax.y) {
  66908. lmax.y = point.y;
  66909. }
  66910. });
  66911. return {
  66912. min: lmin,
  66913. max: lmax,
  66914. width: lmax.x - lmin.x,
  66915. height: lmax.y - lmin.y
  66916. };
  66917. };
  66918. return PolygonPoints;
  66919. }());
  66920. var Polygon = /** @class */ (function () {
  66921. function Polygon() {
  66922. }
  66923. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66924. return [
  66925. new BABYLON.Vector2(xmin, ymin),
  66926. new BABYLON.Vector2(xmax, ymin),
  66927. new BABYLON.Vector2(xmax, ymax),
  66928. new BABYLON.Vector2(xmin, ymax)
  66929. ];
  66930. };
  66931. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66932. if (cx === void 0) { cx = 0; }
  66933. if (cy === void 0) { cy = 0; }
  66934. if (numberOfSides === void 0) { numberOfSides = 32; }
  66935. var result = new Array();
  66936. var angle = 0;
  66937. var increment = (Math.PI * 2) / numberOfSides;
  66938. for (var i = 0; i < numberOfSides; i++) {
  66939. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66940. angle -= increment;
  66941. }
  66942. return result;
  66943. };
  66944. Polygon.Parse = function (input) {
  66945. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66946. var i, result = [];
  66947. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66948. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66949. }
  66950. return result;
  66951. };
  66952. Polygon.StartingAt = function (x, y) {
  66953. return BABYLON.Path2.StartingAt(x, y);
  66954. };
  66955. return Polygon;
  66956. }());
  66957. BABYLON.Polygon = Polygon;
  66958. var PolygonMeshBuilder = /** @class */ (function () {
  66959. function PolygonMeshBuilder(name, contours, scene) {
  66960. this._points = new PolygonPoints();
  66961. this._outlinepoints = new PolygonPoints();
  66962. this._holes = new Array();
  66963. this._epoints = new Array();
  66964. this._eholes = new Array();
  66965. this._name = name;
  66966. this._scene = scene;
  66967. var points;
  66968. if (contours instanceof BABYLON.Path2) {
  66969. points = contours.getPoints();
  66970. }
  66971. else {
  66972. points = contours;
  66973. }
  66974. this._addToepoint(points);
  66975. this._points.add(points);
  66976. this._outlinepoints.add(points);
  66977. }
  66978. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66979. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66980. var p = points_1[_i];
  66981. this._epoints.push(p.x, p.y);
  66982. }
  66983. };
  66984. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66985. this._points.add(hole);
  66986. var holepoints = new PolygonPoints();
  66987. holepoints.add(hole);
  66988. this._holes.push(holepoints);
  66989. this._eholes.push(this._epoints.length / 2);
  66990. this._addToepoint(hole);
  66991. return this;
  66992. };
  66993. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66994. var _this = this;
  66995. if (updatable === void 0) { updatable = false; }
  66996. if (depth === void 0) { depth = 0; }
  66997. var result = new BABYLON.Mesh(this._name, this._scene);
  66998. var normals = new Array();
  66999. var positions = new Array();
  67000. var uvs = new Array();
  67001. var bounds = this._points.computeBounds();
  67002. this._points.elements.forEach(function (p) {
  67003. normals.push(0, 1.0, 0);
  67004. positions.push(p.x, 0, p.y);
  67005. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  67006. });
  67007. var indices = new Array();
  67008. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  67009. for (var i = 0; i < res.length; i++) {
  67010. indices.push(res[i]);
  67011. }
  67012. if (depth > 0) {
  67013. var positionscount = (positions.length / 3); //get the current pointcount
  67014. this._points.elements.forEach(function (p) {
  67015. normals.push(0, -1.0, 0);
  67016. positions.push(p.x, -depth, p.y);
  67017. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  67018. });
  67019. var totalCount = indices.length;
  67020. for (var i = 0; i < totalCount; i += 3) {
  67021. var i0 = indices[i + 0];
  67022. var i1 = indices[i + 1];
  67023. var i2 = indices[i + 2];
  67024. indices.push(i2 + positionscount);
  67025. indices.push(i1 + positionscount);
  67026. indices.push(i0 + positionscount);
  67027. }
  67028. //Add the sides
  67029. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  67030. this._holes.forEach(function (hole) {
  67031. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  67032. });
  67033. }
  67034. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  67035. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  67036. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  67037. result.setIndices(indices);
  67038. return result;
  67039. };
  67040. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  67041. var StartIndex = positions.length / 3;
  67042. var ulength = 0;
  67043. for (var i = 0; i < points.elements.length; i++) {
  67044. var p = points.elements[i];
  67045. var p1;
  67046. if ((i + 1) > points.elements.length - 1) {
  67047. p1 = points.elements[0];
  67048. }
  67049. else {
  67050. p1 = points.elements[i + 1];
  67051. }
  67052. positions.push(p.x, 0, p.y);
  67053. positions.push(p.x, -depth, p.y);
  67054. positions.push(p1.x, 0, p1.y);
  67055. positions.push(p1.x, -depth, p1.y);
  67056. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  67057. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  67058. var v3 = v2.subtract(v1);
  67059. var v4 = new BABYLON.Vector3(0, 1, 0);
  67060. var vn = BABYLON.Vector3.Cross(v3, v4);
  67061. vn = vn.normalize();
  67062. uvs.push(ulength / bounds.width, 0);
  67063. uvs.push(ulength / bounds.width, 1);
  67064. ulength += v3.length();
  67065. uvs.push((ulength / bounds.width), 0);
  67066. uvs.push((ulength / bounds.width), 1);
  67067. if (!flip) {
  67068. normals.push(-vn.x, -vn.y, -vn.z);
  67069. normals.push(-vn.x, -vn.y, -vn.z);
  67070. normals.push(-vn.x, -vn.y, -vn.z);
  67071. normals.push(-vn.x, -vn.y, -vn.z);
  67072. indices.push(StartIndex);
  67073. indices.push(StartIndex + 1);
  67074. indices.push(StartIndex + 2);
  67075. indices.push(StartIndex + 1);
  67076. indices.push(StartIndex + 3);
  67077. indices.push(StartIndex + 2);
  67078. }
  67079. else {
  67080. normals.push(vn.x, vn.y, vn.z);
  67081. normals.push(vn.x, vn.y, vn.z);
  67082. normals.push(vn.x, vn.y, vn.z);
  67083. normals.push(vn.x, vn.y, vn.z);
  67084. indices.push(StartIndex);
  67085. indices.push(StartIndex + 2);
  67086. indices.push(StartIndex + 1);
  67087. indices.push(StartIndex + 1);
  67088. indices.push(StartIndex + 2);
  67089. indices.push(StartIndex + 3);
  67090. }
  67091. StartIndex += 4;
  67092. }
  67093. ;
  67094. };
  67095. return PolygonMeshBuilder;
  67096. }());
  67097. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  67098. })(BABYLON || (BABYLON = {}));
  67099. //# sourceMappingURL=babylon.polygonMesh.js.map
  67100. var BABYLON;
  67101. (function (BABYLON) {
  67102. // Unique ID when we import meshes from Babylon to CSG
  67103. var currentCSGMeshId = 0;
  67104. // # class Vertex
  67105. // Represents a vertex of a polygon. Use your own vertex class instead of this
  67106. // one to provide additional features like texture coordinates and vertex
  67107. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  67108. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  67109. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  67110. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  67111. // is not used anywhere else.
  67112. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  67113. var Vertex = /** @class */ (function () {
  67114. function Vertex(pos, normal, uv) {
  67115. this.pos = pos;
  67116. this.normal = normal;
  67117. this.uv = uv;
  67118. }
  67119. Vertex.prototype.clone = function () {
  67120. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  67121. };
  67122. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  67123. // orientation of a polygon is flipped.
  67124. Vertex.prototype.flip = function () {
  67125. this.normal = this.normal.scale(-1);
  67126. };
  67127. // Create a new vertex between this vertex and `other` by linearly
  67128. // interpolating all properties using a parameter of `t`. Subclasses should
  67129. // override this to interpolate additional properties.
  67130. Vertex.prototype.interpolate = function (other, t) {
  67131. 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));
  67132. };
  67133. return Vertex;
  67134. }());
  67135. // # class Plane
  67136. // Represents a plane in 3D space.
  67137. var Plane = /** @class */ (function () {
  67138. function Plane(normal, w) {
  67139. this.normal = normal;
  67140. this.w = w;
  67141. }
  67142. Plane.FromPoints = function (a, b, c) {
  67143. var v0 = c.subtract(a);
  67144. var v1 = b.subtract(a);
  67145. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  67146. return null;
  67147. }
  67148. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67149. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67150. };
  67151. Plane.prototype.clone = function () {
  67152. return new Plane(this.normal.clone(), this.w);
  67153. };
  67154. Plane.prototype.flip = function () {
  67155. this.normal.scaleInPlace(-1);
  67156. this.w = -this.w;
  67157. };
  67158. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67159. // fragments in the appropriate lists. Coplanar polygons go into either
  67160. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67161. // respect to this plane. Polygons in front or in back of this plane go into
  67162. // either `front` or `back`.
  67163. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67164. var COPLANAR = 0;
  67165. var FRONT = 1;
  67166. var BACK = 2;
  67167. var SPANNING = 3;
  67168. // Classify each point as well as the entire polygon into one of the above
  67169. // four classes.
  67170. var polygonType = 0;
  67171. var types = [];
  67172. var i;
  67173. var t;
  67174. for (i = 0; i < polygon.vertices.length; i++) {
  67175. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67176. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67177. polygonType |= type;
  67178. types.push(type);
  67179. }
  67180. // Put the polygon in the correct list, splitting it when necessary.
  67181. switch (polygonType) {
  67182. case COPLANAR:
  67183. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67184. break;
  67185. case FRONT:
  67186. front.push(polygon);
  67187. break;
  67188. case BACK:
  67189. back.push(polygon);
  67190. break;
  67191. case SPANNING:
  67192. var f = [], b = [];
  67193. for (i = 0; i < polygon.vertices.length; i++) {
  67194. var j = (i + 1) % polygon.vertices.length;
  67195. var ti = types[i], tj = types[j];
  67196. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67197. if (ti !== BACK)
  67198. f.push(vi);
  67199. if (ti !== FRONT)
  67200. b.push(ti !== BACK ? vi.clone() : vi);
  67201. if ((ti | tj) === SPANNING) {
  67202. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67203. var v = vi.interpolate(vj, t);
  67204. f.push(v);
  67205. b.push(v.clone());
  67206. }
  67207. }
  67208. var poly;
  67209. if (f.length >= 3) {
  67210. poly = new Polygon(f, polygon.shared);
  67211. if (poly.plane)
  67212. front.push(poly);
  67213. }
  67214. if (b.length >= 3) {
  67215. poly = new Polygon(b, polygon.shared);
  67216. if (poly.plane)
  67217. back.push(poly);
  67218. }
  67219. break;
  67220. }
  67221. };
  67222. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67223. // point is on the plane.
  67224. Plane.EPSILON = 1e-5;
  67225. return Plane;
  67226. }());
  67227. // # class Polygon
  67228. // Represents a convex polygon. The vertices used to initialize a polygon must
  67229. // be coplanar and form a convex loop.
  67230. //
  67231. // Each convex polygon has a `shared` property, which is shared between all
  67232. // polygons that are clones of each other or were split from the same polygon.
  67233. // This can be used to define per-polygon properties (such as surface color).
  67234. var Polygon = /** @class */ (function () {
  67235. function Polygon(vertices, shared) {
  67236. this.vertices = vertices;
  67237. this.shared = shared;
  67238. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67239. }
  67240. Polygon.prototype.clone = function () {
  67241. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67242. return new Polygon(vertices, this.shared);
  67243. };
  67244. Polygon.prototype.flip = function () {
  67245. this.vertices.reverse().map(function (v) { v.flip(); });
  67246. this.plane.flip();
  67247. };
  67248. return Polygon;
  67249. }());
  67250. // # class Node
  67251. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67252. // by picking a polygon to split along. That polygon (and all other coplanar
  67253. // polygons) are added directly to that node and the other polygons are added to
  67254. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67255. // no distinction between internal and leaf nodes.
  67256. var Node = /** @class */ (function () {
  67257. function Node(polygons) {
  67258. this.plane = null;
  67259. this.front = null;
  67260. this.back = null;
  67261. this.polygons = new Array();
  67262. if (polygons) {
  67263. this.build(polygons);
  67264. }
  67265. }
  67266. Node.prototype.clone = function () {
  67267. var node = new Node();
  67268. node.plane = this.plane && this.plane.clone();
  67269. node.front = this.front && this.front.clone();
  67270. node.back = this.back && this.back.clone();
  67271. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67272. return node;
  67273. };
  67274. // Convert solid space to empty space and empty space to solid space.
  67275. Node.prototype.invert = function () {
  67276. for (var i = 0; i < this.polygons.length; i++) {
  67277. this.polygons[i].flip();
  67278. }
  67279. if (this.plane) {
  67280. this.plane.flip();
  67281. }
  67282. if (this.front) {
  67283. this.front.invert();
  67284. }
  67285. if (this.back) {
  67286. this.back.invert();
  67287. }
  67288. var temp = this.front;
  67289. this.front = this.back;
  67290. this.back = temp;
  67291. };
  67292. // Recursively remove all polygons in `polygons` that are inside this BSP
  67293. // tree.
  67294. Node.prototype.clipPolygons = function (polygons) {
  67295. if (!this.plane)
  67296. return polygons.slice();
  67297. var front = new Array(), back = new Array();
  67298. for (var i = 0; i < polygons.length; i++) {
  67299. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67300. }
  67301. if (this.front) {
  67302. front = this.front.clipPolygons(front);
  67303. }
  67304. if (this.back) {
  67305. back = this.back.clipPolygons(back);
  67306. }
  67307. else {
  67308. back = [];
  67309. }
  67310. return front.concat(back);
  67311. };
  67312. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67313. // `bsp`.
  67314. Node.prototype.clipTo = function (bsp) {
  67315. this.polygons = bsp.clipPolygons(this.polygons);
  67316. if (this.front)
  67317. this.front.clipTo(bsp);
  67318. if (this.back)
  67319. this.back.clipTo(bsp);
  67320. };
  67321. // Return a list of all polygons in this BSP tree.
  67322. Node.prototype.allPolygons = function () {
  67323. var polygons = this.polygons.slice();
  67324. if (this.front)
  67325. polygons = polygons.concat(this.front.allPolygons());
  67326. if (this.back)
  67327. polygons = polygons.concat(this.back.allPolygons());
  67328. return polygons;
  67329. };
  67330. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67331. // new polygons are filtered down to the bottom of the tree and become new
  67332. // nodes there. Each set of polygons is partitioned using the first polygon
  67333. // (no heuristic is used to pick a good split).
  67334. Node.prototype.build = function (polygons) {
  67335. if (!polygons.length)
  67336. return;
  67337. if (!this.plane)
  67338. this.plane = polygons[0].plane.clone();
  67339. var front = new Array(), back = new Array();
  67340. for (var i = 0; i < polygons.length; i++) {
  67341. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67342. }
  67343. if (front.length) {
  67344. if (!this.front)
  67345. this.front = new Node();
  67346. this.front.build(front);
  67347. }
  67348. if (back.length) {
  67349. if (!this.back)
  67350. this.back = new Node();
  67351. this.back.build(back);
  67352. }
  67353. };
  67354. return Node;
  67355. }());
  67356. var CSG = /** @class */ (function () {
  67357. function CSG() {
  67358. this.polygons = new Array();
  67359. }
  67360. // Convert BABYLON.Mesh to BABYLON.CSG
  67361. CSG.FromMesh = function (mesh) {
  67362. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67363. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67364. if (mesh instanceof BABYLON.Mesh) {
  67365. mesh.computeWorldMatrix(true);
  67366. matrix = mesh.getWorldMatrix();
  67367. meshPosition = mesh.position.clone();
  67368. meshRotation = mesh.rotation.clone();
  67369. if (mesh.rotationQuaternion) {
  67370. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67371. }
  67372. meshScaling = mesh.scaling.clone();
  67373. }
  67374. else {
  67375. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67376. }
  67377. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67378. var subMeshes = mesh.subMeshes;
  67379. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67380. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67381. vertices = [];
  67382. for (var j = 0; j < 3; j++) {
  67383. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67384. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67385. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67386. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67387. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67388. vertex = new Vertex(position, normal, uv);
  67389. vertices.push(vertex);
  67390. }
  67391. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67392. // To handle the case of degenerated triangle
  67393. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67394. if (polygon.plane)
  67395. polygons.push(polygon);
  67396. }
  67397. }
  67398. var csg = CSG.FromPolygons(polygons);
  67399. csg.matrix = matrix;
  67400. csg.position = meshPosition;
  67401. csg.rotation = meshRotation;
  67402. csg.scaling = meshScaling;
  67403. csg.rotationQuaternion = meshRotationQuaternion;
  67404. currentCSGMeshId++;
  67405. return csg;
  67406. };
  67407. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67408. CSG.FromPolygons = function (polygons) {
  67409. var csg = new CSG();
  67410. csg.polygons = polygons;
  67411. return csg;
  67412. };
  67413. CSG.prototype.clone = function () {
  67414. var csg = new CSG();
  67415. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67416. csg.copyTransformAttributes(this);
  67417. return csg;
  67418. };
  67419. CSG.prototype.union = function (csg) {
  67420. var a = new Node(this.clone().polygons);
  67421. var b = new Node(csg.clone().polygons);
  67422. a.clipTo(b);
  67423. b.clipTo(a);
  67424. b.invert();
  67425. b.clipTo(a);
  67426. b.invert();
  67427. a.build(b.allPolygons());
  67428. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67429. };
  67430. CSG.prototype.unionInPlace = function (csg) {
  67431. var a = new Node(this.polygons);
  67432. var b = new Node(csg.polygons);
  67433. a.clipTo(b);
  67434. b.clipTo(a);
  67435. b.invert();
  67436. b.clipTo(a);
  67437. b.invert();
  67438. a.build(b.allPolygons());
  67439. this.polygons = a.allPolygons();
  67440. };
  67441. CSG.prototype.subtract = function (csg) {
  67442. var a = new Node(this.clone().polygons);
  67443. var b = new Node(csg.clone().polygons);
  67444. a.invert();
  67445. a.clipTo(b);
  67446. b.clipTo(a);
  67447. b.invert();
  67448. b.clipTo(a);
  67449. b.invert();
  67450. a.build(b.allPolygons());
  67451. a.invert();
  67452. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67453. };
  67454. CSG.prototype.subtractInPlace = function (csg) {
  67455. var a = new Node(this.polygons);
  67456. var b = new Node(csg.polygons);
  67457. a.invert();
  67458. a.clipTo(b);
  67459. b.clipTo(a);
  67460. b.invert();
  67461. b.clipTo(a);
  67462. b.invert();
  67463. a.build(b.allPolygons());
  67464. a.invert();
  67465. this.polygons = a.allPolygons();
  67466. };
  67467. CSG.prototype.intersect = function (csg) {
  67468. var a = new Node(this.clone().polygons);
  67469. var b = new Node(csg.clone().polygons);
  67470. a.invert();
  67471. b.clipTo(a);
  67472. b.invert();
  67473. a.clipTo(b);
  67474. b.clipTo(a);
  67475. a.build(b.allPolygons());
  67476. a.invert();
  67477. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67478. };
  67479. CSG.prototype.intersectInPlace = function (csg) {
  67480. var a = new Node(this.polygons);
  67481. var b = new Node(csg.polygons);
  67482. a.invert();
  67483. b.clipTo(a);
  67484. b.invert();
  67485. a.clipTo(b);
  67486. b.clipTo(a);
  67487. a.build(b.allPolygons());
  67488. a.invert();
  67489. this.polygons = a.allPolygons();
  67490. };
  67491. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67492. // not modified.
  67493. CSG.prototype.inverse = function () {
  67494. var csg = this.clone();
  67495. csg.inverseInPlace();
  67496. return csg;
  67497. };
  67498. CSG.prototype.inverseInPlace = function () {
  67499. this.polygons.map(function (p) { p.flip(); });
  67500. };
  67501. // This is used to keep meshes transformations so they can be restored
  67502. // when we build back a Babylon Mesh
  67503. // NB : All CSG operations are performed in world coordinates
  67504. CSG.prototype.copyTransformAttributes = function (csg) {
  67505. this.matrix = csg.matrix;
  67506. this.position = csg.position;
  67507. this.rotation = csg.rotation;
  67508. this.scaling = csg.scaling;
  67509. this.rotationQuaternion = csg.rotationQuaternion;
  67510. return this;
  67511. };
  67512. // Build Raw mesh from CSG
  67513. // Coordinates here are in world space
  67514. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67515. var matrix = this.matrix.clone();
  67516. matrix.invert();
  67517. 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;
  67518. if (keepSubMeshes) {
  67519. // Sort Polygons, since subMeshes are indices range
  67520. polygons.sort(function (a, b) {
  67521. if (a.shared.meshId === b.shared.meshId) {
  67522. return a.shared.subMeshId - b.shared.subMeshId;
  67523. }
  67524. else {
  67525. return a.shared.meshId - b.shared.meshId;
  67526. }
  67527. });
  67528. }
  67529. for (var i = 0, il = polygons.length; i < il; i++) {
  67530. polygon = polygons[i];
  67531. // Building SubMeshes
  67532. if (!subMesh_dict[polygon.shared.meshId]) {
  67533. subMesh_dict[polygon.shared.meshId] = {};
  67534. }
  67535. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67536. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67537. indexStart: +Infinity,
  67538. indexEnd: -Infinity,
  67539. materialIndex: polygon.shared.materialIndex
  67540. };
  67541. }
  67542. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67543. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67544. polygonIndices[0] = 0;
  67545. polygonIndices[1] = j - 1;
  67546. polygonIndices[2] = j;
  67547. for (var k = 0; k < 3; k++) {
  67548. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67549. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67550. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67551. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67552. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67553. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67554. // Check if 2 points can be merged
  67555. if (!(typeof vertex_idx !== 'undefined' &&
  67556. normals[vertex_idx * 3] === localNormal.x &&
  67557. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67558. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67559. uvs[vertex_idx * 2] === uv.x &&
  67560. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67561. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67562. uvs.push(uv.x, uv.y);
  67563. normals.push(normal.x, normal.y, normal.z);
  67564. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67565. }
  67566. indices.push(vertex_idx);
  67567. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67568. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67569. currentIndex++;
  67570. }
  67571. }
  67572. }
  67573. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67574. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67575. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67576. mesh.setIndices(indices, null);
  67577. if (keepSubMeshes) {
  67578. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67579. var materialIndexOffset = 0, materialMaxIndex;
  67580. mesh.subMeshes = new Array();
  67581. for (var m in subMesh_dict) {
  67582. materialMaxIndex = -1;
  67583. for (var sm in subMesh_dict[m]) {
  67584. subMesh_obj = subMesh_dict[m][sm];
  67585. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67586. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67587. }
  67588. materialIndexOffset += ++materialMaxIndex;
  67589. }
  67590. }
  67591. return mesh;
  67592. };
  67593. // Build Mesh from CSG taking material and transforms into account
  67594. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67595. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67596. mesh.material = material;
  67597. mesh.position.copyFrom(this.position);
  67598. mesh.rotation.copyFrom(this.rotation);
  67599. if (this.rotationQuaternion) {
  67600. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67601. }
  67602. mesh.scaling.copyFrom(this.scaling);
  67603. mesh.computeWorldMatrix(true);
  67604. return mesh;
  67605. };
  67606. return CSG;
  67607. }());
  67608. BABYLON.CSG = CSG;
  67609. })(BABYLON || (BABYLON = {}));
  67610. //# sourceMappingURL=babylon.csg.js.map
  67611. var BABYLON;
  67612. (function (BABYLON) {
  67613. var LensFlare = /** @class */ (function () {
  67614. function LensFlare(size, position, color, imgUrl, system) {
  67615. this.size = size;
  67616. this.position = position;
  67617. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67618. this.color = color || new BABYLON.Color3(1, 1, 1);
  67619. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67620. this._system = system;
  67621. system.lensFlares.push(this);
  67622. }
  67623. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67624. return new LensFlare(size, position, color, imgUrl, system);
  67625. };
  67626. LensFlare.prototype.dispose = function () {
  67627. if (this.texture) {
  67628. this.texture.dispose();
  67629. }
  67630. // Remove from scene
  67631. var index = this._system.lensFlares.indexOf(this);
  67632. this._system.lensFlares.splice(index, 1);
  67633. };
  67634. ;
  67635. return LensFlare;
  67636. }());
  67637. BABYLON.LensFlare = LensFlare;
  67638. })(BABYLON || (BABYLON = {}));
  67639. //# sourceMappingURL=babylon.lensFlare.js.map
  67640. var BABYLON;
  67641. (function (BABYLON) {
  67642. var LensFlareSystem = /** @class */ (function () {
  67643. function LensFlareSystem(name, emitter, scene) {
  67644. this.name = name;
  67645. this.lensFlares = new Array();
  67646. this.borderLimit = 300;
  67647. this.viewportBorder = 0;
  67648. this.layerMask = 0x0FFFFFFF;
  67649. this._vertexBuffers = {};
  67650. this._isEnabled = true;
  67651. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67652. this._emitter = emitter;
  67653. this.id = name;
  67654. scene.lensFlareSystems.push(this);
  67655. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67656. var engine = scene.getEngine();
  67657. // VBO
  67658. var vertices = [];
  67659. vertices.push(1, 1);
  67660. vertices.push(-1, 1);
  67661. vertices.push(-1, -1);
  67662. vertices.push(1, -1);
  67663. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67664. // Indices
  67665. var indices = [];
  67666. indices.push(0);
  67667. indices.push(1);
  67668. indices.push(2);
  67669. indices.push(0);
  67670. indices.push(2);
  67671. indices.push(3);
  67672. this._indexBuffer = engine.createIndexBuffer(indices);
  67673. // Effects
  67674. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67675. }
  67676. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67677. get: function () {
  67678. return this._isEnabled;
  67679. },
  67680. set: function (value) {
  67681. this._isEnabled = value;
  67682. },
  67683. enumerable: true,
  67684. configurable: true
  67685. });
  67686. LensFlareSystem.prototype.getScene = function () {
  67687. return this._scene;
  67688. };
  67689. LensFlareSystem.prototype.getEmitter = function () {
  67690. return this._emitter;
  67691. };
  67692. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67693. this._emitter = newEmitter;
  67694. };
  67695. LensFlareSystem.prototype.getEmitterPosition = function () {
  67696. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67697. };
  67698. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67699. var position = this.getEmitterPosition();
  67700. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67701. this._positionX = position.x;
  67702. this._positionY = position.y;
  67703. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67704. if (this.viewportBorder > 0) {
  67705. globalViewport.x -= this.viewportBorder;
  67706. globalViewport.y -= this.viewportBorder;
  67707. globalViewport.width += this.viewportBorder * 2;
  67708. globalViewport.height += this.viewportBorder * 2;
  67709. position.x += this.viewportBorder;
  67710. position.y += this.viewportBorder;
  67711. this._positionX += this.viewportBorder;
  67712. this._positionY += this.viewportBorder;
  67713. }
  67714. if (position.z > 0) {
  67715. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67716. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67717. return true;
  67718. }
  67719. return true;
  67720. }
  67721. return false;
  67722. };
  67723. LensFlareSystem.prototype._isVisible = function () {
  67724. if (!this._isEnabled || !this._scene.activeCamera) {
  67725. return false;
  67726. }
  67727. var emitterPosition = this.getEmitterPosition();
  67728. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67729. var distance = direction.length();
  67730. direction.normalize();
  67731. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67732. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67733. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67734. };
  67735. LensFlareSystem.prototype.render = function () {
  67736. if (!this._effect.isReady() || !this._scene.activeCamera)
  67737. return false;
  67738. var engine = this._scene.getEngine();
  67739. var viewport = this._scene.activeCamera.viewport;
  67740. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67741. // Position
  67742. if (!this.computeEffectivePosition(globalViewport)) {
  67743. return false;
  67744. }
  67745. // Visibility
  67746. if (!this._isVisible()) {
  67747. return false;
  67748. }
  67749. // Intensity
  67750. var awayX;
  67751. var awayY;
  67752. if (this._positionX < this.borderLimit + globalViewport.x) {
  67753. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67754. }
  67755. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67756. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67757. }
  67758. else {
  67759. awayX = 0;
  67760. }
  67761. if (this._positionY < this.borderLimit + globalViewport.y) {
  67762. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67763. }
  67764. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67765. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67766. }
  67767. else {
  67768. awayY = 0;
  67769. }
  67770. var away = (awayX > awayY) ? awayX : awayY;
  67771. away -= this.viewportBorder;
  67772. if (away > this.borderLimit) {
  67773. away = this.borderLimit;
  67774. }
  67775. var intensity = 1.0 - (away / this.borderLimit);
  67776. if (intensity < 0) {
  67777. return false;
  67778. }
  67779. if (intensity > 1.0) {
  67780. intensity = 1.0;
  67781. }
  67782. if (this.viewportBorder > 0) {
  67783. globalViewport.x += this.viewportBorder;
  67784. globalViewport.y += this.viewportBorder;
  67785. globalViewport.width -= this.viewportBorder * 2;
  67786. globalViewport.height -= this.viewportBorder * 2;
  67787. this._positionX -= this.viewportBorder;
  67788. this._positionY -= this.viewportBorder;
  67789. }
  67790. // Position
  67791. var centerX = globalViewport.x + globalViewport.width / 2;
  67792. var centerY = globalViewport.y + globalViewport.height / 2;
  67793. var distX = centerX - this._positionX;
  67794. var distY = centerY - this._positionY;
  67795. // Effects
  67796. engine.enableEffect(this._effect);
  67797. engine.setState(false);
  67798. engine.setDepthBuffer(false);
  67799. // VBOs
  67800. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67801. // Flares
  67802. for (var index = 0; index < this.lensFlares.length; index++) {
  67803. var flare = this.lensFlares[index];
  67804. engine.setAlphaMode(flare.alphaMode);
  67805. var x = centerX - (distX * flare.position);
  67806. var y = centerY - (distY * flare.position);
  67807. var cw = flare.size;
  67808. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67809. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67810. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67811. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67812. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67813. // Texture
  67814. this._effect.setTexture("textureSampler", flare.texture);
  67815. // Color
  67816. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67817. // Draw order
  67818. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67819. }
  67820. engine.setDepthBuffer(true);
  67821. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67822. return true;
  67823. };
  67824. LensFlareSystem.prototype.dispose = function () {
  67825. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67826. if (vertexBuffer) {
  67827. vertexBuffer.dispose();
  67828. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67829. }
  67830. if (this._indexBuffer) {
  67831. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67832. this._indexBuffer = null;
  67833. }
  67834. while (this.lensFlares.length) {
  67835. this.lensFlares[0].dispose();
  67836. }
  67837. // Remove from scene
  67838. var index = this._scene.lensFlareSystems.indexOf(this);
  67839. this._scene.lensFlareSystems.splice(index, 1);
  67840. };
  67841. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67842. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67843. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67844. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67845. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67846. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67847. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67848. var parsedFlare = parsedLensFlareSystem.flares[index];
  67849. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67850. }
  67851. return lensFlareSystem;
  67852. };
  67853. LensFlareSystem.prototype.serialize = function () {
  67854. var serializationObject = {};
  67855. serializationObject.id = this.id;
  67856. serializationObject.name = this.name;
  67857. serializationObject.emitterId = this.getEmitter().id;
  67858. serializationObject.borderLimit = this.borderLimit;
  67859. serializationObject.flares = [];
  67860. for (var index = 0; index < this.lensFlares.length; index++) {
  67861. var flare = this.lensFlares[index];
  67862. serializationObject.flares.push({
  67863. size: flare.size,
  67864. position: flare.position,
  67865. color: flare.color.asArray(),
  67866. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67867. });
  67868. }
  67869. return serializationObject;
  67870. };
  67871. return LensFlareSystem;
  67872. }());
  67873. BABYLON.LensFlareSystem = LensFlareSystem;
  67874. })(BABYLON || (BABYLON = {}));
  67875. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67876. var BABYLON;
  67877. (function (BABYLON) {
  67878. /**
  67879. * This is a holder class for the physics joint created by the physics plugin.
  67880. * It holds a set of functions to control the underlying joint.
  67881. */
  67882. var PhysicsJoint = /** @class */ (function () {
  67883. function PhysicsJoint(type, jointData) {
  67884. this.type = type;
  67885. this.jointData = jointData;
  67886. jointData.nativeParams = jointData.nativeParams || {};
  67887. }
  67888. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67889. get: function () {
  67890. return this._physicsJoint;
  67891. },
  67892. set: function (newJoint) {
  67893. if (this._physicsJoint) {
  67894. //remove from the wolrd
  67895. }
  67896. this._physicsJoint = newJoint;
  67897. },
  67898. enumerable: true,
  67899. configurable: true
  67900. });
  67901. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67902. set: function (physicsPlugin) {
  67903. this._physicsPlugin = physicsPlugin;
  67904. },
  67905. enumerable: true,
  67906. configurable: true
  67907. });
  67908. /**
  67909. * Execute a function that is physics-plugin specific.
  67910. * @param {Function} func the function that will be executed.
  67911. * It accepts two parameters: the physics world and the physics joint.
  67912. */
  67913. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67914. func(this._physicsPlugin.world, this._physicsJoint);
  67915. };
  67916. //TODO check if the native joints are the same
  67917. //Joint Types
  67918. PhysicsJoint.DistanceJoint = 0;
  67919. PhysicsJoint.HingeJoint = 1;
  67920. PhysicsJoint.BallAndSocketJoint = 2;
  67921. PhysicsJoint.WheelJoint = 3;
  67922. PhysicsJoint.SliderJoint = 4;
  67923. //OIMO
  67924. PhysicsJoint.PrismaticJoint = 5;
  67925. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67926. PhysicsJoint.UniversalJoint = 6;
  67927. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67928. //Cannon
  67929. //Similar to a Ball-Joint. Different in params
  67930. PhysicsJoint.PointToPointJoint = 8;
  67931. //Cannon only at the moment
  67932. PhysicsJoint.SpringJoint = 9;
  67933. PhysicsJoint.LockJoint = 10;
  67934. return PhysicsJoint;
  67935. }());
  67936. BABYLON.PhysicsJoint = PhysicsJoint;
  67937. /**
  67938. * A class representing a physics distance joint.
  67939. */
  67940. var DistanceJoint = /** @class */ (function (_super) {
  67941. __extends(DistanceJoint, _super);
  67942. function DistanceJoint(jointData) {
  67943. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67944. }
  67945. /**
  67946. * Update the predefined distance.
  67947. */
  67948. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67949. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67950. };
  67951. return DistanceJoint;
  67952. }(PhysicsJoint));
  67953. BABYLON.DistanceJoint = DistanceJoint;
  67954. var MotorEnabledJoint = /** @class */ (function (_super) {
  67955. __extends(MotorEnabledJoint, _super);
  67956. function MotorEnabledJoint(type, jointData) {
  67957. return _super.call(this, type, jointData) || this;
  67958. }
  67959. /**
  67960. * Set the motor values.
  67961. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67962. * @param {number} force the force to apply
  67963. * @param {number} maxForce max force for this motor.
  67964. */
  67965. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67966. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67967. };
  67968. /**
  67969. * Set the motor's limits.
  67970. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67971. */
  67972. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67973. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67974. };
  67975. return MotorEnabledJoint;
  67976. }(PhysicsJoint));
  67977. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67978. /**
  67979. * This class represents a single hinge physics joint
  67980. */
  67981. var HingeJoint = /** @class */ (function (_super) {
  67982. __extends(HingeJoint, _super);
  67983. function HingeJoint(jointData) {
  67984. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67985. }
  67986. /**
  67987. * Set the motor values.
  67988. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67989. * @param {number} force the force to apply
  67990. * @param {number} maxForce max force for this motor.
  67991. */
  67992. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67993. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67994. };
  67995. /**
  67996. * Set the motor's limits.
  67997. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67998. */
  67999. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  68000. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  68001. };
  68002. return HingeJoint;
  68003. }(MotorEnabledJoint));
  68004. BABYLON.HingeJoint = HingeJoint;
  68005. /**
  68006. * This class represents a dual hinge physics joint (same as wheel joint)
  68007. */
  68008. var Hinge2Joint = /** @class */ (function (_super) {
  68009. __extends(Hinge2Joint, _super);
  68010. function Hinge2Joint(jointData) {
  68011. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  68012. }
  68013. /**
  68014. * Set the motor values.
  68015. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68016. * @param {number} force the force to apply
  68017. * @param {number} maxForce max force for this motor.
  68018. * @param {motorIndex} the motor's index, 0 or 1.
  68019. */
  68020. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  68021. if (motorIndex === void 0) { motorIndex = 0; }
  68022. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  68023. };
  68024. /**
  68025. * Set the motor limits.
  68026. * Attention, this function is plugin specific. Engines won't react 100% the same.
  68027. * @param {number} upperLimit the upper limit
  68028. * @param {number} lowerLimit lower limit
  68029. * @param {motorIndex} the motor's index, 0 or 1.
  68030. */
  68031. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  68032. if (motorIndex === void 0) { motorIndex = 0; }
  68033. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  68034. };
  68035. return Hinge2Joint;
  68036. }(MotorEnabledJoint));
  68037. BABYLON.Hinge2Joint = Hinge2Joint;
  68038. })(BABYLON || (BABYLON = {}));
  68039. //# sourceMappingURL=babylon.physicsJoint.js.map
  68040. var BABYLON;
  68041. (function (BABYLON) {
  68042. var PhysicsImpostor = /** @class */ (function () {
  68043. function PhysicsImpostor(object, type, _options, _scene) {
  68044. if (_options === void 0) { _options = { mass: 0 }; }
  68045. var _this = this;
  68046. this.object = object;
  68047. this.type = type;
  68048. this._options = _options;
  68049. this._scene = _scene;
  68050. this._bodyUpdateRequired = false;
  68051. this._onBeforePhysicsStepCallbacks = new Array();
  68052. this._onAfterPhysicsStepCallbacks = new Array();
  68053. this._onPhysicsCollideCallbacks = [];
  68054. this._deltaPosition = BABYLON.Vector3.Zero();
  68055. this._isDisposed = false;
  68056. //temp variables for parent rotation calculations
  68057. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  68058. this._tmpQuat = new BABYLON.Quaternion();
  68059. this._tmpQuat2 = new BABYLON.Quaternion();
  68060. /**
  68061. * this function is executed by the physics engine.
  68062. */
  68063. this.beforeStep = function () {
  68064. if (!_this._physicsEngine) {
  68065. return;
  68066. }
  68067. _this.object.translate(_this._deltaPosition, -1);
  68068. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  68069. _this.object.computeWorldMatrix(false);
  68070. if (_this.object.parent && _this.object.rotationQuaternion) {
  68071. _this.getParentsRotation();
  68072. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  68073. }
  68074. else {
  68075. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  68076. }
  68077. if (!_this._options.disableBidirectionalTransformation) {
  68078. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  68079. }
  68080. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  68081. func(_this);
  68082. });
  68083. };
  68084. /**
  68085. * this function is executed by the physics engine.
  68086. */
  68087. this.afterStep = function () {
  68088. if (!_this._physicsEngine) {
  68089. return;
  68090. }
  68091. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  68092. func(_this);
  68093. });
  68094. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  68095. // object has now its world rotation. needs to be converted to local.
  68096. if (_this.object.parent && _this.object.rotationQuaternion) {
  68097. _this.getParentsRotation();
  68098. _this._tmpQuat.conjugateInPlace();
  68099. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  68100. }
  68101. // take the position set and make it the absolute position of this object.
  68102. _this.object.setAbsolutePosition(_this.object.position);
  68103. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  68104. _this.object.translate(_this._deltaPosition, 1);
  68105. };
  68106. /**
  68107. * Legacy collision detection event support
  68108. */
  68109. this.onCollideEvent = null;
  68110. //event and body object due to cannon's event-based architecture.
  68111. this.onCollide = function (e) {
  68112. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  68113. return;
  68114. }
  68115. if (!_this._physicsEngine) {
  68116. return;
  68117. }
  68118. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  68119. if (otherImpostor) {
  68120. // Legacy collision detection event support
  68121. if (_this.onCollideEvent) {
  68122. _this.onCollideEvent(_this, otherImpostor);
  68123. }
  68124. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  68125. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  68126. }).forEach(function (obj) {
  68127. obj.callback(_this, otherImpostor);
  68128. });
  68129. }
  68130. };
  68131. //sanity check!
  68132. if (!this.object) {
  68133. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  68134. return;
  68135. }
  68136. //legacy support for old syntax.
  68137. if (!this._scene && object.getScene) {
  68138. this._scene = object.getScene();
  68139. }
  68140. if (!this._scene) {
  68141. return;
  68142. }
  68143. this._physicsEngine = this._scene.getPhysicsEngine();
  68144. if (!this._physicsEngine) {
  68145. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  68146. }
  68147. else {
  68148. //set the object's quaternion, if not set
  68149. if (!this.object.rotationQuaternion) {
  68150. if (this.object.rotation) {
  68151. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68152. }
  68153. else {
  68154. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68155. }
  68156. }
  68157. //default options params
  68158. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68159. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68160. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68161. this._joints = [];
  68162. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68163. if (!this.object.parent || this._options.ignoreParent) {
  68164. this._init();
  68165. }
  68166. else if (this.object.parent.physicsImpostor) {
  68167. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68168. }
  68169. }
  68170. }
  68171. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68172. get: function () {
  68173. return this._isDisposed;
  68174. },
  68175. enumerable: true,
  68176. configurable: true
  68177. });
  68178. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68179. get: function () {
  68180. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68181. },
  68182. set: function (value) {
  68183. this.setMass(value);
  68184. },
  68185. enumerable: true,
  68186. configurable: true
  68187. });
  68188. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68189. get: function () {
  68190. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68191. },
  68192. set: function (value) {
  68193. if (!this._physicsEngine) {
  68194. return;
  68195. }
  68196. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68197. },
  68198. enumerable: true,
  68199. configurable: true
  68200. });
  68201. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68202. get: function () {
  68203. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68204. },
  68205. set: function (value) {
  68206. if (!this._physicsEngine) {
  68207. return;
  68208. }
  68209. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68210. },
  68211. enumerable: true,
  68212. configurable: true
  68213. });
  68214. /**
  68215. * This function will completly initialize this impostor.
  68216. * It will create a new body - but only if this mesh has no parent.
  68217. * If it has, this impostor will not be used other than to define the impostor
  68218. * of the child mesh.
  68219. */
  68220. PhysicsImpostor.prototype._init = function () {
  68221. if (!this._physicsEngine) {
  68222. return;
  68223. }
  68224. this._physicsEngine.removeImpostor(this);
  68225. this.physicsBody = null;
  68226. this._parent = this._parent || this._getPhysicsParent();
  68227. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68228. this._physicsEngine.addImpostor(this);
  68229. }
  68230. };
  68231. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68232. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68233. var parentMesh = this.object.parent;
  68234. return parentMesh.physicsImpostor;
  68235. }
  68236. return null;
  68237. };
  68238. /**
  68239. * Should a new body be generated.
  68240. */
  68241. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68242. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68243. };
  68244. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68245. this.forceUpdate();
  68246. };
  68247. /**
  68248. * Force a regeneration of this or the parent's impostor's body.
  68249. * Use under cautious - This will remove all joints already implemented.
  68250. */
  68251. PhysicsImpostor.prototype.forceUpdate = function () {
  68252. this._init();
  68253. if (this.parent && !this._options.ignoreParent) {
  68254. this.parent.forceUpdate();
  68255. }
  68256. };
  68257. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68258. /*public get mesh(): AbstractMesh {
  68259. return this._mesh;
  68260. }*/
  68261. /**
  68262. * Gets the body that holds this impostor. Either its own, or its parent.
  68263. */
  68264. get: function () {
  68265. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68266. },
  68267. /**
  68268. * Set the physics body. Used mainly by the physics engine/plugin
  68269. */
  68270. set: function (physicsBody) {
  68271. if (this._physicsBody && this._physicsEngine) {
  68272. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68273. }
  68274. this._physicsBody = physicsBody;
  68275. this.resetUpdateFlags();
  68276. },
  68277. enumerable: true,
  68278. configurable: true
  68279. });
  68280. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68281. get: function () {
  68282. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68283. },
  68284. set: function (value) {
  68285. this._parent = value;
  68286. },
  68287. enumerable: true,
  68288. configurable: true
  68289. });
  68290. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68291. this._bodyUpdateRequired = false;
  68292. };
  68293. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68294. if (this.object.getBoundingInfo) {
  68295. var q = this.object.rotationQuaternion;
  68296. //reset rotation
  68297. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68298. //calculate the world matrix with no rotation
  68299. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68300. var boundingInfo = this.object.getBoundingInfo();
  68301. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68302. //bring back the rotation
  68303. this.object.rotationQuaternion = q;
  68304. //calculate the world matrix with the new rotation
  68305. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68306. return size;
  68307. }
  68308. else {
  68309. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68310. }
  68311. };
  68312. PhysicsImpostor.prototype.getObjectCenter = function () {
  68313. if (this.object.getBoundingInfo) {
  68314. var boundingInfo = this.object.getBoundingInfo();
  68315. return boundingInfo.boundingBox.centerWorld;
  68316. }
  68317. else {
  68318. return this.object.position;
  68319. }
  68320. };
  68321. /**
  68322. * Get a specific parametes from the options parameter.
  68323. */
  68324. PhysicsImpostor.prototype.getParam = function (paramName) {
  68325. return this._options[paramName];
  68326. };
  68327. /**
  68328. * Sets a specific parameter in the options given to the physics plugin
  68329. */
  68330. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68331. this._options[paramName] = value;
  68332. this._bodyUpdateRequired = true;
  68333. };
  68334. /**
  68335. * Specifically change the body's mass option. Won't recreate the physics body object
  68336. */
  68337. PhysicsImpostor.prototype.setMass = function (mass) {
  68338. if (this.getParam("mass") !== mass) {
  68339. this.setParam("mass", mass);
  68340. }
  68341. if (this._physicsEngine) {
  68342. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68343. }
  68344. };
  68345. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68346. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68347. };
  68348. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68349. if (this._physicsEngine) {
  68350. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68351. }
  68352. };
  68353. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68354. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68355. };
  68356. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68357. if (this._physicsEngine) {
  68358. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68359. }
  68360. };
  68361. /**
  68362. * Execute a function with the physics plugin native code.
  68363. * Provide a function the will have two variables - the world object and the physics body object.
  68364. */
  68365. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68366. if (this._physicsEngine) {
  68367. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68368. }
  68369. };
  68370. /**
  68371. * Register a function that will be executed before the physics world is stepping forward.
  68372. */
  68373. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68374. this._onBeforePhysicsStepCallbacks.push(func);
  68375. };
  68376. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68377. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68378. if (index > -1) {
  68379. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68380. }
  68381. else {
  68382. BABYLON.Tools.Warn("Function to remove was not found");
  68383. }
  68384. };
  68385. /**
  68386. * Register a function that will be executed after the physics step
  68387. */
  68388. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68389. this._onAfterPhysicsStepCallbacks.push(func);
  68390. };
  68391. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68392. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68393. if (index > -1) {
  68394. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68395. }
  68396. else {
  68397. BABYLON.Tools.Warn("Function to remove was not found");
  68398. }
  68399. };
  68400. /**
  68401. * register a function that will be executed when this impostor collides against a different body.
  68402. */
  68403. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68404. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68405. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68406. };
  68407. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68408. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68409. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68410. if (index > -1) {
  68411. this._onPhysicsCollideCallbacks.splice(index, 1);
  68412. }
  68413. else {
  68414. BABYLON.Tools.Warn("Function to remove was not found");
  68415. }
  68416. };
  68417. PhysicsImpostor.prototype.getParentsRotation = function () {
  68418. var parent = this.object.parent;
  68419. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68420. while (parent) {
  68421. if (parent.rotationQuaternion) {
  68422. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68423. }
  68424. else {
  68425. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68426. }
  68427. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68428. parent = parent.parent;
  68429. }
  68430. return this._tmpQuat;
  68431. };
  68432. /**
  68433. * Apply a force
  68434. */
  68435. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68436. if (this._physicsEngine) {
  68437. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68438. }
  68439. return this;
  68440. };
  68441. /**
  68442. * Apply an impulse
  68443. */
  68444. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68445. if (this._physicsEngine) {
  68446. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68447. }
  68448. return this;
  68449. };
  68450. /**
  68451. * A help function to create a joint.
  68452. */
  68453. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68454. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68455. this.addJoint(otherImpostor, joint);
  68456. return this;
  68457. };
  68458. /**
  68459. * Add a joint to this impostor with a different impostor.
  68460. */
  68461. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68462. this._joints.push({
  68463. otherImpostor: otherImpostor,
  68464. joint: joint
  68465. });
  68466. if (this._physicsEngine) {
  68467. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68468. }
  68469. return this;
  68470. };
  68471. /**
  68472. * Will keep this body still, in a sleep mode.
  68473. */
  68474. PhysicsImpostor.prototype.sleep = function () {
  68475. if (this._physicsEngine) {
  68476. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68477. }
  68478. return this;
  68479. };
  68480. /**
  68481. * Wake the body up.
  68482. */
  68483. PhysicsImpostor.prototype.wakeUp = function () {
  68484. if (this._physicsEngine) {
  68485. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68486. }
  68487. return this;
  68488. };
  68489. PhysicsImpostor.prototype.clone = function (newObject) {
  68490. if (!newObject)
  68491. return null;
  68492. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68493. };
  68494. PhysicsImpostor.prototype.dispose = function () {
  68495. var _this = this;
  68496. //no dispose if no physics engine is available.
  68497. if (!this._physicsEngine) {
  68498. return;
  68499. }
  68500. this._joints.forEach(function (j) {
  68501. if (_this._physicsEngine) {
  68502. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68503. }
  68504. });
  68505. //dispose the physics body
  68506. this._physicsEngine.removeImpostor(this);
  68507. if (this.parent) {
  68508. this.parent.forceUpdate();
  68509. }
  68510. else {
  68511. /*this._object.getChildMeshes().forEach(function(mesh) {
  68512. if (mesh.physicsImpostor) {
  68513. if (disposeChildren) {
  68514. mesh.physicsImpostor.dispose();
  68515. mesh.physicsImpostor = null;
  68516. }
  68517. }
  68518. })*/
  68519. }
  68520. this._isDisposed = true;
  68521. };
  68522. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68523. this._deltaPosition.copyFrom(position);
  68524. };
  68525. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68526. if (!this._deltaRotation) {
  68527. this._deltaRotation = new BABYLON.Quaternion();
  68528. }
  68529. this._deltaRotation.copyFrom(rotation);
  68530. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68531. };
  68532. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68533. if (this._physicsEngine) {
  68534. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68535. }
  68536. return this;
  68537. };
  68538. PhysicsImpostor.prototype.getRadius = function () {
  68539. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68540. };
  68541. /**
  68542. * Sync a bone with this impostor
  68543. * @param bone The bone to sync to the impostor.
  68544. * @param boneMesh The mesh that the bone is influencing.
  68545. * @param jointPivot The pivot of the joint / bone in local space.
  68546. * @param distToJoint Optional distance from the impostor to the joint.
  68547. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68548. */
  68549. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68550. var tempVec = PhysicsImpostor._tmpVecs[0];
  68551. var mesh = this.object;
  68552. if (mesh.rotationQuaternion) {
  68553. if (adjustRotation) {
  68554. var tempQuat = PhysicsImpostor._tmpQuat;
  68555. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68556. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68557. }
  68558. else {
  68559. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68560. }
  68561. }
  68562. tempVec.x = 0;
  68563. tempVec.y = 0;
  68564. tempVec.z = 0;
  68565. if (jointPivot) {
  68566. tempVec.x = jointPivot.x;
  68567. tempVec.y = jointPivot.y;
  68568. tempVec.z = jointPivot.z;
  68569. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68570. if (distToJoint === undefined || distToJoint === null) {
  68571. distToJoint = jointPivot.length();
  68572. }
  68573. tempVec.x *= distToJoint;
  68574. tempVec.y *= distToJoint;
  68575. tempVec.z *= distToJoint;
  68576. }
  68577. if (bone.getParent()) {
  68578. tempVec.addInPlace(mesh.getAbsolutePosition());
  68579. bone.setAbsolutePosition(tempVec, boneMesh);
  68580. }
  68581. else {
  68582. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68583. boneMesh.position.x -= tempVec.x;
  68584. boneMesh.position.y -= tempVec.y;
  68585. boneMesh.position.z -= tempVec.z;
  68586. }
  68587. };
  68588. /**
  68589. * Sync impostor to a bone
  68590. * @param bone The bone that the impostor will be synced to.
  68591. * @param boneMesh The mesh that the bone is influencing.
  68592. * @param jointPivot The pivot of the joint / bone in local space.
  68593. * @param distToJoint Optional distance from the impostor to the joint.
  68594. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68595. * @param boneAxis Optional vector3 axis the bone is aligned with
  68596. */
  68597. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68598. var mesh = this.object;
  68599. if (mesh.rotationQuaternion) {
  68600. if (adjustRotation) {
  68601. var tempQuat = PhysicsImpostor._tmpQuat;
  68602. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68603. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68604. }
  68605. else {
  68606. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68607. }
  68608. }
  68609. var pos = PhysicsImpostor._tmpVecs[0];
  68610. var boneDir = PhysicsImpostor._tmpVecs[1];
  68611. if (!boneAxis) {
  68612. boneAxis = PhysicsImpostor._tmpVecs[2];
  68613. boneAxis.x = 0;
  68614. boneAxis.y = 1;
  68615. boneAxis.z = 0;
  68616. }
  68617. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68618. bone.getAbsolutePositionToRef(boneMesh, pos);
  68619. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68620. distToJoint = jointPivot.length();
  68621. }
  68622. if (distToJoint !== undefined && distToJoint !== null) {
  68623. pos.x += boneDir.x * distToJoint;
  68624. pos.y += boneDir.y * distToJoint;
  68625. pos.z += boneDir.z * distToJoint;
  68626. }
  68627. mesh.setAbsolutePosition(pos);
  68628. };
  68629. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68630. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68631. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68632. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68633. //Impostor types
  68634. PhysicsImpostor.NoImpostor = 0;
  68635. PhysicsImpostor.SphereImpostor = 1;
  68636. PhysicsImpostor.BoxImpostor = 2;
  68637. PhysicsImpostor.PlaneImpostor = 3;
  68638. PhysicsImpostor.MeshImpostor = 4;
  68639. PhysicsImpostor.CylinderImpostor = 7;
  68640. PhysicsImpostor.ParticleImpostor = 8;
  68641. PhysicsImpostor.HeightmapImpostor = 9;
  68642. return PhysicsImpostor;
  68643. }());
  68644. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68645. })(BABYLON || (BABYLON = {}));
  68646. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68647. var BABYLON;
  68648. (function (BABYLON) {
  68649. var PhysicsEngine = /** @class */ (function () {
  68650. function PhysicsEngine(gravity, _physicsPlugin) {
  68651. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68652. this._physicsPlugin = _physicsPlugin;
  68653. //new methods and parameters
  68654. this._impostors = [];
  68655. this._joints = [];
  68656. if (!this._physicsPlugin.isSupported()) {
  68657. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68658. + "Please make sure it is included.");
  68659. }
  68660. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68661. this.setGravity(gravity);
  68662. this.setTimeStep();
  68663. }
  68664. PhysicsEngine.prototype.setGravity = function (gravity) {
  68665. this.gravity = gravity;
  68666. this._physicsPlugin.setGravity(this.gravity);
  68667. };
  68668. /**
  68669. * Set the time step of the physics engine.
  68670. * default is 1/60.
  68671. * To slow it down, enter 1/600 for example.
  68672. * To speed it up, 1/30
  68673. * @param {number} newTimeStep the new timestep to apply to this world.
  68674. */
  68675. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68676. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68677. this._physicsPlugin.setTimeStep(newTimeStep);
  68678. };
  68679. /**
  68680. * Get the time step of the physics engine.
  68681. */
  68682. PhysicsEngine.prototype.getTimeStep = function () {
  68683. return this._physicsPlugin.getTimeStep();
  68684. };
  68685. PhysicsEngine.prototype.dispose = function () {
  68686. this._impostors.forEach(function (impostor) {
  68687. impostor.dispose();
  68688. });
  68689. this._physicsPlugin.dispose();
  68690. };
  68691. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68692. return this._physicsPlugin.name;
  68693. };
  68694. /**
  68695. * Adding a new impostor for the impostor tracking.
  68696. * This will be done by the impostor itself.
  68697. * @param {PhysicsImpostor} impostor the impostor to add
  68698. */
  68699. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68700. impostor.uniqueId = this._impostors.push(impostor);
  68701. //if no parent, generate the body
  68702. if (!impostor.parent) {
  68703. this._physicsPlugin.generatePhysicsBody(impostor);
  68704. }
  68705. };
  68706. /**
  68707. * Remove an impostor from the engine.
  68708. * This impostor and its mesh will not longer be updated by the physics engine.
  68709. * @param {PhysicsImpostor} impostor the impostor to remove
  68710. */
  68711. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68712. var index = this._impostors.indexOf(impostor);
  68713. if (index > -1) {
  68714. var removed = this._impostors.splice(index, 1);
  68715. //Is it needed?
  68716. if (removed.length) {
  68717. //this will also remove it from the world.
  68718. removed[0].physicsBody = null;
  68719. }
  68720. }
  68721. };
  68722. /**
  68723. * Add a joint to the physics engine
  68724. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68725. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68726. * @param {PhysicsJoint} the joint that will connect both impostors.
  68727. */
  68728. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68729. var impostorJoint = {
  68730. mainImpostor: mainImpostor,
  68731. connectedImpostor: connectedImpostor,
  68732. joint: joint
  68733. };
  68734. joint.physicsPlugin = this._physicsPlugin;
  68735. this._joints.push(impostorJoint);
  68736. this._physicsPlugin.generateJoint(impostorJoint);
  68737. };
  68738. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68739. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68740. return (impostorJoint.connectedImpostor === connectedImpostor
  68741. && impostorJoint.joint === joint
  68742. && impostorJoint.mainImpostor === mainImpostor);
  68743. });
  68744. if (matchingJoints.length) {
  68745. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68746. //TODO remove it from the list as well
  68747. }
  68748. };
  68749. /**
  68750. * Called by the scene. no need to call it.
  68751. */
  68752. PhysicsEngine.prototype._step = function (delta) {
  68753. var _this = this;
  68754. //check if any mesh has no body / requires an update
  68755. this._impostors.forEach(function (impostor) {
  68756. if (impostor.isBodyInitRequired()) {
  68757. _this._physicsPlugin.generatePhysicsBody(impostor);
  68758. }
  68759. });
  68760. if (delta > 0.1) {
  68761. delta = 0.1;
  68762. }
  68763. else if (delta <= 0) {
  68764. delta = 1.0 / 60.0;
  68765. }
  68766. this._physicsPlugin.executeStep(delta, this._impostors);
  68767. };
  68768. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68769. return this._physicsPlugin;
  68770. };
  68771. PhysicsEngine.prototype.getImpostors = function () {
  68772. return this._impostors;
  68773. };
  68774. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68775. for (var i = 0; i < this._impostors.length; ++i) {
  68776. if (this._impostors[i].object === object) {
  68777. return this._impostors[i];
  68778. }
  68779. }
  68780. return null;
  68781. };
  68782. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68783. for (var i = 0; i < this._impostors.length; ++i) {
  68784. if (this._impostors[i].physicsBody === body) {
  68785. return this._impostors[i];
  68786. }
  68787. }
  68788. return null;
  68789. };
  68790. // Statics
  68791. PhysicsEngine.Epsilon = 0.001;
  68792. return PhysicsEngine;
  68793. }());
  68794. BABYLON.PhysicsEngine = PhysicsEngine;
  68795. })(BABYLON || (BABYLON = {}));
  68796. //# sourceMappingURL=babylon.physicsEngine.js.map
  68797. var BABYLON;
  68798. (function (BABYLON) {
  68799. var PhysicsHelper = /** @class */ (function () {
  68800. function PhysicsHelper(scene) {
  68801. this._scene = scene;
  68802. this._physicsEngine = this._scene.getPhysicsEngine();
  68803. if (!this._physicsEngine) {
  68804. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68805. }
  68806. }
  68807. /**
  68808. * @param {Vector3} origin the origin of the explosion
  68809. * @param {number} radius the explosion radius
  68810. * @param {number} strength the explosion strength
  68811. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68812. */
  68813. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68814. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68815. if (!this._physicsEngine) {
  68816. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68817. return null;
  68818. }
  68819. var impostors = this._physicsEngine.getImpostors();
  68820. if (impostors.length === 0) {
  68821. return null;
  68822. }
  68823. var event = new PhysicsRadialExplosionEvent(this._scene);
  68824. impostors.forEach(function (impostor) {
  68825. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68826. if (!impostorForceAndContactPoint) {
  68827. return;
  68828. }
  68829. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68830. });
  68831. event.dispose(false);
  68832. return event;
  68833. };
  68834. /**
  68835. * @param {Vector3} origin the origin of the explosion
  68836. * @param {number} radius the explosion radius
  68837. * @param {number} strength the explosion strength
  68838. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68839. */
  68840. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68841. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68842. if (!this._physicsEngine) {
  68843. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68844. return null;
  68845. }
  68846. var impostors = this._physicsEngine.getImpostors();
  68847. if (impostors.length === 0) {
  68848. return null;
  68849. }
  68850. var event = new PhysicsRadialExplosionEvent(this._scene);
  68851. impostors.forEach(function (impostor) {
  68852. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68853. if (!impostorForceAndContactPoint) {
  68854. return;
  68855. }
  68856. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68857. });
  68858. event.dispose(false);
  68859. return event;
  68860. };
  68861. /**
  68862. * @param {Vector3} origin the origin of the explosion
  68863. * @param {number} radius the explosion radius
  68864. * @param {number} strength the explosion strength
  68865. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68866. */
  68867. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68868. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68869. if (!this._physicsEngine) {
  68870. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68871. return null;
  68872. }
  68873. var impostors = this._physicsEngine.getImpostors();
  68874. if (impostors.length === 0) {
  68875. return null;
  68876. }
  68877. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68878. event.dispose(false);
  68879. return event;
  68880. };
  68881. /**
  68882. * @param {Vector3} origin the origin of the updraft
  68883. * @param {number} radius the radius of the updraft
  68884. * @param {number} strength the strength of the updraft
  68885. * @param {number} height the height of the updraft
  68886. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68887. */
  68888. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68889. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68890. if (!this._physicsEngine) {
  68891. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68892. return null;
  68893. }
  68894. if (this._physicsEngine.getImpostors().length === 0) {
  68895. return null;
  68896. }
  68897. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68898. event.dispose(false);
  68899. return event;
  68900. };
  68901. /**
  68902. * @param {Vector3} origin the of the vortex
  68903. * @param {number} radius the radius of the vortex
  68904. * @param {number} strength the strength of the vortex
  68905. * @param {number} height the height of the vortex
  68906. */
  68907. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68908. if (!this._physicsEngine) {
  68909. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68910. return null;
  68911. }
  68912. if (this._physicsEngine.getImpostors().length === 0) {
  68913. return null;
  68914. }
  68915. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68916. event.dispose(false);
  68917. return event;
  68918. };
  68919. return PhysicsHelper;
  68920. }());
  68921. BABYLON.PhysicsHelper = PhysicsHelper;
  68922. /***** Radial explosion *****/
  68923. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68924. function PhysicsRadialExplosionEvent(scene) {
  68925. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68926. this._rays = [];
  68927. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68928. this._scene = scene;
  68929. }
  68930. /**
  68931. * Returns the data related to the radial explosion event (sphere & rays).
  68932. * @returns {PhysicsRadialExplosionEventData}
  68933. */
  68934. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68935. this._dataFetched = true;
  68936. return {
  68937. sphere: this._sphere,
  68938. rays: this._rays,
  68939. };
  68940. };
  68941. /**
  68942. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68943. * @param impostor
  68944. * @param {Vector3} origin the origin of the explosion
  68945. * @param {number} radius the explosion radius
  68946. * @param {number} strength the explosion strength
  68947. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68948. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68949. */
  68950. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68951. if (impostor.mass === 0) {
  68952. return null;
  68953. }
  68954. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68955. return null;
  68956. }
  68957. if (impostor.object.getClassName() !== 'Mesh') {
  68958. return null;
  68959. }
  68960. var impostorObject = impostor.object;
  68961. var impostorObjectCenter = impostor.getObjectCenter();
  68962. var direction = impostorObjectCenter.subtract(origin);
  68963. var ray = new BABYLON.Ray(origin, direction, radius);
  68964. this._rays.push(ray);
  68965. var hit = ray.intersectsMesh(impostorObject);
  68966. var contactPoint = hit.pickedPoint;
  68967. if (!contactPoint) {
  68968. return null;
  68969. }
  68970. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68971. if (distanceFromOrigin > radius) {
  68972. return null;
  68973. }
  68974. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68975. ? strength
  68976. : strength * (1 - (distanceFromOrigin / radius));
  68977. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68978. return { force: force, contactPoint: contactPoint };
  68979. };
  68980. /**
  68981. * Disposes the sphere.
  68982. * @param {bolean} force
  68983. */
  68984. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68985. var _this = this;
  68986. if (force === void 0) { force = true; }
  68987. if (force) {
  68988. this._sphere.dispose();
  68989. }
  68990. else {
  68991. setTimeout(function () {
  68992. if (!_this._dataFetched) {
  68993. _this._sphere.dispose();
  68994. }
  68995. }, 0);
  68996. }
  68997. };
  68998. /*** Helpers ***/
  68999. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  69000. if (!this._sphere) {
  69001. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  69002. this._sphere.isVisible = false;
  69003. }
  69004. };
  69005. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  69006. var impostorObject = impostor.object;
  69007. this._prepareSphere();
  69008. this._sphere.position = origin;
  69009. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  69010. this._sphere._updateBoundingInfo();
  69011. this._sphere.computeWorldMatrix(true);
  69012. return this._sphere.intersectsMesh(impostorObject, true);
  69013. };
  69014. return PhysicsRadialExplosionEvent;
  69015. }());
  69016. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  69017. /***** Gravitational Field *****/
  69018. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  69019. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  69020. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  69021. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69022. this._physicsHelper = physicsHelper;
  69023. this._scene = scene;
  69024. this._origin = origin;
  69025. this._radius = radius;
  69026. this._strength = strength;
  69027. this._falloff = falloff;
  69028. this._tickCallback = this._tick.bind(this);
  69029. }
  69030. /**
  69031. * Returns the data related to the gravitational field event (sphere).
  69032. * @returns {PhysicsGravitationalFieldEventData}
  69033. */
  69034. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  69035. this._dataFetched = true;
  69036. return {
  69037. sphere: this._sphere,
  69038. };
  69039. };
  69040. /**
  69041. * Enables the gravitational field.
  69042. */
  69043. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  69044. this._tickCallback.call(this);
  69045. this._scene.registerBeforeRender(this._tickCallback);
  69046. };
  69047. /**
  69048. * Disables the gravitational field.
  69049. */
  69050. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  69051. this._scene.unregisterBeforeRender(this._tickCallback);
  69052. };
  69053. /**
  69054. * Disposes the sphere.
  69055. * @param {bolean} force
  69056. */
  69057. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  69058. var _this = this;
  69059. if (force === void 0) { force = true; }
  69060. if (force) {
  69061. this._sphere.dispose();
  69062. }
  69063. else {
  69064. setTimeout(function () {
  69065. if (!_this._dataFetched) {
  69066. _this._sphere.dispose();
  69067. }
  69068. }, 0);
  69069. }
  69070. };
  69071. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  69072. // Since the params won't change, we fetch the event only once
  69073. if (this._sphere) {
  69074. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  69075. }
  69076. else {
  69077. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  69078. if (radialExplosionEvent) {
  69079. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  69080. }
  69081. }
  69082. };
  69083. return PhysicsGravitationalFieldEvent;
  69084. }());
  69085. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  69086. /***** Updraft *****/
  69087. var PhysicsUpdraftEvent = /** @class */ (function () {
  69088. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  69089. this._scene = _scene;
  69090. this._origin = _origin;
  69091. this._radius = _radius;
  69092. this._strength = _strength;
  69093. this._height = _height;
  69094. this._updraftMode = _updraftMode;
  69095. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69096. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  69097. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69098. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69099. this._physicsEngine = this._scene.getPhysicsEngine();
  69100. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69101. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69102. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69103. this._originDirection = this._origin.subtract(this._originTop).normalize();
  69104. }
  69105. this._tickCallback = this._tick.bind(this);
  69106. }
  69107. /**
  69108. * Returns the data related to the updraft event (cylinder).
  69109. * @returns {PhysicsUpdraftEventData}
  69110. */
  69111. PhysicsUpdraftEvent.prototype.getData = function () {
  69112. this._dataFetched = true;
  69113. return {
  69114. cylinder: this._cylinder,
  69115. };
  69116. };
  69117. /**
  69118. * Enables the updraft.
  69119. */
  69120. PhysicsUpdraftEvent.prototype.enable = function () {
  69121. this._tickCallback.call(this);
  69122. this._scene.registerBeforeRender(this._tickCallback);
  69123. };
  69124. /**
  69125. * Disables the cortex.
  69126. */
  69127. PhysicsUpdraftEvent.prototype.disable = function () {
  69128. this._scene.unregisterBeforeRender(this._tickCallback);
  69129. };
  69130. /**
  69131. * Disposes the sphere.
  69132. * @param {bolean} force
  69133. */
  69134. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  69135. var _this = this;
  69136. if (force === void 0) { force = true; }
  69137. if (force) {
  69138. this._cylinder.dispose();
  69139. }
  69140. else {
  69141. setTimeout(function () {
  69142. if (!_this._dataFetched) {
  69143. _this._cylinder.dispose();
  69144. }
  69145. }, 0);
  69146. }
  69147. };
  69148. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69149. if (impostor.mass === 0) {
  69150. return null;
  69151. }
  69152. if (!this._intersectsWithCylinder(impostor)) {
  69153. return null;
  69154. }
  69155. var impostorObjectCenter = impostor.getObjectCenter();
  69156. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69157. var direction = this._originDirection;
  69158. }
  69159. else {
  69160. var direction = impostorObjectCenter.subtract(this._originTop);
  69161. }
  69162. var multiplier = this._strength * -1;
  69163. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69164. return { force: force, contactPoint: impostorObjectCenter };
  69165. };
  69166. PhysicsUpdraftEvent.prototype._tick = function () {
  69167. var _this = this;
  69168. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69169. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69170. if (!impostorForceAndContactPoint) {
  69171. return;
  69172. }
  69173. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69174. });
  69175. };
  69176. /*** Helpers ***/
  69177. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69178. if (!this._cylinder) {
  69179. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69180. height: this._height,
  69181. diameter: this._radius * 2,
  69182. }, this._scene);
  69183. this._cylinder.isVisible = false;
  69184. }
  69185. };
  69186. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69187. var impostorObject = impostor.object;
  69188. this._prepareCylinder();
  69189. this._cylinder.position = this._cylinderPosition;
  69190. return this._cylinder.intersectsMesh(impostorObject, true);
  69191. };
  69192. return PhysicsUpdraftEvent;
  69193. }());
  69194. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69195. /***** Vortex *****/
  69196. var PhysicsVortexEvent = /** @class */ (function () {
  69197. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69198. this._scene = _scene;
  69199. this._origin = _origin;
  69200. this._radius = _radius;
  69201. this._strength = _strength;
  69202. this._height = _height;
  69203. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69204. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69205. this._updraftMultiplier = 0.02;
  69206. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69207. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69208. this._physicsEngine = this._scene.getPhysicsEngine();
  69209. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69210. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69211. this._tickCallback = this._tick.bind(this);
  69212. }
  69213. /**
  69214. * Returns the data related to the vortex event (cylinder).
  69215. * @returns {PhysicsVortexEventData}
  69216. */
  69217. PhysicsVortexEvent.prototype.getData = function () {
  69218. this._dataFetched = true;
  69219. return {
  69220. cylinder: this._cylinder,
  69221. };
  69222. };
  69223. /**
  69224. * Enables the vortex.
  69225. */
  69226. PhysicsVortexEvent.prototype.enable = function () {
  69227. this._tickCallback.call(this);
  69228. this._scene.registerBeforeRender(this._tickCallback);
  69229. };
  69230. /**
  69231. * Disables the cortex.
  69232. */
  69233. PhysicsVortexEvent.prototype.disable = function () {
  69234. this._scene.unregisterBeforeRender(this._tickCallback);
  69235. };
  69236. /**
  69237. * Disposes the sphere.
  69238. * @param {bolean} force
  69239. */
  69240. PhysicsVortexEvent.prototype.dispose = function (force) {
  69241. var _this = this;
  69242. if (force === void 0) { force = true; }
  69243. if (force) {
  69244. this._cylinder.dispose();
  69245. }
  69246. else {
  69247. setTimeout(function () {
  69248. if (!_this._dataFetched) {
  69249. _this._cylinder.dispose();
  69250. }
  69251. }, 0);
  69252. }
  69253. };
  69254. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69255. if (impostor.mass === 0) {
  69256. return null;
  69257. }
  69258. if (!this._intersectsWithCylinder(impostor)) {
  69259. return null;
  69260. }
  69261. if (impostor.object.getClassName() !== 'Mesh') {
  69262. return null;
  69263. }
  69264. var impostorObject = impostor.object;
  69265. var impostorObjectCenter = impostor.getObjectCenter();
  69266. 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)
  69267. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69268. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69269. var hit = ray.intersectsMesh(impostorObject);
  69270. var contactPoint = hit.pickedPoint;
  69271. if (!contactPoint) {
  69272. return null;
  69273. }
  69274. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69275. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69276. var directionToOrigin = contactPoint.normalize();
  69277. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69278. directionToOrigin = directionToOrigin.negate();
  69279. }
  69280. // TODO: find a more physically based solution
  69281. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69282. var forceX = directionToOrigin.x * this._strength / 8;
  69283. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69284. var forceZ = directionToOrigin.z * this._strength / 8;
  69285. }
  69286. else {
  69287. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69288. var forceY = this._originTop.y * this._updraftMultiplier;
  69289. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69290. }
  69291. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69292. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69293. return { force: force, contactPoint: impostorObjectCenter };
  69294. };
  69295. PhysicsVortexEvent.prototype._tick = function () {
  69296. var _this = this;
  69297. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69298. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69299. if (!impostorForceAndContactPoint) {
  69300. return;
  69301. }
  69302. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69303. });
  69304. };
  69305. /*** Helpers ***/
  69306. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69307. if (!this._cylinder) {
  69308. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69309. height: this._height,
  69310. diameter: this._radius * 2,
  69311. }, this._scene);
  69312. this._cylinder.isVisible = false;
  69313. }
  69314. };
  69315. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69316. var impostorObject = impostor.object;
  69317. this._prepareCylinder();
  69318. this._cylinder.position = this._cylinderPosition;
  69319. return this._cylinder.intersectsMesh(impostorObject, true);
  69320. };
  69321. return PhysicsVortexEvent;
  69322. }());
  69323. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69324. /***** Enums *****/
  69325. /**
  69326. * The strenght of the force in correspondence to the distance of the affected object
  69327. */
  69328. var PhysicsRadialImpulseFalloff;
  69329. (function (PhysicsRadialImpulseFalloff) {
  69330. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69331. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69332. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69333. /**
  69334. * The strenght of the force in correspondence to the distance of the affected object
  69335. */
  69336. var PhysicsUpdraftMode;
  69337. (function (PhysicsUpdraftMode) {
  69338. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69339. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69340. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69341. })(BABYLON || (BABYLON = {}));
  69342. //# sourceMappingURL=babylon.physicsHelper.js.map
  69343. var BABYLON;
  69344. (function (BABYLON) {
  69345. var CannonJSPlugin = /** @class */ (function () {
  69346. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69347. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69348. if (iterations === void 0) { iterations = 10; }
  69349. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69350. this.name = "CannonJSPlugin";
  69351. this._physicsMaterials = new Array();
  69352. this._fixedTimeStep = 1 / 60;
  69353. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69354. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69355. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69356. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69357. this._tmpPosition = BABYLON.Vector3.Zero();
  69358. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69359. this._tmpUnityRotation = new BABYLON.Quaternion();
  69360. if (!this.isSupported()) {
  69361. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69362. return;
  69363. }
  69364. this._extendNamespace();
  69365. this.world = new this.BJSCANNON.World();
  69366. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69367. this.world.solver.iterations = iterations;
  69368. }
  69369. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69370. this.world.gravity.copy(gravity);
  69371. };
  69372. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69373. this._fixedTimeStep = timeStep;
  69374. };
  69375. CannonJSPlugin.prototype.getTimeStep = function () {
  69376. return this._fixedTimeStep;
  69377. };
  69378. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69379. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69380. };
  69381. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69382. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69383. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69384. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69385. };
  69386. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69387. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69388. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69389. impostor.physicsBody.applyForce(impulse, worldPoint);
  69390. };
  69391. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69392. //parent-child relationship. Does this impostor has a parent impostor?
  69393. if (impostor.parent) {
  69394. if (impostor.physicsBody) {
  69395. this.removePhysicsBody(impostor);
  69396. //TODO is that needed?
  69397. impostor.forceUpdate();
  69398. }
  69399. return;
  69400. }
  69401. //should a new body be created for this impostor?
  69402. if (impostor.isBodyInitRequired()) {
  69403. var shape = this._createShape(impostor);
  69404. //unregister events, if body is being changed
  69405. var oldBody = impostor.physicsBody;
  69406. if (oldBody) {
  69407. this.removePhysicsBody(impostor);
  69408. }
  69409. //create the body and material
  69410. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69411. var bodyCreationObject = {
  69412. mass: impostor.getParam("mass"),
  69413. material: material
  69414. };
  69415. // A simple extend, in case native options were used.
  69416. var nativeOptions = impostor.getParam("nativeOptions");
  69417. for (var key in nativeOptions) {
  69418. if (nativeOptions.hasOwnProperty(key)) {
  69419. bodyCreationObject[key] = nativeOptions[key];
  69420. }
  69421. }
  69422. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69423. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69424. this.world.addEventListener("preStep", impostor.beforeStep);
  69425. this.world.addEventListener("postStep", impostor.afterStep);
  69426. impostor.physicsBody.addShape(shape);
  69427. this.world.add(impostor.physicsBody);
  69428. //try to keep the body moving in the right direction by taking old properties.
  69429. //Should be tested!
  69430. if (oldBody) {
  69431. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69432. impostor.physicsBody[param].copy(oldBody[param]);
  69433. });
  69434. }
  69435. this._processChildMeshes(impostor);
  69436. }
  69437. //now update the body's transformation
  69438. this._updatePhysicsBodyTransformation(impostor);
  69439. };
  69440. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69441. var _this = this;
  69442. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69443. var currentRotation = mainImpostor.object.rotationQuaternion;
  69444. if (meshChildren.length) {
  69445. var processMesh = function (localPosition, mesh) {
  69446. if (!currentRotation || !mesh.rotationQuaternion) {
  69447. return;
  69448. }
  69449. var childImpostor = mesh.getPhysicsImpostor();
  69450. if (childImpostor) {
  69451. var parent = childImpostor.parent;
  69452. if (parent !== mainImpostor) {
  69453. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69454. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69455. if (childImpostor.physicsBody) {
  69456. _this.removePhysicsBody(childImpostor);
  69457. childImpostor.physicsBody = null;
  69458. }
  69459. childImpostor.parent = mainImpostor;
  69460. childImpostor.resetUpdateFlags();
  69461. 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));
  69462. //Add the mass of the children.
  69463. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69464. }
  69465. }
  69466. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69467. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69468. };
  69469. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69470. }
  69471. };
  69472. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69473. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69474. this.world.removeEventListener("preStep", impostor.beforeStep);
  69475. this.world.removeEventListener("postStep", impostor.afterStep);
  69476. this.world.remove(impostor.physicsBody);
  69477. };
  69478. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69479. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69480. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69481. if (!mainBody || !connectedBody) {
  69482. return;
  69483. }
  69484. var constraint;
  69485. var jointData = impostorJoint.joint.jointData;
  69486. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69487. var constraintData = {
  69488. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69489. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69490. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69491. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69492. maxForce: jointData.nativeParams.maxForce,
  69493. collideConnected: !!jointData.collision
  69494. };
  69495. switch (impostorJoint.joint.type) {
  69496. case BABYLON.PhysicsJoint.HingeJoint:
  69497. case BABYLON.PhysicsJoint.Hinge2Joint:
  69498. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69499. break;
  69500. case BABYLON.PhysicsJoint.DistanceJoint:
  69501. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69502. break;
  69503. case BABYLON.PhysicsJoint.SpringJoint:
  69504. var springData = jointData;
  69505. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69506. restLength: springData.length,
  69507. stiffness: springData.stiffness,
  69508. damping: springData.damping,
  69509. localAnchorA: constraintData.pivotA,
  69510. localAnchorB: constraintData.pivotB
  69511. });
  69512. break;
  69513. case BABYLON.PhysicsJoint.LockJoint:
  69514. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69515. break;
  69516. case BABYLON.PhysicsJoint.PointToPointJoint:
  69517. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69518. default:
  69519. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69520. break;
  69521. }
  69522. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69523. constraint.collideConnected = !!jointData.collision;
  69524. impostorJoint.joint.physicsJoint = constraint;
  69525. //don't add spring as constraint, as it is not one.
  69526. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69527. this.world.addConstraint(constraint);
  69528. }
  69529. else {
  69530. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69531. constraint.applyForce();
  69532. });
  69533. }
  69534. };
  69535. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69536. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69537. };
  69538. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69539. var index;
  69540. var mat;
  69541. for (index = 0; index < this._physicsMaterials.length; index++) {
  69542. mat = this._physicsMaterials[index];
  69543. if (mat.friction === friction && mat.restitution === restitution) {
  69544. return mat;
  69545. }
  69546. }
  69547. var currentMat = new this.BJSCANNON.Material(name);
  69548. currentMat.friction = friction;
  69549. currentMat.restitution = restitution;
  69550. this._physicsMaterials.push(currentMat);
  69551. return currentMat;
  69552. };
  69553. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69554. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69555. };
  69556. CannonJSPlugin.prototype._createShape = function (impostor) {
  69557. var object = impostor.object;
  69558. var returnValue;
  69559. var extendSize = impostor.getObjectExtendSize();
  69560. switch (impostor.type) {
  69561. case BABYLON.PhysicsImpostor.SphereImpostor:
  69562. var radiusX = extendSize.x;
  69563. var radiusY = extendSize.y;
  69564. var radiusZ = extendSize.z;
  69565. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69566. break;
  69567. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69568. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69569. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69570. break;
  69571. case BABYLON.PhysicsImpostor.BoxImpostor:
  69572. var box = extendSize.scale(0.5);
  69573. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69574. break;
  69575. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69576. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69577. returnValue = new this.BJSCANNON.Plane();
  69578. break;
  69579. case BABYLON.PhysicsImpostor.MeshImpostor:
  69580. // should transform the vertex data to world coordinates!!
  69581. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69582. var rawFaces = object.getIndices ? object.getIndices() : [];
  69583. if (!rawVerts)
  69584. return;
  69585. // get only scale! so the object could transform correctly.
  69586. var oldPosition = object.position.clone();
  69587. var oldRotation = object.rotation && object.rotation.clone();
  69588. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69589. object.position.copyFromFloats(0, 0, 0);
  69590. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69591. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69592. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69593. var transform = object.computeWorldMatrix(true);
  69594. // convert rawVerts to object space
  69595. var temp = new Array();
  69596. var index;
  69597. for (index = 0; index < rawVerts.length; index += 3) {
  69598. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69599. }
  69600. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69601. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69602. //now set back the transformation!
  69603. object.position.copyFrom(oldPosition);
  69604. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69605. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69606. break;
  69607. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69608. var oldPosition2 = object.position.clone();
  69609. var oldRotation2 = object.rotation && object.rotation.clone();
  69610. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69611. object.position.copyFromFloats(0, 0, 0);
  69612. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69613. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69614. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69615. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69616. returnValue = this._createHeightmap(object);
  69617. object.position.copyFrom(oldPosition2);
  69618. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69619. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69620. object.computeWorldMatrix(true);
  69621. break;
  69622. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69623. returnValue = new this.BJSCANNON.Particle();
  69624. break;
  69625. }
  69626. return returnValue;
  69627. };
  69628. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69629. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69630. var transform = object.computeWorldMatrix(true);
  69631. // convert rawVerts to object space
  69632. var temp = new Array();
  69633. var index;
  69634. for (index = 0; index < pos.length; index += 3) {
  69635. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69636. }
  69637. pos = temp;
  69638. var matrix = new Array();
  69639. //For now pointDepth will not be used and will be automatically calculated.
  69640. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69641. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69642. var boundingInfo = object.getBoundingInfo();
  69643. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69644. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69645. var elementSize = dim * 2 / arraySize;
  69646. for (var i = 0; i < pos.length; i = i + 3) {
  69647. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69648. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69649. var y = -pos[i + 2] + minY;
  69650. if (!matrix[x]) {
  69651. matrix[x] = [];
  69652. }
  69653. if (!matrix[x][z]) {
  69654. matrix[x][z] = y;
  69655. }
  69656. matrix[x][z] = Math.max(y, matrix[x][z]);
  69657. }
  69658. for (var x = 0; x <= arraySize; ++x) {
  69659. if (!matrix[x]) {
  69660. var loc = 1;
  69661. while (!matrix[(x + loc) % arraySize]) {
  69662. loc++;
  69663. }
  69664. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69665. //console.log("missing x", x);
  69666. }
  69667. for (var z = 0; z <= arraySize; ++z) {
  69668. if (!matrix[x][z]) {
  69669. var loc = 1;
  69670. var newValue;
  69671. while (newValue === undefined) {
  69672. newValue = matrix[x][(z + loc++) % arraySize];
  69673. }
  69674. matrix[x][z] = newValue;
  69675. }
  69676. }
  69677. }
  69678. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69679. elementSize: elementSize
  69680. });
  69681. //For future reference, needed for body transformation
  69682. shape.minY = minY;
  69683. return shape;
  69684. };
  69685. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69686. var object = impostor.object;
  69687. //make sure it is updated...
  69688. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69689. // The delta between the mesh position and the mesh bounding box center
  69690. var bInfo = object.getBoundingInfo();
  69691. if (!bInfo)
  69692. return;
  69693. var center = impostor.getObjectCenter();
  69694. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69695. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69696. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69697. this._tmpPosition.copyFrom(center);
  69698. var quaternion = object.rotationQuaternion;
  69699. if (!quaternion) {
  69700. return;
  69701. }
  69702. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69703. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69704. //-90 DEG in X, precalculated
  69705. quaternion = quaternion.multiply(this._minus90X);
  69706. //Invert! (Precalculated, 90 deg in X)
  69707. //No need to clone. this will never change.
  69708. impostor.setDeltaRotation(this._plus90X);
  69709. }
  69710. //If it is a heightfield, if should be centered.
  69711. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69712. var mesh = object;
  69713. var boundingInfo = mesh.getBoundingInfo();
  69714. //calculate the correct body position:
  69715. var rotationQuaternion = mesh.rotationQuaternion;
  69716. mesh.rotationQuaternion = this._tmpUnityRotation;
  69717. mesh.computeWorldMatrix(true);
  69718. //get original center with no rotation
  69719. var c = center.clone();
  69720. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69721. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69722. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69723. mesh.setPivotMatrix(p);
  69724. mesh.computeWorldMatrix(true);
  69725. //calculate the translation
  69726. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69727. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69728. //add it inverted to the delta
  69729. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69730. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69731. //rotation is back
  69732. mesh.rotationQuaternion = rotationQuaternion;
  69733. mesh.setPivotMatrix(oldPivot);
  69734. mesh.computeWorldMatrix(true);
  69735. }
  69736. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69737. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69738. //this._tmpPosition.copyFrom(object.position);
  69739. }
  69740. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69741. //Now update the impostor object
  69742. impostor.physicsBody.position.copy(this._tmpPosition);
  69743. impostor.physicsBody.quaternion.copy(quaternion);
  69744. };
  69745. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69746. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69747. if (impostor.object.rotationQuaternion) {
  69748. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69749. }
  69750. };
  69751. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69752. impostor.physicsBody.position.copy(newPosition);
  69753. impostor.physicsBody.quaternion.copy(newRotation);
  69754. };
  69755. CannonJSPlugin.prototype.isSupported = function () {
  69756. return this.BJSCANNON !== undefined;
  69757. };
  69758. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69759. impostor.physicsBody.velocity.copy(velocity);
  69760. };
  69761. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69762. impostor.physicsBody.angularVelocity.copy(velocity);
  69763. };
  69764. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69765. var v = impostor.physicsBody.velocity;
  69766. if (!v) {
  69767. return null;
  69768. }
  69769. return new BABYLON.Vector3(v.x, v.y, v.z);
  69770. };
  69771. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69772. var v = impostor.physicsBody.angularVelocity;
  69773. if (!v) {
  69774. return null;
  69775. }
  69776. return new BABYLON.Vector3(v.x, v.y, v.z);
  69777. };
  69778. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69779. impostor.physicsBody.mass = mass;
  69780. impostor.physicsBody.updateMassProperties();
  69781. };
  69782. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69783. return impostor.physicsBody.mass;
  69784. };
  69785. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69786. return impostor.physicsBody.material.friction;
  69787. };
  69788. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69789. impostor.physicsBody.material.friction = friction;
  69790. };
  69791. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69792. return impostor.physicsBody.material.restitution;
  69793. };
  69794. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69795. impostor.physicsBody.material.restitution = restitution;
  69796. };
  69797. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69798. impostor.physicsBody.sleep();
  69799. };
  69800. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69801. impostor.physicsBody.wakeUp();
  69802. };
  69803. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69804. joint.physicsJoint.distance = maxDistance;
  69805. };
  69806. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69807. // if (!motorIndex) {
  69808. // joint.physicsJoint.enableMotor();
  69809. // }
  69810. // }
  69811. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69812. // if (!motorIndex) {
  69813. // joint.physicsJoint.disableMotor();
  69814. // }
  69815. // }
  69816. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69817. if (!motorIndex) {
  69818. joint.physicsJoint.enableMotor();
  69819. joint.physicsJoint.setMotorSpeed(speed);
  69820. if (maxForce) {
  69821. this.setLimit(joint, maxForce);
  69822. }
  69823. }
  69824. };
  69825. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69826. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69827. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69828. };
  69829. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69830. var body = impostor.physicsBody;
  69831. mesh.position.x = body.position.x;
  69832. mesh.position.y = body.position.y;
  69833. mesh.position.z = body.position.z;
  69834. if (mesh.rotationQuaternion) {
  69835. mesh.rotationQuaternion.x = body.quaternion.x;
  69836. mesh.rotationQuaternion.y = body.quaternion.y;
  69837. mesh.rotationQuaternion.z = body.quaternion.z;
  69838. mesh.rotationQuaternion.w = body.quaternion.w;
  69839. }
  69840. };
  69841. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69842. var shape = impostor.physicsBody.shapes[0];
  69843. return shape.boundingSphereRadius;
  69844. };
  69845. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69846. var shape = impostor.physicsBody.shapes[0];
  69847. result.x = shape.halfExtents.x * 2;
  69848. result.y = shape.halfExtents.y * 2;
  69849. result.z = shape.halfExtents.z * 2;
  69850. };
  69851. CannonJSPlugin.prototype.dispose = function () {
  69852. };
  69853. CannonJSPlugin.prototype._extendNamespace = function () {
  69854. //this will force cannon to execute at least one step when using interpolation
  69855. var step_tmp1 = new this.BJSCANNON.Vec3();
  69856. var Engine = this.BJSCANNON;
  69857. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69858. maxSubSteps = maxSubSteps || 10;
  69859. timeSinceLastCalled = timeSinceLastCalled || 0;
  69860. if (timeSinceLastCalled === 0) {
  69861. this.internalStep(dt);
  69862. this.time += dt;
  69863. }
  69864. else {
  69865. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69866. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69867. var t0 = performance.now();
  69868. for (var i = 0; i !== internalSteps; i++) {
  69869. this.internalStep(dt);
  69870. if (performance.now() - t0 > dt * 1000) {
  69871. break;
  69872. }
  69873. }
  69874. this.time += timeSinceLastCalled;
  69875. var h = this.time % dt;
  69876. var h_div_dt = h / dt;
  69877. var interpvelo = step_tmp1;
  69878. var bodies = this.bodies;
  69879. for (var j = 0; j !== bodies.length; j++) {
  69880. var b = bodies[j];
  69881. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69882. b.position.vsub(b.previousPosition, interpvelo);
  69883. interpvelo.scale(h_div_dt, interpvelo);
  69884. b.position.vadd(interpvelo, b.interpolatedPosition);
  69885. }
  69886. else {
  69887. b.interpolatedPosition.copy(b.position);
  69888. b.interpolatedQuaternion.copy(b.quaternion);
  69889. }
  69890. }
  69891. }
  69892. };
  69893. };
  69894. return CannonJSPlugin;
  69895. }());
  69896. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69897. })(BABYLON || (BABYLON = {}));
  69898. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69899. var BABYLON;
  69900. (function (BABYLON) {
  69901. var OimoJSPlugin = /** @class */ (function () {
  69902. function OimoJSPlugin(iterations) {
  69903. this.name = "OimoJSPlugin";
  69904. this._tmpImpostorsArray = [];
  69905. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69906. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69907. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69908. this.world.worldscale(1);
  69909. this.world.clear();
  69910. //making sure no stats are calculated
  69911. this.world.isNoStat = true;
  69912. }
  69913. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69914. this.world.gravity.copy(gravity);
  69915. };
  69916. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69917. this.world.timeStep = timeStep;
  69918. };
  69919. OimoJSPlugin.prototype.getTimeStep = function () {
  69920. return this.world.timeStep;
  69921. };
  69922. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69923. var _this = this;
  69924. impostors.forEach(function (impostor) {
  69925. impostor.beforeStep();
  69926. });
  69927. this.world.step();
  69928. impostors.forEach(function (impostor) {
  69929. impostor.afterStep();
  69930. //update the ordered impostors array
  69931. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69932. });
  69933. //check for collisions
  69934. var contact = this.world.contacts;
  69935. while (contact !== null) {
  69936. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69937. contact = contact.next;
  69938. continue;
  69939. }
  69940. //is this body colliding with any other? get the impostor
  69941. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69942. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69943. if (!mainImpostor || !collidingImpostor) {
  69944. contact = contact.next;
  69945. continue;
  69946. }
  69947. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69948. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69949. contact = contact.next;
  69950. }
  69951. };
  69952. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69953. var mass = impostor.physicsBody.massInfo.mass;
  69954. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69955. };
  69956. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69957. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69958. this.applyImpulse(impostor, force, contactPoint);
  69959. };
  69960. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69961. var _this = this;
  69962. //parent-child relationship. Does this impostor has a parent impostor?
  69963. if (impostor.parent) {
  69964. if (impostor.physicsBody) {
  69965. this.removePhysicsBody(impostor);
  69966. //TODO is that needed?
  69967. impostor.forceUpdate();
  69968. }
  69969. return;
  69970. }
  69971. if (impostor.isBodyInitRequired()) {
  69972. var bodyConfig = {
  69973. name: impostor.uniqueId,
  69974. //Oimo must have mass, also for static objects.
  69975. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69976. size: [],
  69977. type: [],
  69978. pos: [],
  69979. rot: [],
  69980. move: impostor.getParam("mass") !== 0,
  69981. //Supporting older versions of Oimo
  69982. world: this.world
  69983. };
  69984. var impostors = [impostor];
  69985. var addToArray = function (parent) {
  69986. if (!parent.getChildMeshes)
  69987. return;
  69988. parent.getChildMeshes().forEach(function (m) {
  69989. if (m.physicsImpostor) {
  69990. impostors.push(m.physicsImpostor);
  69991. //m.physicsImpostor._init();
  69992. }
  69993. });
  69994. };
  69995. addToArray(impostor.object);
  69996. var checkWithEpsilon_1 = function (value) {
  69997. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69998. };
  69999. impostors.forEach(function (i) {
  70000. if (!impostor.object.rotationQuaternion) {
  70001. return;
  70002. }
  70003. //get the correct bounding box
  70004. var oldQuaternion = i.object.rotationQuaternion;
  70005. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  70006. x: impostor.object.rotationQuaternion.x,
  70007. y: impostor.object.rotationQuaternion.y,
  70008. z: impostor.object.rotationQuaternion.z,
  70009. s: impostor.object.rotationQuaternion.w
  70010. });
  70011. var extendSize = i.getObjectExtendSize();
  70012. if (i === impostor) {
  70013. var center = impostor.getObjectCenter();
  70014. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  70015. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  70016. //Can also use Array.prototype.push.apply
  70017. bodyConfig.pos.push(center.x);
  70018. bodyConfig.pos.push(center.y);
  70019. bodyConfig.pos.push(center.z);
  70020. //tmp solution
  70021. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70022. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70023. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  70024. }
  70025. else {
  70026. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  70027. bodyConfig.pos.push(localPosition.x);
  70028. bodyConfig.pos.push(localPosition.y);
  70029. bodyConfig.pos.push(localPosition.z);
  70030. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  70031. bodyConfig.rot.push(0);
  70032. bodyConfig.rot.push(0);
  70033. bodyConfig.rot.push(0);
  70034. }
  70035. // register mesh
  70036. switch (i.type) {
  70037. case BABYLON.PhysicsImpostor.ParticleImpostor:
  70038. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  70039. case BABYLON.PhysicsImpostor.SphereImpostor:
  70040. var radiusX = extendSize.x;
  70041. var radiusY = extendSize.y;
  70042. var radiusZ = extendSize.z;
  70043. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  70044. bodyConfig.type.push('sphere');
  70045. //due to the way oimo works with compounds, add 3 times
  70046. bodyConfig.size.push(size);
  70047. bodyConfig.size.push(size);
  70048. bodyConfig.size.push(size);
  70049. break;
  70050. case BABYLON.PhysicsImpostor.CylinderImpostor:
  70051. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  70052. var sizeY = checkWithEpsilon_1(extendSize.y);
  70053. bodyConfig.type.push('cylinder');
  70054. bodyConfig.size.push(sizeX);
  70055. bodyConfig.size.push(sizeY);
  70056. //due to the way oimo works with compounds, add one more value.
  70057. bodyConfig.size.push(sizeY);
  70058. break;
  70059. case BABYLON.PhysicsImpostor.PlaneImpostor:
  70060. case BABYLON.PhysicsImpostor.BoxImpostor:
  70061. default:
  70062. var sizeX = checkWithEpsilon_1(extendSize.x);
  70063. var sizeY = checkWithEpsilon_1(extendSize.y);
  70064. var sizeZ = checkWithEpsilon_1(extendSize.z);
  70065. bodyConfig.type.push('box');
  70066. bodyConfig.size.push(sizeX);
  70067. bodyConfig.size.push(sizeY);
  70068. bodyConfig.size.push(sizeZ);
  70069. break;
  70070. }
  70071. //actually not needed, but hey...
  70072. i.object.rotationQuaternion = oldQuaternion;
  70073. });
  70074. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  70075. }
  70076. else {
  70077. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  70078. }
  70079. impostor.setDeltaPosition(this._tmpPositionVector);
  70080. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  70081. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  70082. };
  70083. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  70084. //impostor.physicsBody.dispose();
  70085. //Same as : (older oimo versions)
  70086. this.world.removeRigidBody(impostor.physicsBody);
  70087. };
  70088. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  70089. var mainBody = impostorJoint.mainImpostor.physicsBody;
  70090. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  70091. if (!mainBody || !connectedBody) {
  70092. return;
  70093. }
  70094. var jointData = impostorJoint.joint.jointData;
  70095. var options = jointData.nativeParams || {};
  70096. var type;
  70097. var nativeJointData = {
  70098. body1: mainBody,
  70099. body2: connectedBody,
  70100. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  70101. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  70102. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  70103. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  70104. min: options.min,
  70105. max: options.max,
  70106. collision: options.collision || jointData.collision,
  70107. spring: options.spring,
  70108. //supporting older version of Oimo
  70109. world: this.world
  70110. };
  70111. switch (impostorJoint.joint.type) {
  70112. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  70113. type = "jointBall";
  70114. break;
  70115. case BABYLON.PhysicsJoint.SpringJoint:
  70116. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  70117. var springData = jointData;
  70118. nativeJointData.min = springData.length || nativeJointData.min;
  70119. //Max should also be set, just make sure it is at least min
  70120. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  70121. case BABYLON.PhysicsJoint.DistanceJoint:
  70122. type = "jointDistance";
  70123. nativeJointData.max = jointData.maxDistance;
  70124. break;
  70125. case BABYLON.PhysicsJoint.PrismaticJoint:
  70126. type = "jointPrisme";
  70127. break;
  70128. case BABYLON.PhysicsJoint.SliderJoint:
  70129. type = "jointSlide";
  70130. break;
  70131. case BABYLON.PhysicsJoint.WheelJoint:
  70132. type = "jointWheel";
  70133. break;
  70134. case BABYLON.PhysicsJoint.HingeJoint:
  70135. default:
  70136. type = "jointHinge";
  70137. break;
  70138. }
  70139. nativeJointData.type = type;
  70140. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  70141. };
  70142. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  70143. //Bug in Oimo prevents us from disposing a joint in the playground
  70144. //joint.joint.physicsJoint.dispose();
  70145. //So we will bruteforce it!
  70146. try {
  70147. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70148. }
  70149. catch (e) {
  70150. BABYLON.Tools.Warn(e);
  70151. }
  70152. };
  70153. OimoJSPlugin.prototype.isSupported = function () {
  70154. return this.BJSOIMO !== undefined;
  70155. };
  70156. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70157. if (!impostor.physicsBody.sleeping) {
  70158. //TODO check that
  70159. if (impostor.physicsBody.shapes.next) {
  70160. var parentShape = this._getLastShape(impostor.physicsBody);
  70161. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70162. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70163. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70164. }
  70165. else {
  70166. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70167. }
  70168. if (impostor.object.rotationQuaternion) {
  70169. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70170. impostor.object.rotationQuaternion.normalize();
  70171. }
  70172. }
  70173. };
  70174. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70175. var body = impostor.physicsBody;
  70176. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70177. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70178. body.syncShapes();
  70179. body.awake();
  70180. };
  70181. OimoJSPlugin.prototype._getLastShape = function (body) {
  70182. var lastShape = body.shapes;
  70183. while (lastShape.next) {
  70184. lastShape = lastShape.next;
  70185. }
  70186. return lastShape;
  70187. };
  70188. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70189. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70190. };
  70191. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70192. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70193. };
  70194. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70195. var v = impostor.physicsBody.linearVelocity;
  70196. if (!v) {
  70197. return null;
  70198. }
  70199. return new BABYLON.Vector3(v.x, v.y, v.z);
  70200. };
  70201. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70202. var v = impostor.physicsBody.angularVelocity;
  70203. if (!v) {
  70204. return null;
  70205. }
  70206. return new BABYLON.Vector3(v.x, v.y, v.z);
  70207. };
  70208. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70209. var staticBody = mass === 0;
  70210. //this will actually set the body's density and not its mass.
  70211. //But this is how oimo treats the mass variable.
  70212. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70213. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70214. };
  70215. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70216. return impostor.physicsBody.shapes.density;
  70217. };
  70218. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70219. return impostor.physicsBody.shapes.friction;
  70220. };
  70221. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70222. impostor.physicsBody.shapes.friction = friction;
  70223. };
  70224. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70225. return impostor.physicsBody.shapes.restitution;
  70226. };
  70227. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70228. impostor.physicsBody.shapes.restitution = restitution;
  70229. };
  70230. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70231. impostor.physicsBody.sleep();
  70232. };
  70233. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70234. impostor.physicsBody.awake();
  70235. };
  70236. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70237. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70238. if (minDistance !== void 0) {
  70239. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70240. }
  70241. };
  70242. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70243. //TODO separate rotational and transational motors.
  70244. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70245. if (motor) {
  70246. motor.setMotor(speed, maxForce);
  70247. }
  70248. };
  70249. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70250. //TODO separate rotational and transational motors.
  70251. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70252. if (motor) {
  70253. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70254. }
  70255. };
  70256. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70257. var body = impostor.physicsBody;
  70258. mesh.position.x = body.position.x;
  70259. mesh.position.y = body.position.y;
  70260. mesh.position.z = body.position.z;
  70261. if (mesh.rotationQuaternion) {
  70262. mesh.rotationQuaternion.x = body.orientation.x;
  70263. mesh.rotationQuaternion.y = body.orientation.y;
  70264. mesh.rotationQuaternion.z = body.orientation.z;
  70265. mesh.rotationQuaternion.w = body.orientation.s;
  70266. }
  70267. };
  70268. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70269. return impostor.physicsBody.shapes.radius;
  70270. };
  70271. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70272. var shape = impostor.physicsBody.shapes;
  70273. result.x = shape.halfWidth * 2;
  70274. result.y = shape.halfHeight * 2;
  70275. result.z = shape.halfDepth * 2;
  70276. };
  70277. OimoJSPlugin.prototype.dispose = function () {
  70278. this.world.clear();
  70279. };
  70280. return OimoJSPlugin;
  70281. }());
  70282. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70283. })(BABYLON || (BABYLON = {}));
  70284. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70285. var BABYLON;
  70286. (function (BABYLON) {
  70287. /*
  70288. * Based on jsTGALoader - Javascript loader for TGA file
  70289. * By Vincent Thibault
  70290. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70291. */
  70292. var TGATools = /** @class */ (function () {
  70293. function TGATools() {
  70294. }
  70295. TGATools.GetTGAHeader = function (data) {
  70296. var offset = 0;
  70297. var header = {
  70298. id_length: data[offset++],
  70299. colormap_type: data[offset++],
  70300. image_type: data[offset++],
  70301. colormap_index: data[offset++] | data[offset++] << 8,
  70302. colormap_length: data[offset++] | data[offset++] << 8,
  70303. colormap_size: data[offset++],
  70304. origin: [
  70305. data[offset++] | data[offset++] << 8,
  70306. data[offset++] | data[offset++] << 8
  70307. ],
  70308. width: data[offset++] | data[offset++] << 8,
  70309. height: data[offset++] | data[offset++] << 8,
  70310. pixel_size: data[offset++],
  70311. flags: data[offset++]
  70312. };
  70313. return header;
  70314. };
  70315. TGATools.UploadContent = function (gl, data) {
  70316. // Not enough data to contain header ?
  70317. if (data.length < 19) {
  70318. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70319. return;
  70320. }
  70321. // Read Header
  70322. var offset = 18;
  70323. var header = TGATools.GetTGAHeader(data);
  70324. // Assume it's a valid Targa file.
  70325. if (header.id_length + offset > data.length) {
  70326. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70327. return;
  70328. }
  70329. // Skip not needed data
  70330. offset += header.id_length;
  70331. var use_rle = false;
  70332. var use_pal = false;
  70333. var use_grey = false;
  70334. // Get some informations.
  70335. switch (header.image_type) {
  70336. case TGATools._TYPE_RLE_INDEXED:
  70337. use_rle = true;
  70338. case TGATools._TYPE_INDEXED:
  70339. use_pal = true;
  70340. break;
  70341. case TGATools._TYPE_RLE_RGB:
  70342. use_rle = true;
  70343. case TGATools._TYPE_RGB:
  70344. // use_rgb = true;
  70345. break;
  70346. case TGATools._TYPE_RLE_GREY:
  70347. use_rle = true;
  70348. case TGATools._TYPE_GREY:
  70349. use_grey = true;
  70350. break;
  70351. }
  70352. var pixel_data;
  70353. // var numAlphaBits = header.flags & 0xf;
  70354. var pixel_size = header.pixel_size >> 3;
  70355. var pixel_total = header.width * header.height * pixel_size;
  70356. // Read palettes
  70357. var palettes;
  70358. if (use_pal) {
  70359. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70360. }
  70361. // Read LRE
  70362. if (use_rle) {
  70363. pixel_data = new Uint8Array(pixel_total);
  70364. var c, count, i;
  70365. var localOffset = 0;
  70366. var pixels = new Uint8Array(pixel_size);
  70367. while (offset < pixel_total && localOffset < pixel_total) {
  70368. c = data[offset++];
  70369. count = (c & 0x7f) + 1;
  70370. // RLE pixels
  70371. if (c & 0x80) {
  70372. // Bind pixel tmp array
  70373. for (i = 0; i < pixel_size; ++i) {
  70374. pixels[i] = data[offset++];
  70375. }
  70376. // Copy pixel array
  70377. for (i = 0; i < count; ++i) {
  70378. pixel_data.set(pixels, localOffset + i * pixel_size);
  70379. }
  70380. localOffset += pixel_size * count;
  70381. }
  70382. else {
  70383. count *= pixel_size;
  70384. for (i = 0; i < count; ++i) {
  70385. pixel_data[localOffset + i] = data[offset++];
  70386. }
  70387. localOffset += count;
  70388. }
  70389. }
  70390. }
  70391. else {
  70392. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70393. }
  70394. // Load to texture
  70395. var x_start, y_start, x_step, y_step, y_end, x_end;
  70396. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70397. default:
  70398. case TGATools._ORIGIN_UL:
  70399. x_start = 0;
  70400. x_step = 1;
  70401. x_end = header.width;
  70402. y_start = 0;
  70403. y_step = 1;
  70404. y_end = header.height;
  70405. break;
  70406. case TGATools._ORIGIN_BL:
  70407. x_start = 0;
  70408. x_step = 1;
  70409. x_end = header.width;
  70410. y_start = header.height - 1;
  70411. y_step = -1;
  70412. y_end = -1;
  70413. break;
  70414. case TGATools._ORIGIN_UR:
  70415. x_start = header.width - 1;
  70416. x_step = -1;
  70417. x_end = -1;
  70418. y_start = 0;
  70419. y_step = 1;
  70420. y_end = header.height;
  70421. break;
  70422. case TGATools._ORIGIN_BR:
  70423. x_start = header.width - 1;
  70424. x_step = -1;
  70425. x_end = -1;
  70426. y_start = header.height - 1;
  70427. y_step = -1;
  70428. y_end = -1;
  70429. break;
  70430. }
  70431. // Load the specify method
  70432. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70433. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70434. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70435. };
  70436. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70437. var image = pixel_data, colormap = palettes;
  70438. var width = header.width, height = header.height;
  70439. var color, i = 0, x, y;
  70440. var imageData = new Uint8Array(width * height * 4);
  70441. for (y = y_start; y !== y_end; y += y_step) {
  70442. for (x = x_start; x !== x_end; x += x_step, i++) {
  70443. color = image[i];
  70444. imageData[(x + width * y) * 4 + 3] = 255;
  70445. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70446. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70447. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70448. }
  70449. }
  70450. return imageData;
  70451. };
  70452. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70453. var image = pixel_data;
  70454. var width = header.width, height = header.height;
  70455. var color, i = 0, x, y;
  70456. var imageData = new Uint8Array(width * height * 4);
  70457. for (y = y_start; y !== y_end; y += y_step) {
  70458. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70459. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70460. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70461. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70462. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70463. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70464. }
  70465. }
  70466. return imageData;
  70467. };
  70468. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70469. var image = pixel_data;
  70470. var width = header.width, height = header.height;
  70471. var i = 0, x, y;
  70472. var imageData = new Uint8Array(width * height * 4);
  70473. for (y = y_start; y !== y_end; y += y_step) {
  70474. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70475. imageData[(x + width * y) * 4 + 3] = 255;
  70476. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70477. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70478. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70479. }
  70480. }
  70481. return imageData;
  70482. };
  70483. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70484. var image = pixel_data;
  70485. var width = header.width, height = header.height;
  70486. var i = 0, x, y;
  70487. var imageData = new Uint8Array(width * height * 4);
  70488. for (y = y_start; y !== y_end; y += y_step) {
  70489. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70490. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70491. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70492. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70493. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70494. }
  70495. }
  70496. return imageData;
  70497. };
  70498. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70499. var image = pixel_data;
  70500. var width = header.width, height = header.height;
  70501. var color, i = 0, x, y;
  70502. var imageData = new Uint8Array(width * height * 4);
  70503. for (y = y_start; y !== y_end; y += y_step) {
  70504. for (x = x_start; x !== x_end; x += x_step, i++) {
  70505. color = image[i];
  70506. imageData[(x + width * y) * 4 + 0] = color;
  70507. imageData[(x + width * y) * 4 + 1] = color;
  70508. imageData[(x + width * y) * 4 + 2] = color;
  70509. imageData[(x + width * y) * 4 + 3] = 255;
  70510. }
  70511. }
  70512. return imageData;
  70513. };
  70514. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70515. var image = pixel_data;
  70516. var width = header.width, height = header.height;
  70517. var i = 0, x, y;
  70518. var imageData = new Uint8Array(width * height * 4);
  70519. for (y = y_start; y !== y_end; y += y_step) {
  70520. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70521. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70522. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70523. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70524. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70525. }
  70526. }
  70527. return imageData;
  70528. };
  70529. //private static _TYPE_NO_DATA = 0;
  70530. TGATools._TYPE_INDEXED = 1;
  70531. TGATools._TYPE_RGB = 2;
  70532. TGATools._TYPE_GREY = 3;
  70533. TGATools._TYPE_RLE_INDEXED = 9;
  70534. TGATools._TYPE_RLE_RGB = 10;
  70535. TGATools._TYPE_RLE_GREY = 11;
  70536. TGATools._ORIGIN_MASK = 0x30;
  70537. TGATools._ORIGIN_SHIFT = 0x04;
  70538. TGATools._ORIGIN_BL = 0x00;
  70539. TGATools._ORIGIN_BR = 0x01;
  70540. TGATools._ORIGIN_UL = 0x02;
  70541. TGATools._ORIGIN_UR = 0x03;
  70542. return TGATools;
  70543. }());
  70544. BABYLON.TGATools = TGATools;
  70545. })(BABYLON || (BABYLON = {}));
  70546. //# sourceMappingURL=babylon.tga.js.map
  70547. var BABYLON;
  70548. (function (BABYLON) {
  70549. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70550. // All values and structures referenced from:
  70551. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70552. var DDS_MAGIC = 0x20534444;
  70553. var
  70554. //DDSD_CAPS = 0x1,
  70555. //DDSD_HEIGHT = 0x2,
  70556. //DDSD_WIDTH = 0x4,
  70557. //DDSD_PITCH = 0x8,
  70558. //DDSD_PIXELFORMAT = 0x1000,
  70559. DDSD_MIPMAPCOUNT = 0x20000;
  70560. //DDSD_LINEARSIZE = 0x80000,
  70561. //DDSD_DEPTH = 0x800000;
  70562. // var DDSCAPS_COMPLEX = 0x8,
  70563. // DDSCAPS_MIPMAP = 0x400000,
  70564. // DDSCAPS_TEXTURE = 0x1000;
  70565. var DDSCAPS2_CUBEMAP = 0x200;
  70566. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70567. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70568. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70569. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70570. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70571. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70572. // DDSCAPS2_VOLUME = 0x200000;
  70573. var
  70574. //DDPF_ALPHAPIXELS = 0x1,
  70575. //DDPF_ALPHA = 0x2,
  70576. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70577. //DDPF_YUV = 0x200,
  70578. DDPF_LUMINANCE = 0x20000;
  70579. function FourCCToInt32(value) {
  70580. return value.charCodeAt(0) +
  70581. (value.charCodeAt(1) << 8) +
  70582. (value.charCodeAt(2) << 16) +
  70583. (value.charCodeAt(3) << 24);
  70584. }
  70585. function Int32ToFourCC(value) {
  70586. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70587. }
  70588. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70589. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70590. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70591. var FOURCC_DX10 = FourCCToInt32("DX10");
  70592. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70593. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70594. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70595. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70596. var headerLengthInt = 31; // The header length in 32 bit ints
  70597. // Offsets into the header array
  70598. var off_magic = 0;
  70599. var off_size = 1;
  70600. var off_flags = 2;
  70601. var off_height = 3;
  70602. var off_width = 4;
  70603. var off_mipmapCount = 7;
  70604. var off_pfFlags = 20;
  70605. var off_pfFourCC = 21;
  70606. var off_RGBbpp = 22;
  70607. // var off_RMask = 23;
  70608. // var off_GMask = 24;
  70609. // var off_BMask = 25;
  70610. // var off_AMask = 26;
  70611. // var off_caps1 = 27;
  70612. var off_caps2 = 28;
  70613. // var off_caps3 = 29;
  70614. // var off_caps4 = 30;
  70615. var off_dxgiFormat = 32;
  70616. ;
  70617. var DDSTools = /** @class */ (function () {
  70618. function DDSTools() {
  70619. }
  70620. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70621. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70622. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70623. var mipmapCount = 1;
  70624. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70625. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70626. }
  70627. var fourCC = header[off_pfFourCC];
  70628. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70629. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70630. switch (fourCC) {
  70631. case FOURCC_D3DFMT_R16G16B16A16F:
  70632. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70633. break;
  70634. case FOURCC_D3DFMT_R32G32B32A32F:
  70635. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70636. break;
  70637. case FOURCC_DX10:
  70638. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70639. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70640. break;
  70641. }
  70642. }
  70643. return {
  70644. width: header[off_width],
  70645. height: header[off_height],
  70646. mipmapCount: mipmapCount,
  70647. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70648. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70649. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70650. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70651. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70652. dxgiFormat: dxgiFormat,
  70653. textureType: textureType
  70654. };
  70655. };
  70656. DDSTools._ToHalfFloat = function (value) {
  70657. if (!DDSTools._FloatView) {
  70658. DDSTools._FloatView = new Float32Array(1);
  70659. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70660. }
  70661. DDSTools._FloatView[0] = value;
  70662. var x = DDSTools._Int32View[0];
  70663. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70664. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70665. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70666. /* If zero, or denormal, or exponent underflows too much for a denormal
  70667. * half, return signed zero. */
  70668. if (e < 103) {
  70669. return bits;
  70670. }
  70671. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70672. if (e > 142) {
  70673. bits |= 0x7c00;
  70674. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70675. * not Inf, so make sure we set one mantissa bit too. */
  70676. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70677. return bits;
  70678. }
  70679. /* If exponent underflows but not too much, return a denormal */
  70680. if (e < 113) {
  70681. m |= 0x0800;
  70682. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70683. * to 1, which is OK. */
  70684. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70685. return bits;
  70686. }
  70687. bits |= ((e - 112) << 10) | (m >> 1);
  70688. bits += m & 1;
  70689. return bits;
  70690. };
  70691. DDSTools._FromHalfFloat = function (value) {
  70692. var s = (value & 0x8000) >> 15;
  70693. var e = (value & 0x7C00) >> 10;
  70694. var f = value & 0x03FF;
  70695. if (e === 0) {
  70696. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70697. }
  70698. else if (e == 0x1F) {
  70699. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70700. }
  70701. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70702. };
  70703. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70704. var destArray = new Float32Array(dataLength);
  70705. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70706. var index = 0;
  70707. for (var y = 0; y < height; y++) {
  70708. for (var x = 0; x < width; x++) {
  70709. var srcPos = (x + y * width) * 4;
  70710. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70711. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70712. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70713. if (DDSTools.StoreLODInAlphaChannel) {
  70714. destArray[index + 3] = lod;
  70715. }
  70716. else {
  70717. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70718. }
  70719. index += 4;
  70720. }
  70721. }
  70722. return destArray;
  70723. };
  70724. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70725. if (DDSTools.StoreLODInAlphaChannel) {
  70726. var destArray = new Uint16Array(dataLength);
  70727. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70728. var index = 0;
  70729. for (var y = 0; y < height; y++) {
  70730. for (var x = 0; x < width; x++) {
  70731. var srcPos = (x + y * width) * 4;
  70732. destArray[index] = srcData[srcPos];
  70733. destArray[index + 1] = srcData[srcPos + 1];
  70734. destArray[index + 2] = srcData[srcPos + 2];
  70735. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70736. index += 4;
  70737. }
  70738. }
  70739. return destArray;
  70740. }
  70741. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70742. };
  70743. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70744. if (DDSTools.StoreLODInAlphaChannel) {
  70745. var destArray = new Float32Array(dataLength);
  70746. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70747. var index = 0;
  70748. for (var y = 0; y < height; y++) {
  70749. for (var x = 0; x < width; x++) {
  70750. var srcPos = (x + y * width) * 4;
  70751. destArray[index] = srcData[srcPos];
  70752. destArray[index + 1] = srcData[srcPos + 1];
  70753. destArray[index + 2] = srcData[srcPos + 2];
  70754. destArray[index + 3] = lod;
  70755. index += 4;
  70756. }
  70757. }
  70758. return destArray;
  70759. }
  70760. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70761. };
  70762. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70763. var destArray = new Uint8Array(dataLength);
  70764. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70765. var index = 0;
  70766. for (var y = 0; y < height; y++) {
  70767. for (var x = 0; x < width; x++) {
  70768. var srcPos = (x + y * width) * 4;
  70769. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70770. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70771. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70772. if (DDSTools.StoreLODInAlphaChannel) {
  70773. destArray[index + 3] = lod;
  70774. }
  70775. else {
  70776. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70777. }
  70778. index += 4;
  70779. }
  70780. }
  70781. return destArray;
  70782. };
  70783. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70784. var destArray = new Uint8Array(dataLength);
  70785. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70786. var index = 0;
  70787. for (var y = 0; y < height; y++) {
  70788. for (var x = 0; x < width; x++) {
  70789. var srcPos = (x + y * width) * 4;
  70790. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70791. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70792. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70793. if (DDSTools.StoreLODInAlphaChannel) {
  70794. destArray[index + 3] = lod;
  70795. }
  70796. else {
  70797. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70798. }
  70799. index += 4;
  70800. }
  70801. }
  70802. return destArray;
  70803. };
  70804. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70805. var byteArray = new Uint8Array(dataLength);
  70806. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70807. var index = 0;
  70808. for (var y = 0; y < height; y++) {
  70809. for (var x = 0; x < width; x++) {
  70810. var srcPos = (x + y * width) * 4;
  70811. byteArray[index] = srcData[srcPos + 2];
  70812. byteArray[index + 1] = srcData[srcPos + 1];
  70813. byteArray[index + 2] = srcData[srcPos];
  70814. byteArray[index + 3] = srcData[srcPos + 3];
  70815. index += 4;
  70816. }
  70817. }
  70818. return byteArray;
  70819. };
  70820. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70821. var byteArray = new Uint8Array(dataLength);
  70822. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70823. var index = 0;
  70824. for (var y = 0; y < height; y++) {
  70825. for (var x = 0; x < width; x++) {
  70826. var srcPos = (x + y * width) * 3;
  70827. byteArray[index] = srcData[srcPos + 2];
  70828. byteArray[index + 1] = srcData[srcPos + 1];
  70829. byteArray[index + 2] = srcData[srcPos];
  70830. index += 3;
  70831. }
  70832. }
  70833. return byteArray;
  70834. };
  70835. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70836. var byteArray = new Uint8Array(dataLength);
  70837. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70838. var index = 0;
  70839. for (var y = 0; y < height; y++) {
  70840. for (var x = 0; x < width; x++) {
  70841. var srcPos = (x + y * width);
  70842. byteArray[index] = srcData[srcPos];
  70843. index++;
  70844. }
  70845. }
  70846. return byteArray;
  70847. };
  70848. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70849. if (lodIndex === void 0) { lodIndex = -1; }
  70850. var ext = engine.getCaps().s3tc;
  70851. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70852. var fourCC, width, height, dataLength = 0, dataOffset;
  70853. var byteArray, mipmapCount, mip;
  70854. var internalFormat = 0;
  70855. var format = 0;
  70856. var blockBytes = 1;
  70857. if (header[off_magic] !== DDS_MAGIC) {
  70858. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70859. return;
  70860. }
  70861. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70862. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70863. return;
  70864. }
  70865. if (info.isCompressed && !ext) {
  70866. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70867. return;
  70868. }
  70869. var bpp = header[off_RGBbpp];
  70870. dataOffset = header[off_size] + 4;
  70871. var computeFormats = false;
  70872. if (info.isFourCC) {
  70873. fourCC = header[off_pfFourCC];
  70874. switch (fourCC) {
  70875. case FOURCC_DXT1:
  70876. blockBytes = 8;
  70877. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70878. break;
  70879. case FOURCC_DXT3:
  70880. blockBytes = 16;
  70881. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70882. break;
  70883. case FOURCC_DXT5:
  70884. blockBytes = 16;
  70885. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70886. break;
  70887. case FOURCC_D3DFMT_R16G16B16A16F:
  70888. computeFormats = true;
  70889. break;
  70890. case FOURCC_D3DFMT_R32G32B32A32F:
  70891. computeFormats = true;
  70892. break;
  70893. case FOURCC_DX10:
  70894. // There is an additionnal header so dataOffset need to be changed
  70895. dataOffset += 5 * 4; // 5 uints
  70896. var supported = false;
  70897. switch (info.dxgiFormat) {
  70898. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70899. computeFormats = true;
  70900. supported = true;
  70901. break;
  70902. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70903. info.isRGB = true;
  70904. info.isFourCC = false;
  70905. bpp = 32;
  70906. supported = true;
  70907. break;
  70908. }
  70909. if (supported) {
  70910. break;
  70911. }
  70912. default:
  70913. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70914. return;
  70915. }
  70916. }
  70917. if (computeFormats) {
  70918. format = engine._getWebGLTextureType(info.textureType);
  70919. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70920. }
  70921. mipmapCount = 1;
  70922. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70923. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70924. }
  70925. for (var face = 0; face < faces; face++) {
  70926. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70927. width = header[off_width];
  70928. height = header[off_height];
  70929. for (mip = 0; mip < mipmapCount; ++mip) {
  70930. if (lodIndex === -1 || lodIndex === mip) {
  70931. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70932. var i = (lodIndex === -1) ? mip : 0;
  70933. if (!info.isCompressed && info.isFourCC) {
  70934. dataLength = width * height * 4;
  70935. var floatArray = null;
  70936. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70937. if (bpp === 128) {
  70938. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70939. }
  70940. else if (bpp === 64) {
  70941. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70942. }
  70943. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70944. format = engine._getWebGLTextureType(info.textureType);
  70945. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70946. }
  70947. else {
  70948. if (bpp === 128) {
  70949. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70950. }
  70951. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70952. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70953. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70954. format = engine._getWebGLTextureType(info.textureType);
  70955. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70956. }
  70957. else {
  70958. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70959. }
  70960. }
  70961. if (floatArray) {
  70962. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70963. }
  70964. }
  70965. else if (info.isRGB) {
  70966. if (bpp === 24) {
  70967. dataLength = width * height * 3;
  70968. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70969. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70970. }
  70971. else {
  70972. dataLength = width * height * 4;
  70973. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70974. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70975. }
  70976. }
  70977. else if (info.isLuminance) {
  70978. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70979. var unpaddedRowSize = width;
  70980. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70981. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70982. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70983. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70984. }
  70985. else {
  70986. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70987. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70988. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70989. }
  70990. }
  70991. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70992. width *= 0.5;
  70993. height *= 0.5;
  70994. width = Math.max(1.0, width);
  70995. height = Math.max(1.0, height);
  70996. }
  70997. if (currentFace !== undefined) {
  70998. // Loading a single face
  70999. break;
  71000. }
  71001. }
  71002. };
  71003. DDSTools.StoreLODInAlphaChannel = false;
  71004. return DDSTools;
  71005. }());
  71006. BABYLON.DDSTools = DDSTools;
  71007. })(BABYLON || (BABYLON = {}));
  71008. //# sourceMappingURL=babylon.dds.js.map
  71009. var BABYLON;
  71010. (function (BABYLON) {
  71011. /**
  71012. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  71013. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  71014. */
  71015. var KhronosTextureContainer = /** @class */ (function () {
  71016. /**
  71017. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  71018. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  71019. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  71020. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  71021. */
  71022. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  71023. this.arrayBuffer = arrayBuffer;
  71024. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  71025. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  71026. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  71027. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  71028. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  71029. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  71030. BABYLON.Tools.Error("texture missing KTX identifier");
  71031. return;
  71032. }
  71033. // load the reset of the header in native 32 bit int
  71034. var header = new Int32Array(this.arrayBuffer, 12, 13);
  71035. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  71036. var oppositeEndianess = header[0] === 0x01020304;
  71037. // read all the header elements in order they exist in the file, without modification (sans endainness)
  71038. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  71039. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  71040. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  71041. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  71042. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  71043. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  71044. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  71045. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  71046. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  71047. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  71048. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  71049. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  71050. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  71051. if (this.glType !== 0) {
  71052. BABYLON.Tools.Error("only compressed formats currently supported");
  71053. return;
  71054. }
  71055. else {
  71056. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  71057. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  71058. }
  71059. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  71060. BABYLON.Tools.Error("only 2D textures currently supported");
  71061. return;
  71062. }
  71063. if (this.numberOfArrayElements !== 0) {
  71064. BABYLON.Tools.Error("texture arrays not currently supported");
  71065. return;
  71066. }
  71067. if (this.numberOfFaces !== facesExpected) {
  71068. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  71069. return;
  71070. }
  71071. // we now have a completely validated file, so could use existence of loadType as success
  71072. // would need to make this more elaborate & adjust checks above to support more than one load type
  71073. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  71074. }
  71075. // not as fast hardware based, but will probably never need to use
  71076. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  71077. return ((val & 0xFF) << 24)
  71078. | ((val & 0xFF00) << 8)
  71079. | ((val >> 8) & 0xFF00)
  71080. | ((val >> 24) & 0xFF);
  71081. };
  71082. /**
  71083. * It is assumed that the texture has already been created & is currently bound
  71084. */
  71085. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  71086. switch (this.loadType) {
  71087. case KhronosTextureContainer.COMPRESSED_2D:
  71088. this._upload2DCompressedLevels(gl, loadMipmaps);
  71089. break;
  71090. case KhronosTextureContainer.TEX_2D:
  71091. case KhronosTextureContainer.COMPRESSED_3D:
  71092. case KhronosTextureContainer.TEX_3D:
  71093. }
  71094. };
  71095. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  71096. // initialize width & height for level 1
  71097. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  71098. var width = this.pixelWidth;
  71099. var height = this.pixelHeight;
  71100. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  71101. for (var level = 0; level < mipmapCount; level++) {
  71102. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  71103. for (var face = 0; face < this.numberOfFaces; face++) {
  71104. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  71105. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  71106. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  71107. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  71108. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  71109. }
  71110. width = Math.max(1.0, width * 0.5);
  71111. height = Math.max(1.0, height * 0.5);
  71112. }
  71113. };
  71114. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  71115. // load types
  71116. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  71117. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  71118. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  71119. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  71120. return KhronosTextureContainer;
  71121. }());
  71122. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  71123. })(BABYLON || (BABYLON = {}));
  71124. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  71125. var BABYLON;
  71126. (function (BABYLON) {
  71127. var Debug = /** @class */ (function () {
  71128. function Debug() {
  71129. }
  71130. Debug.AxesViewer = /** @class */ (function () {
  71131. function AxesViewer(scene, scaleLines) {
  71132. if (scaleLines === void 0) { scaleLines = 1; }
  71133. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71134. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71135. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71136. this.scaleLines = 1;
  71137. this.scaleLines = scaleLines;
  71138. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  71139. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  71140. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  71141. this._xmesh.renderingGroupId = 2;
  71142. this._ymesh.renderingGroupId = 2;
  71143. this._zmesh.renderingGroupId = 2;
  71144. this._xmesh.material.checkReadyOnlyOnce = true;
  71145. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  71146. this._ymesh.material.checkReadyOnlyOnce = true;
  71147. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71148. this._zmesh.material.checkReadyOnlyOnce = true;
  71149. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71150. this.scene = scene;
  71151. }
  71152. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71153. var scaleLines = this.scaleLines;
  71154. if (this._xmesh) {
  71155. this._xmesh.position.copyFrom(position);
  71156. }
  71157. if (this._ymesh) {
  71158. this._ymesh.position.copyFrom(position);
  71159. }
  71160. if (this._zmesh) {
  71161. this._zmesh.position.copyFrom(position);
  71162. }
  71163. var point2 = this._xline[1];
  71164. point2.x = xaxis.x * scaleLines;
  71165. point2.y = xaxis.y * scaleLines;
  71166. point2.z = xaxis.z * scaleLines;
  71167. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71168. point2 = this._yline[1];
  71169. point2.x = yaxis.x * scaleLines;
  71170. point2.y = yaxis.y * scaleLines;
  71171. point2.z = yaxis.z * scaleLines;
  71172. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71173. point2 = this._zline[1];
  71174. point2.x = zaxis.x * scaleLines;
  71175. point2.y = zaxis.y * scaleLines;
  71176. point2.z = zaxis.z * scaleLines;
  71177. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71178. };
  71179. AxesViewer.prototype.dispose = function () {
  71180. if (this._xmesh) {
  71181. this._xmesh.dispose();
  71182. }
  71183. if (this._ymesh) {
  71184. this._ymesh.dispose();
  71185. }
  71186. if (this._zmesh) {
  71187. this._zmesh.dispose();
  71188. }
  71189. this._xmesh = null;
  71190. this._ymesh = null;
  71191. this._zmesh = null;
  71192. this.scene = null;
  71193. };
  71194. return AxesViewer;
  71195. }());
  71196. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71197. __extends(BoneAxesViewer, _super);
  71198. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71199. if (scaleLines === void 0) { scaleLines = 1; }
  71200. var _this = _super.call(this, scene, scaleLines) || this;
  71201. _this.pos = BABYLON.Vector3.Zero();
  71202. _this.xaxis = BABYLON.Vector3.Zero();
  71203. _this.yaxis = BABYLON.Vector3.Zero();
  71204. _this.zaxis = BABYLON.Vector3.Zero();
  71205. _this.mesh = mesh;
  71206. _this.bone = bone;
  71207. return _this;
  71208. }
  71209. BoneAxesViewer.prototype.update = function () {
  71210. if (!this.mesh || !this.bone) {
  71211. return;
  71212. }
  71213. var bone = this.bone;
  71214. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71215. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71216. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71217. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71218. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71219. };
  71220. BoneAxesViewer.prototype.dispose = function () {
  71221. if (this.mesh) {
  71222. this.mesh = null;
  71223. this.bone = null;
  71224. _super.prototype.dispose.call(this);
  71225. }
  71226. };
  71227. return BoneAxesViewer;
  71228. }(Debug.AxesViewer));
  71229. Debug.PhysicsViewer = /** @class */ (function () {
  71230. function PhysicsViewer(scene) {
  71231. this._impostors = [];
  71232. this._meshes = [];
  71233. this._numMeshes = 0;
  71234. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71235. var physicEngine = this._scene.getPhysicsEngine();
  71236. if (physicEngine) {
  71237. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71238. }
  71239. }
  71240. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71241. var plugin = this._physicsEnginePlugin;
  71242. for (var i = 0; i < this._numMeshes; i++) {
  71243. var impostor = this._impostors[i];
  71244. if (!impostor) {
  71245. continue;
  71246. }
  71247. if (impostor.isDisposed) {
  71248. this.hideImpostor(this._impostors[i--]);
  71249. }
  71250. else {
  71251. var mesh = this._meshes[i];
  71252. if (mesh && plugin) {
  71253. plugin.syncMeshWithImpostor(mesh, impostor);
  71254. }
  71255. }
  71256. }
  71257. };
  71258. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71259. if (!this._scene) {
  71260. return;
  71261. }
  71262. for (var i = 0; i < this._numMeshes; i++) {
  71263. if (this._impostors[i] == impostor) {
  71264. return;
  71265. }
  71266. }
  71267. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71268. if (debugMesh) {
  71269. this._impostors[this._numMeshes] = impostor;
  71270. this._meshes[this._numMeshes] = debugMesh;
  71271. if (this._numMeshes === 0) {
  71272. this._renderFunction = this._updateDebugMeshes.bind(this);
  71273. this._scene.registerBeforeRender(this._renderFunction);
  71274. }
  71275. this._numMeshes++;
  71276. }
  71277. };
  71278. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71279. if (!impostor || !this._scene) {
  71280. return;
  71281. }
  71282. var removed = false;
  71283. for (var i = 0; i < this._numMeshes; i++) {
  71284. if (this._impostors[i] == impostor) {
  71285. var mesh = this._meshes[i];
  71286. if (!mesh) {
  71287. continue;
  71288. }
  71289. this._scene.removeMesh(mesh);
  71290. mesh.dispose();
  71291. this._numMeshes--;
  71292. if (this._numMeshes > 0) {
  71293. this._meshes[i] = this._meshes[this._numMeshes];
  71294. this._impostors[i] = this._impostors[this._numMeshes];
  71295. this._meshes[this._numMeshes] = null;
  71296. this._impostors[this._numMeshes] = null;
  71297. }
  71298. else {
  71299. this._meshes[0] = null;
  71300. this._impostors[0] = null;
  71301. }
  71302. removed = true;
  71303. break;
  71304. }
  71305. }
  71306. if (removed && this._numMeshes === 0) {
  71307. this._scene.unregisterBeforeRender(this._renderFunction);
  71308. }
  71309. };
  71310. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71311. if (!this._debugMaterial) {
  71312. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71313. this._debugMaterial.wireframe = true;
  71314. }
  71315. return this._debugMaterial;
  71316. };
  71317. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71318. if (!this._debugBoxMesh) {
  71319. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71320. this._debugBoxMesh.renderingGroupId = 1;
  71321. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71322. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71323. scene.removeMesh(this._debugBoxMesh);
  71324. }
  71325. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71326. };
  71327. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71328. if (!this._debugSphereMesh) {
  71329. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71330. this._debugSphereMesh.renderingGroupId = 1;
  71331. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71332. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71333. scene.removeMesh(this._debugSphereMesh);
  71334. }
  71335. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71336. };
  71337. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71338. var mesh = null;
  71339. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71340. mesh = this._getDebugBoxMesh(scene);
  71341. impostor.getBoxSizeToRef(mesh.scaling);
  71342. }
  71343. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71344. mesh = this._getDebugSphereMesh(scene);
  71345. var radius = impostor.getRadius();
  71346. mesh.scaling.x = radius * 2;
  71347. mesh.scaling.y = radius * 2;
  71348. mesh.scaling.z = radius * 2;
  71349. }
  71350. return mesh;
  71351. };
  71352. PhysicsViewer.prototype.dispose = function () {
  71353. for (var i = 0; i < this._numMeshes; i++) {
  71354. this.hideImpostor(this._impostors[i]);
  71355. }
  71356. if (this._debugBoxMesh) {
  71357. this._debugBoxMesh.dispose();
  71358. }
  71359. if (this._debugSphereMesh) {
  71360. this._debugSphereMesh.dispose();
  71361. }
  71362. if (this._debugMaterial) {
  71363. this._debugMaterial.dispose();
  71364. }
  71365. this._impostors.length = 0;
  71366. this._scene = null;
  71367. this._physicsEnginePlugin = null;
  71368. };
  71369. return PhysicsViewer;
  71370. }());
  71371. Debug.SkeletonViewer = /** @class */ (function () {
  71372. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71373. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71374. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71375. this.skeleton = skeleton;
  71376. this.mesh = mesh;
  71377. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71378. this.renderingGroupId = renderingGroupId;
  71379. this.color = BABYLON.Color3.White();
  71380. this._debugLines = new Array();
  71381. this._isEnabled = false;
  71382. this._scene = scene;
  71383. this.update();
  71384. this._renderFunction = this.update.bind(this);
  71385. }
  71386. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71387. get: function () {
  71388. return this._isEnabled;
  71389. },
  71390. set: function (value) {
  71391. if (this._isEnabled === value) {
  71392. return;
  71393. }
  71394. this._isEnabled = value;
  71395. if (value) {
  71396. this._scene.registerBeforeRender(this._renderFunction);
  71397. }
  71398. else {
  71399. this._scene.unregisterBeforeRender(this._renderFunction);
  71400. }
  71401. },
  71402. enumerable: true,
  71403. configurable: true
  71404. });
  71405. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71406. if (x === void 0) { x = 0; }
  71407. if (y === void 0) { y = 0; }
  71408. if (z === void 0) { z = 0; }
  71409. var tmat = BABYLON.Tmp.Matrix[0];
  71410. var parentBone = bone.getParent();
  71411. tmat.copyFrom(bone.getLocalMatrix());
  71412. if (x !== 0 || y !== 0 || z !== 0) {
  71413. var tmat2 = BABYLON.Tmp.Matrix[1];
  71414. BABYLON.Matrix.IdentityToRef(tmat2);
  71415. tmat2.m[12] = x;
  71416. tmat2.m[13] = y;
  71417. tmat2.m[14] = z;
  71418. tmat2.multiplyToRef(tmat, tmat);
  71419. }
  71420. if (parentBone) {
  71421. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71422. }
  71423. tmat.multiplyToRef(meshMat, tmat);
  71424. position.x = tmat.m[12];
  71425. position.y = tmat.m[13];
  71426. position.z = tmat.m[14];
  71427. };
  71428. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71429. var len = bones.length;
  71430. var meshPos = this.mesh.position;
  71431. for (var i = 0; i < len; i++) {
  71432. var bone = bones[i];
  71433. var points = this._debugLines[i];
  71434. if (!points) {
  71435. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71436. this._debugLines[i] = points;
  71437. }
  71438. this._getBonePosition(points[0], bone, meshMat);
  71439. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71440. points[0].subtractInPlace(meshPos);
  71441. points[1].subtractInPlace(meshPos);
  71442. }
  71443. };
  71444. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71445. var len = bones.length;
  71446. var boneNum = 0;
  71447. var meshPos = this.mesh.position;
  71448. for (var i = len - 1; i >= 0; i--) {
  71449. var childBone = bones[i];
  71450. var parentBone = childBone.getParent();
  71451. if (!parentBone) {
  71452. continue;
  71453. }
  71454. var points = this._debugLines[boneNum];
  71455. if (!points) {
  71456. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71457. this._debugLines[boneNum] = points;
  71458. }
  71459. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71460. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71461. points[0].subtractInPlace(meshPos);
  71462. points[1].subtractInPlace(meshPos);
  71463. boneNum++;
  71464. }
  71465. };
  71466. SkeletonViewer.prototype.update = function () {
  71467. if (this.autoUpdateBonesMatrices) {
  71468. this.skeleton.computeAbsoluteTransforms();
  71469. }
  71470. if (this.skeleton.bones[0].length === undefined) {
  71471. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71472. }
  71473. else {
  71474. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71475. }
  71476. if (!this._debugMesh) {
  71477. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71478. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71479. }
  71480. else {
  71481. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71482. }
  71483. this._debugMesh.position.copyFrom(this.mesh.position);
  71484. this._debugMesh.color = this.color;
  71485. };
  71486. SkeletonViewer.prototype.dispose = function () {
  71487. if (this._debugMesh) {
  71488. this.isEnabled = false;
  71489. this._debugMesh.dispose();
  71490. this._debugMesh = null;
  71491. }
  71492. };
  71493. return SkeletonViewer;
  71494. }());
  71495. return Debug;
  71496. }());
  71497. BABYLON.Debug = Debug;
  71498. })(BABYLON || (BABYLON = {}));
  71499. //# sourceMappingURL=babylon.debugModules.js.map
  71500. var BABYLON;
  71501. (function (BABYLON) {
  71502. var RayHelper = /** @class */ (function () {
  71503. function RayHelper(ray) {
  71504. this.ray = ray;
  71505. }
  71506. RayHelper.CreateAndShow = function (ray, scene, color) {
  71507. var helper = new RayHelper(ray);
  71508. helper.show(scene, color);
  71509. return helper;
  71510. };
  71511. RayHelper.prototype.show = function (scene, color) {
  71512. if (!this._renderFunction && this.ray) {
  71513. var ray = this.ray;
  71514. this._renderFunction = this._render.bind(this);
  71515. this._scene = scene;
  71516. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71517. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71518. if (this._renderFunction) {
  71519. this._scene.registerBeforeRender(this._renderFunction);
  71520. }
  71521. }
  71522. if (color && this._renderLine) {
  71523. this._renderLine.color.copyFrom(color);
  71524. }
  71525. };
  71526. RayHelper.prototype.hide = function () {
  71527. if (this._renderFunction && this._scene) {
  71528. this._scene.unregisterBeforeRender(this._renderFunction);
  71529. this._scene = null;
  71530. this._renderFunction = null;
  71531. if (this._renderLine) {
  71532. this._renderLine.dispose();
  71533. this._renderLine = null;
  71534. }
  71535. this._renderPoints = [];
  71536. }
  71537. };
  71538. RayHelper.prototype._render = function () {
  71539. var ray = this.ray;
  71540. if (!ray) {
  71541. return;
  71542. }
  71543. var point = this._renderPoints[1];
  71544. var len = Math.min(ray.length, 1000000);
  71545. point.copyFrom(ray.direction);
  71546. point.scaleInPlace(len);
  71547. point.addInPlace(ray.origin);
  71548. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71549. };
  71550. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71551. this._attachedToMesh = mesh;
  71552. var ray = this.ray;
  71553. if (!ray) {
  71554. return;
  71555. }
  71556. if (!ray.direction) {
  71557. ray.direction = BABYLON.Vector3.Zero();
  71558. }
  71559. if (!ray.origin) {
  71560. ray.origin = BABYLON.Vector3.Zero();
  71561. }
  71562. if (length) {
  71563. ray.length = length;
  71564. }
  71565. if (!meshSpaceOrigin) {
  71566. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71567. }
  71568. if (!meshSpaceDirection) {
  71569. // -1 so that this will work with Mesh.lookAt
  71570. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71571. }
  71572. if (!this._meshSpaceDirection) {
  71573. this._meshSpaceDirection = meshSpaceDirection.clone();
  71574. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71575. }
  71576. else {
  71577. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71578. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71579. }
  71580. if (!this._updateToMeshFunction) {
  71581. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71582. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71583. }
  71584. this._updateToMesh();
  71585. };
  71586. RayHelper.prototype.detachFromMesh = function () {
  71587. if (this._attachedToMesh) {
  71588. if (this._updateToMeshFunction) {
  71589. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71590. }
  71591. this._attachedToMesh = null;
  71592. this._updateToMeshFunction = null;
  71593. }
  71594. };
  71595. RayHelper.prototype._updateToMesh = function () {
  71596. var ray = this.ray;
  71597. if (!this._attachedToMesh || !ray) {
  71598. return;
  71599. }
  71600. if (this._attachedToMesh._isDisposed) {
  71601. this.detachFromMesh();
  71602. return;
  71603. }
  71604. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71605. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71606. };
  71607. RayHelper.prototype.dispose = function () {
  71608. this.hide();
  71609. this.detachFromMesh();
  71610. this.ray = null;
  71611. };
  71612. return RayHelper;
  71613. }());
  71614. BABYLON.RayHelper = RayHelper;
  71615. })(BABYLON || (BABYLON = {}));
  71616. //# sourceMappingURL=babylon.rayHelper.js.map
  71617. var BABYLON;
  71618. (function (BABYLON) {
  71619. // load the inspector using require, if not present in the global namespace.
  71620. var DebugLayer = /** @class */ (function () {
  71621. function DebugLayer(scene) {
  71622. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71623. this._scene = scene;
  71624. // load inspector using require, if it doesn't exist on the global namespace.
  71625. }
  71626. /** Creates the inspector window. */
  71627. DebugLayer.prototype._createInspector = function (config) {
  71628. if (config === void 0) { config = {}; }
  71629. var popup = config.popup || false;
  71630. var initialTab = config.initialTab || 0;
  71631. var parentElement = config.parentElement || null;
  71632. if (!this._inspector) {
  71633. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71634. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71635. } // else nothing to do,; instance is already existing
  71636. };
  71637. DebugLayer.prototype.isVisible = function () {
  71638. if (!this._inspector) {
  71639. return false;
  71640. }
  71641. return true;
  71642. };
  71643. DebugLayer.prototype.hide = function () {
  71644. if (this._inspector) {
  71645. try {
  71646. this._inspector.dispose();
  71647. }
  71648. catch (e) {
  71649. // If the inspector has been removed directly from the inspector tool
  71650. }
  71651. this._inspector = null;
  71652. }
  71653. };
  71654. DebugLayer.prototype.show = function (config) {
  71655. if (config === void 0) { config = {}; }
  71656. if (typeof this.BJSINSPECTOR == 'undefined') {
  71657. // Load inspector and add it to the DOM
  71658. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71659. }
  71660. else {
  71661. // Otherwise creates the inspector
  71662. this._createInspector(config);
  71663. }
  71664. };
  71665. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71666. return DebugLayer;
  71667. }());
  71668. BABYLON.DebugLayer = DebugLayer;
  71669. })(BABYLON || (BABYLON = {}));
  71670. //# sourceMappingURL=babylon.debugLayer.js.map
  71671. var BABYLON;
  71672. (function (BABYLON) {
  71673. var BoundingBoxRenderer = /** @class */ (function () {
  71674. function BoundingBoxRenderer(scene) {
  71675. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71676. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71677. this.showBackLines = true;
  71678. this.renderList = new BABYLON.SmartArray(32);
  71679. this._vertexBuffers = {};
  71680. this._scene = scene;
  71681. }
  71682. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71683. if (this._colorShader) {
  71684. return;
  71685. }
  71686. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71687. attributes: [BABYLON.VertexBuffer.PositionKind],
  71688. uniforms: ["world", "viewProjection", "color"]
  71689. });
  71690. var engine = this._scene.getEngine();
  71691. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71692. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71693. this._createIndexBuffer();
  71694. };
  71695. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71696. var engine = this._scene.getEngine();
  71697. 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]);
  71698. };
  71699. BoundingBoxRenderer.prototype._rebuild = function () {
  71700. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71701. if (vb) {
  71702. vb._rebuild();
  71703. }
  71704. this._createIndexBuffer();
  71705. };
  71706. BoundingBoxRenderer.prototype.reset = function () {
  71707. this.renderList.reset();
  71708. };
  71709. BoundingBoxRenderer.prototype.render = function () {
  71710. if (this.renderList.length === 0) {
  71711. return;
  71712. }
  71713. this._prepareRessources();
  71714. if (!this._colorShader.isReady()) {
  71715. return;
  71716. }
  71717. var engine = this._scene.getEngine();
  71718. engine.setDepthWrite(false);
  71719. this._colorShader._preBind();
  71720. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71721. var boundingBox = this.renderList.data[boundingBoxIndex];
  71722. var min = boundingBox.minimum;
  71723. var max = boundingBox.maximum;
  71724. var diff = max.subtract(min);
  71725. var median = min.add(diff.scale(0.5));
  71726. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71727. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71728. .multiply(boundingBox.getWorldMatrix());
  71729. // VBOs
  71730. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71731. if (this.showBackLines) {
  71732. // Back
  71733. engine.setDepthFunctionToGreaterOrEqual();
  71734. this._scene.resetCachedMaterial();
  71735. this._colorShader.setColor4("color", this.backColor.toColor4());
  71736. this._colorShader.bind(worldMatrix);
  71737. // Draw order
  71738. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71739. }
  71740. // Front
  71741. engine.setDepthFunctionToLess();
  71742. this._scene.resetCachedMaterial();
  71743. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71744. this._colorShader.bind(worldMatrix);
  71745. // Draw order
  71746. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71747. }
  71748. this._colorShader.unbind();
  71749. engine.setDepthFunctionToLessOrEqual();
  71750. engine.setDepthWrite(true);
  71751. };
  71752. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71753. this._prepareRessources();
  71754. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71755. return;
  71756. }
  71757. var engine = this._scene.getEngine();
  71758. engine.setDepthWrite(false);
  71759. engine.setColorWrite(false);
  71760. this._colorShader._preBind();
  71761. var boundingBox = mesh._boundingInfo.boundingBox;
  71762. var min = boundingBox.minimum;
  71763. var max = boundingBox.maximum;
  71764. var diff = max.subtract(min);
  71765. var median = min.add(diff.scale(0.5));
  71766. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71767. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71768. .multiply(boundingBox.getWorldMatrix());
  71769. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71770. engine.setDepthFunctionToLess();
  71771. this._scene.resetCachedMaterial();
  71772. this._colorShader.bind(worldMatrix);
  71773. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71774. this._colorShader.unbind();
  71775. engine.setDepthFunctionToLessOrEqual();
  71776. engine.setDepthWrite(true);
  71777. engine.setColorWrite(true);
  71778. };
  71779. BoundingBoxRenderer.prototype.dispose = function () {
  71780. if (!this._colorShader) {
  71781. return;
  71782. }
  71783. this.renderList.dispose();
  71784. this._colorShader.dispose();
  71785. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71786. if (buffer) {
  71787. buffer.dispose();
  71788. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71789. }
  71790. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71791. };
  71792. return BoundingBoxRenderer;
  71793. }());
  71794. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71795. })(BABYLON || (BABYLON = {}));
  71796. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71797. var BABYLON;
  71798. (function (BABYLON) {
  71799. var MorphTarget = /** @class */ (function () {
  71800. function MorphTarget(name, influence) {
  71801. if (influence === void 0) { influence = 0; }
  71802. this.name = name;
  71803. this.animations = new Array();
  71804. this._positions = null;
  71805. this._normals = null;
  71806. this._tangents = null;
  71807. this.onInfluenceChanged = new BABYLON.Observable();
  71808. this.influence = influence;
  71809. }
  71810. Object.defineProperty(MorphTarget.prototype, "influence", {
  71811. get: function () {
  71812. return this._influence;
  71813. },
  71814. set: function (influence) {
  71815. if (this._influence === influence) {
  71816. return;
  71817. }
  71818. var previous = this._influence;
  71819. this._influence = influence;
  71820. if (this.onInfluenceChanged.hasObservers) {
  71821. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71822. }
  71823. },
  71824. enumerable: true,
  71825. configurable: true
  71826. });
  71827. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71828. get: function () {
  71829. return !!this._positions;
  71830. },
  71831. enumerable: true,
  71832. configurable: true
  71833. });
  71834. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71835. get: function () {
  71836. return !!this._normals;
  71837. },
  71838. enumerable: true,
  71839. configurable: true
  71840. });
  71841. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71842. get: function () {
  71843. return !!this._tangents;
  71844. },
  71845. enumerable: true,
  71846. configurable: true
  71847. });
  71848. MorphTarget.prototype.setPositions = function (data) {
  71849. this._positions = data;
  71850. };
  71851. MorphTarget.prototype.getPositions = function () {
  71852. return this._positions;
  71853. };
  71854. MorphTarget.prototype.setNormals = function (data) {
  71855. this._normals = data;
  71856. };
  71857. MorphTarget.prototype.getNormals = function () {
  71858. return this._normals;
  71859. };
  71860. MorphTarget.prototype.setTangents = function (data) {
  71861. this._tangents = data;
  71862. };
  71863. MorphTarget.prototype.getTangents = function () {
  71864. return this._tangents;
  71865. };
  71866. /**
  71867. * Serializes the current target into a Serialization object.
  71868. * Returns the serialized object.
  71869. */
  71870. MorphTarget.prototype.serialize = function () {
  71871. var serializationObject = {};
  71872. serializationObject.name = this.name;
  71873. serializationObject.influence = this.influence;
  71874. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71875. if (this.hasNormals) {
  71876. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71877. }
  71878. if (this.hasTangents) {
  71879. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71880. }
  71881. // Animations
  71882. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71883. return serializationObject;
  71884. };
  71885. // Statics
  71886. MorphTarget.Parse = function (serializationObject) {
  71887. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71888. result.setPositions(serializationObject.positions);
  71889. if (serializationObject.normals) {
  71890. result.setNormals(serializationObject.normals);
  71891. }
  71892. if (serializationObject.tangents) {
  71893. result.setTangents(serializationObject.tangents);
  71894. }
  71895. // Animations
  71896. if (serializationObject.animations) {
  71897. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71898. var parsedAnimation = serializationObject.animations[animationIndex];
  71899. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71900. }
  71901. }
  71902. return result;
  71903. };
  71904. MorphTarget.FromMesh = function (mesh, name, influence) {
  71905. if (!name) {
  71906. name = mesh.name;
  71907. }
  71908. var result = new MorphTarget(name, influence);
  71909. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71910. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71911. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71912. }
  71913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71914. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71915. }
  71916. return result;
  71917. };
  71918. return MorphTarget;
  71919. }());
  71920. BABYLON.MorphTarget = MorphTarget;
  71921. })(BABYLON || (BABYLON = {}));
  71922. //# sourceMappingURL=babylon.morphTarget.js.map
  71923. var BABYLON;
  71924. (function (BABYLON) {
  71925. var MorphTargetManager = /** @class */ (function () {
  71926. function MorphTargetManager(scene) {
  71927. if (scene === void 0) { scene = null; }
  71928. this._targets = new Array();
  71929. this._targetObservable = new Array();
  71930. this._activeTargets = new BABYLON.SmartArray(16);
  71931. this._supportsNormals = false;
  71932. this._supportsTangents = false;
  71933. this._vertexCount = 0;
  71934. this._uniqueId = 0;
  71935. this._tempInfluences = new Array();
  71936. if (!scene) {
  71937. scene = BABYLON.Engine.LastCreatedScene;
  71938. }
  71939. this._scene = scene;
  71940. if (this._scene) {
  71941. this._scene.morphTargetManagers.push(this);
  71942. this._uniqueId = this._scene.getUniqueId();
  71943. }
  71944. }
  71945. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71946. get: function () {
  71947. return this._uniqueId;
  71948. },
  71949. enumerable: true,
  71950. configurable: true
  71951. });
  71952. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71953. get: function () {
  71954. return this._vertexCount;
  71955. },
  71956. enumerable: true,
  71957. configurable: true
  71958. });
  71959. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71960. get: function () {
  71961. return this._supportsNormals;
  71962. },
  71963. enumerable: true,
  71964. configurable: true
  71965. });
  71966. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71967. get: function () {
  71968. return this._supportsTangents;
  71969. },
  71970. enumerable: true,
  71971. configurable: true
  71972. });
  71973. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71974. get: function () {
  71975. return this._targets.length;
  71976. },
  71977. enumerable: true,
  71978. configurable: true
  71979. });
  71980. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71981. get: function () {
  71982. return this._activeTargets.length;
  71983. },
  71984. enumerable: true,
  71985. configurable: true
  71986. });
  71987. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71988. get: function () {
  71989. return this._influences;
  71990. },
  71991. enumerable: true,
  71992. configurable: true
  71993. });
  71994. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71995. return this._activeTargets.data[index];
  71996. };
  71997. MorphTargetManager.prototype.getTarget = function (index) {
  71998. return this._targets[index];
  71999. };
  72000. MorphTargetManager.prototype.addTarget = function (target) {
  72001. var _this = this;
  72002. this._targets.push(target);
  72003. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  72004. _this._syncActiveTargets(needUpdate);
  72005. }));
  72006. this._syncActiveTargets(true);
  72007. };
  72008. MorphTargetManager.prototype.removeTarget = function (target) {
  72009. var index = this._targets.indexOf(target);
  72010. if (index >= 0) {
  72011. this._targets.splice(index, 1);
  72012. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  72013. this._syncActiveTargets(true);
  72014. }
  72015. };
  72016. /**
  72017. * Serializes the current manager into a Serialization object.
  72018. * Returns the serialized object.
  72019. */
  72020. MorphTargetManager.prototype.serialize = function () {
  72021. var serializationObject = {};
  72022. serializationObject.id = this.uniqueId;
  72023. serializationObject.targets = [];
  72024. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  72025. var target = _a[_i];
  72026. serializationObject.targets.push(target.serialize());
  72027. }
  72028. return serializationObject;
  72029. };
  72030. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  72031. var influenceCount = 0;
  72032. this._activeTargets.reset();
  72033. this._supportsNormals = true;
  72034. this._supportsTangents = true;
  72035. this._vertexCount = 0;
  72036. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  72037. var target = _a[_i];
  72038. this._activeTargets.push(target);
  72039. this._tempInfluences[influenceCount++] = target.influence;
  72040. var positions = target.getPositions();
  72041. if (positions) {
  72042. this._supportsNormals = this._supportsNormals && target.hasNormals;
  72043. this._supportsTangents = this._supportsTangents && target.hasTangents;
  72044. var vertexCount = positions.length / 3;
  72045. if (this._vertexCount === 0) {
  72046. this._vertexCount = vertexCount;
  72047. }
  72048. else if (this._vertexCount !== vertexCount) {
  72049. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  72050. return;
  72051. }
  72052. }
  72053. }
  72054. if (!this._influences || this._influences.length !== influenceCount) {
  72055. this._influences = new Float32Array(influenceCount);
  72056. }
  72057. for (var index = 0; index < influenceCount; index++) {
  72058. this._influences[index] = this._tempInfluences[index];
  72059. }
  72060. if (needUpdate && this._scene) {
  72061. // Flag meshes as dirty to resync with the active targets
  72062. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  72063. var mesh = _c[_b];
  72064. if (mesh.morphTargetManager === this) {
  72065. mesh._syncGeometryWithMorphTargetManager();
  72066. }
  72067. }
  72068. }
  72069. };
  72070. // Statics
  72071. MorphTargetManager.Parse = function (serializationObject, scene) {
  72072. var result = new MorphTargetManager(scene);
  72073. result._uniqueId = serializationObject.id;
  72074. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  72075. var targetData = _a[_i];
  72076. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  72077. }
  72078. return result;
  72079. };
  72080. return MorphTargetManager;
  72081. }());
  72082. BABYLON.MorphTargetManager = MorphTargetManager;
  72083. })(BABYLON || (BABYLON = {}));
  72084. //# sourceMappingURL=babylon.morphTargetManager.js.map
  72085. var BABYLON;
  72086. (function (BABYLON) {
  72087. var Octree = /** @class */ (function () {
  72088. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  72089. if (maxDepth === void 0) { maxDepth = 2; }
  72090. this.maxDepth = maxDepth;
  72091. this.dynamicContent = new Array();
  72092. this._maxBlockCapacity = maxBlockCapacity || 64;
  72093. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  72094. this._creationFunc = creationFunc;
  72095. }
  72096. // Methods
  72097. Octree.prototype.update = function (worldMin, worldMax, entries) {
  72098. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  72099. };
  72100. Octree.prototype.addMesh = function (entry) {
  72101. for (var index = 0; index < this.blocks.length; index++) {
  72102. var block = this.blocks[index];
  72103. block.addEntry(entry);
  72104. }
  72105. };
  72106. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  72107. this._selectionContent.reset();
  72108. for (var index = 0; index < this.blocks.length; index++) {
  72109. var block = this.blocks[index];
  72110. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  72111. }
  72112. if (allowDuplicate) {
  72113. this._selectionContent.concat(this.dynamicContent);
  72114. }
  72115. else {
  72116. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72117. }
  72118. return this._selectionContent;
  72119. };
  72120. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  72121. this._selectionContent.reset();
  72122. for (var index = 0; index < this.blocks.length; index++) {
  72123. var block = this.blocks[index];
  72124. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  72125. }
  72126. if (allowDuplicate) {
  72127. this._selectionContent.concat(this.dynamicContent);
  72128. }
  72129. else {
  72130. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72131. }
  72132. return this._selectionContent;
  72133. };
  72134. Octree.prototype.intersectsRay = function (ray) {
  72135. this._selectionContent.reset();
  72136. for (var index = 0; index < this.blocks.length; index++) {
  72137. var block = this.blocks[index];
  72138. block.intersectsRay(ray, this._selectionContent);
  72139. }
  72140. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72141. return this._selectionContent;
  72142. };
  72143. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  72144. target.blocks = new Array();
  72145. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  72146. // Segmenting space
  72147. for (var x = 0; x < 2; x++) {
  72148. for (var y = 0; y < 2; y++) {
  72149. for (var z = 0; z < 2; z++) {
  72150. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72151. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72152. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72153. block.addEntries(entries);
  72154. target.blocks.push(block);
  72155. }
  72156. }
  72157. }
  72158. };
  72159. Octree.CreationFuncForMeshes = function (entry, block) {
  72160. var boundingInfo = entry.getBoundingInfo();
  72161. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72162. block.entries.push(entry);
  72163. }
  72164. };
  72165. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72166. var boundingInfo = entry.getBoundingInfo();
  72167. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72168. block.entries.push(entry);
  72169. }
  72170. };
  72171. return Octree;
  72172. }());
  72173. BABYLON.Octree = Octree;
  72174. })(BABYLON || (BABYLON = {}));
  72175. //# sourceMappingURL=babylon.octree.js.map
  72176. var BABYLON;
  72177. (function (BABYLON) {
  72178. var OctreeBlock = /** @class */ (function () {
  72179. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72180. this.entries = new Array();
  72181. this._boundingVectors = new Array();
  72182. this._capacity = capacity;
  72183. this._depth = depth;
  72184. this._maxDepth = maxDepth;
  72185. this._creationFunc = creationFunc;
  72186. this._minPoint = minPoint;
  72187. this._maxPoint = maxPoint;
  72188. this._boundingVectors.push(minPoint.clone());
  72189. this._boundingVectors.push(maxPoint.clone());
  72190. this._boundingVectors.push(minPoint.clone());
  72191. this._boundingVectors[2].x = maxPoint.x;
  72192. this._boundingVectors.push(minPoint.clone());
  72193. this._boundingVectors[3].y = maxPoint.y;
  72194. this._boundingVectors.push(minPoint.clone());
  72195. this._boundingVectors[4].z = maxPoint.z;
  72196. this._boundingVectors.push(maxPoint.clone());
  72197. this._boundingVectors[5].z = minPoint.z;
  72198. this._boundingVectors.push(maxPoint.clone());
  72199. this._boundingVectors[6].x = minPoint.x;
  72200. this._boundingVectors.push(maxPoint.clone());
  72201. this._boundingVectors[7].y = minPoint.y;
  72202. }
  72203. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72204. // Property
  72205. get: function () {
  72206. return this._capacity;
  72207. },
  72208. enumerable: true,
  72209. configurable: true
  72210. });
  72211. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72212. get: function () {
  72213. return this._minPoint;
  72214. },
  72215. enumerable: true,
  72216. configurable: true
  72217. });
  72218. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72219. get: function () {
  72220. return this._maxPoint;
  72221. },
  72222. enumerable: true,
  72223. configurable: true
  72224. });
  72225. // Methods
  72226. OctreeBlock.prototype.addEntry = function (entry) {
  72227. if (this.blocks) {
  72228. for (var index = 0; index < this.blocks.length; index++) {
  72229. var block = this.blocks[index];
  72230. block.addEntry(entry);
  72231. }
  72232. return;
  72233. }
  72234. this._creationFunc(entry, this);
  72235. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72236. this.createInnerBlocks();
  72237. }
  72238. };
  72239. OctreeBlock.prototype.addEntries = function (entries) {
  72240. for (var index = 0; index < entries.length; index++) {
  72241. var mesh = entries[index];
  72242. this.addEntry(mesh);
  72243. }
  72244. };
  72245. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72246. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72247. if (this.blocks) {
  72248. for (var index = 0; index < this.blocks.length; index++) {
  72249. var block = this.blocks[index];
  72250. block.select(frustumPlanes, selection, allowDuplicate);
  72251. }
  72252. return;
  72253. }
  72254. if (allowDuplicate) {
  72255. selection.concat(this.entries);
  72256. }
  72257. else {
  72258. selection.concatWithNoDuplicate(this.entries);
  72259. }
  72260. }
  72261. };
  72262. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72263. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72264. if (this.blocks) {
  72265. for (var index = 0; index < this.blocks.length; index++) {
  72266. var block = this.blocks[index];
  72267. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72268. }
  72269. return;
  72270. }
  72271. if (allowDuplicate) {
  72272. selection.concat(this.entries);
  72273. }
  72274. else {
  72275. selection.concatWithNoDuplicate(this.entries);
  72276. }
  72277. }
  72278. };
  72279. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72280. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72281. if (this.blocks) {
  72282. for (var index = 0; index < this.blocks.length; index++) {
  72283. var block = this.blocks[index];
  72284. block.intersectsRay(ray, selection);
  72285. }
  72286. return;
  72287. }
  72288. selection.concatWithNoDuplicate(this.entries);
  72289. }
  72290. };
  72291. OctreeBlock.prototype.createInnerBlocks = function () {
  72292. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72293. };
  72294. return OctreeBlock;
  72295. }());
  72296. BABYLON.OctreeBlock = OctreeBlock;
  72297. })(BABYLON || (BABYLON = {}));
  72298. //# sourceMappingURL=babylon.octreeBlock.js.map
  72299. var BABYLON;
  72300. (function (BABYLON) {
  72301. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72302. __extends(VRDistortionCorrectionPostProcess, _super);
  72303. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72304. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72305. 'LensCenter',
  72306. 'Scale',
  72307. 'ScaleIn',
  72308. 'HmdWarpParam'
  72309. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72310. _this._isRightEye = isRightEye;
  72311. _this._distortionFactors = vrMetrics.distortionK;
  72312. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72313. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72314. _this.adaptScaleToCurrentViewport = true;
  72315. _this.onSizeChangedObservable.add(function () {
  72316. _this.aspectRatio = _this.width * .5 / _this.height;
  72317. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72318. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72319. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72320. });
  72321. _this.onApplyObservable.add(function (effect) {
  72322. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72323. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72324. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72325. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72326. });
  72327. return _this;
  72328. }
  72329. return VRDistortionCorrectionPostProcess;
  72330. }(BABYLON.PostProcess));
  72331. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72332. })(BABYLON || (BABYLON = {}));
  72333. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72334. var BABYLON;
  72335. (function (BABYLON) {
  72336. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72337. __extends(AnaglyphPostProcess, _super);
  72338. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72339. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72340. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72341. _this.onApplyObservable.add(function (effect) {
  72342. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72343. });
  72344. return _this;
  72345. }
  72346. return AnaglyphPostProcess;
  72347. }(BABYLON.PostProcess));
  72348. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72349. })(BABYLON || (BABYLON = {}));
  72350. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72351. var BABYLON;
  72352. (function (BABYLON) {
  72353. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72354. __extends(StereoscopicInterlacePostProcess, _super);
  72355. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72356. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72357. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72358. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72359. _this.onSizeChangedObservable.add(function () {
  72360. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72361. });
  72362. _this.onApplyObservable.add(function (effect) {
  72363. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72364. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72365. });
  72366. return _this;
  72367. }
  72368. return StereoscopicInterlacePostProcess;
  72369. }(BABYLON.PostProcess));
  72370. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72371. })(BABYLON || (BABYLON = {}));
  72372. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72373. var BABYLON;
  72374. (function (BABYLON) {
  72375. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72376. function FreeCameraDeviceOrientationInput() {
  72377. var _this = this;
  72378. this._screenOrientationAngle = 0;
  72379. this._screenQuaternion = new BABYLON.Quaternion();
  72380. this._alpha = 0;
  72381. this._beta = 0;
  72382. this._gamma = 0;
  72383. this._orientationChanged = function () {
  72384. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72385. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72386. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72387. };
  72388. this._deviceOrientation = function (evt) {
  72389. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72390. _this._beta = evt.beta !== null ? evt.beta : 0;
  72391. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72392. };
  72393. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72394. this._orientationChanged();
  72395. }
  72396. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72397. get: function () {
  72398. return this._camera;
  72399. },
  72400. set: function (camera) {
  72401. this._camera = camera;
  72402. if (this._camera != null && !this._camera.rotationQuaternion) {
  72403. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72404. }
  72405. },
  72406. enumerable: true,
  72407. configurable: true
  72408. });
  72409. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72410. window.addEventListener("orientationchange", this._orientationChanged);
  72411. window.addEventListener("deviceorientation", this._deviceOrientation);
  72412. //In certain cases, the attach control is called AFTER orientation was changed,
  72413. //So this is needed.
  72414. this._orientationChanged();
  72415. };
  72416. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72417. window.removeEventListener("orientationchange", this._orientationChanged);
  72418. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72419. };
  72420. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72421. //if no device orientation provided, don't update the rotation.
  72422. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72423. if (!this._alpha)
  72424. return;
  72425. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72426. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72427. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72428. //Mirror on XY Plane
  72429. this._camera.rotationQuaternion.z *= -1;
  72430. this._camera.rotationQuaternion.w *= -1;
  72431. };
  72432. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72433. return "FreeCameraDeviceOrientationInput";
  72434. };
  72435. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72436. return "deviceOrientation";
  72437. };
  72438. return FreeCameraDeviceOrientationInput;
  72439. }());
  72440. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72441. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72442. })(BABYLON || (BABYLON = {}));
  72443. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72444. var BABYLON;
  72445. (function (BABYLON) {
  72446. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72447. function ArcRotateCameraVRDeviceOrientationInput() {
  72448. this.alphaCorrection = 1;
  72449. this.betaCorrection = 1;
  72450. this.gammaCorrection = 1;
  72451. this._alpha = 0;
  72452. this._gamma = 0;
  72453. this._dirty = false;
  72454. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72455. }
  72456. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72457. this.camera.attachControl(element, noPreventDefault);
  72458. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72459. };
  72460. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72461. if (evt.alpha !== null) {
  72462. this._alpha = +evt.alpha | 0;
  72463. }
  72464. if (evt.gamma !== null) {
  72465. this._gamma = +evt.gamma | 0;
  72466. }
  72467. this._dirty = true;
  72468. };
  72469. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72470. if (this._dirty) {
  72471. this._dirty = false;
  72472. if (this._gamma < 0) {
  72473. this._gamma = 180 + this._gamma;
  72474. }
  72475. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72476. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72477. }
  72478. };
  72479. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72480. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72481. };
  72482. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72483. return "ArcRotateCameraVRDeviceOrientationInput";
  72484. };
  72485. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72486. return "VRDeviceOrientation";
  72487. };
  72488. return ArcRotateCameraVRDeviceOrientationInput;
  72489. }());
  72490. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72491. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72492. })(BABYLON || (BABYLON = {}));
  72493. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72494. var BABYLON;
  72495. (function (BABYLON) {
  72496. var VRCameraMetrics = /** @class */ (function () {
  72497. function VRCameraMetrics() {
  72498. this.compensateDistortion = true;
  72499. }
  72500. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72501. get: function () {
  72502. return this.hResolution / (2 * this.vResolution);
  72503. },
  72504. enumerable: true,
  72505. configurable: true
  72506. });
  72507. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72508. get: function () {
  72509. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72510. },
  72511. enumerable: true,
  72512. configurable: true
  72513. });
  72514. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72515. get: function () {
  72516. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72517. var h = (4 * meters) / this.hScreenSize;
  72518. return BABYLON.Matrix.Translation(h, 0, 0);
  72519. },
  72520. enumerable: true,
  72521. configurable: true
  72522. });
  72523. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72524. get: function () {
  72525. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72526. var h = (4 * meters) / this.hScreenSize;
  72527. return BABYLON.Matrix.Translation(-h, 0, 0);
  72528. },
  72529. enumerable: true,
  72530. configurable: true
  72531. });
  72532. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72533. get: function () {
  72534. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72535. },
  72536. enumerable: true,
  72537. configurable: true
  72538. });
  72539. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72540. get: function () {
  72541. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72542. },
  72543. enumerable: true,
  72544. configurable: true
  72545. });
  72546. VRCameraMetrics.GetDefault = function () {
  72547. var result = new VRCameraMetrics();
  72548. result.hResolution = 1280;
  72549. result.vResolution = 800;
  72550. result.hScreenSize = 0.149759993;
  72551. result.vScreenSize = 0.0935999975;
  72552. result.vScreenCenter = 0.0467999987;
  72553. result.eyeToScreenDistance = 0.0410000011;
  72554. result.lensSeparationDistance = 0.0635000020;
  72555. result.interpupillaryDistance = 0.0640000030;
  72556. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72557. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72558. result.postProcessScaleFactor = 1.714605507808412;
  72559. result.lensCenterOffset = 0.151976421;
  72560. return result;
  72561. };
  72562. return VRCameraMetrics;
  72563. }());
  72564. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72565. })(BABYLON || (BABYLON = {}));
  72566. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72567. var BABYLON;
  72568. (function (BABYLON) {
  72569. var WebVRFreeCamera = /** @class */ (function (_super) {
  72570. __extends(WebVRFreeCamera, _super);
  72571. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72572. if (webVROptions === void 0) { webVROptions = {}; }
  72573. var _this = _super.call(this, name, position, scene) || this;
  72574. _this.webVROptions = webVROptions;
  72575. _this._vrDevice = null;
  72576. _this.rawPose = null;
  72577. _this._specsVersion = "1.1";
  72578. _this._attached = false;
  72579. _this._descendants = [];
  72580. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72581. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72582. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72583. _this._standingMatrix = null;
  72584. // Represents device position and rotation in babylon space
  72585. _this.devicePosition = BABYLON.Vector3.Zero();
  72586. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72587. _this.deviceScaleFactor = 1;
  72588. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72589. _this._worldToDevice = BABYLON.Matrix.Identity();
  72590. _this.controllers = [];
  72591. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72592. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72593. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72594. _this._defaultHeight = 0;
  72595. _this.deviceDistanceToRoomGround = function () {
  72596. if (_this._standingMatrix) {
  72597. // Add standing matrix offset to get real offset from ground in room
  72598. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72599. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72600. }
  72601. else {
  72602. return _this._defaultHeight;
  72603. }
  72604. };
  72605. _this.useStandingMatrix = function (callback) {
  72606. if (callback === void 0) { callback = function (bool) { }; }
  72607. // Use standing matrix if availible
  72608. if (!navigator || !navigator.getVRDisplays) {
  72609. callback(false);
  72610. }
  72611. else {
  72612. navigator.getVRDisplays().then(function (displays) {
  72613. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72614. callback(false);
  72615. }
  72616. else {
  72617. _this._standingMatrix = new BABYLON.Matrix();
  72618. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72619. if (!_this.getScene().useRightHandedSystem) {
  72620. [2, 6, 8, 9, 14].forEach(function (num) {
  72621. if (_this._standingMatrix) {
  72622. _this._standingMatrix.m[num] *= -1;
  72623. }
  72624. });
  72625. }
  72626. callback(true);
  72627. }
  72628. });
  72629. }
  72630. };
  72631. _this._workingVector = BABYLON.Vector3.Zero();
  72632. _this._oneVector = BABYLON.Vector3.One();
  72633. _this._workingMatrix = BABYLON.Matrix.Identity();
  72634. _this._cache.position = BABYLON.Vector3.Zero();
  72635. if (webVROptions.defaultHeight) {
  72636. _this._defaultHeight = webVROptions.defaultHeight;
  72637. _this.position.y = _this._defaultHeight;
  72638. }
  72639. _this.minZ = 0.1;
  72640. //legacy support - the compensation boolean was removed.
  72641. if (arguments.length === 5) {
  72642. _this.webVROptions = arguments[4];
  72643. }
  72644. // default webVR options
  72645. if (_this.webVROptions.trackPosition == undefined) {
  72646. _this.webVROptions.trackPosition = true;
  72647. }
  72648. if (_this.webVROptions.controllerMeshes == undefined) {
  72649. _this.webVROptions.controllerMeshes = true;
  72650. }
  72651. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72652. _this.webVROptions.defaultLightingOnControllers = true;
  72653. }
  72654. _this.rotationQuaternion = new BABYLON.Quaternion();
  72655. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72656. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72657. }
  72658. //enable VR
  72659. var engine = _this.getEngine();
  72660. _this._onVREnabled = function (success) { if (success) {
  72661. _this.initControllers();
  72662. } };
  72663. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72664. engine.initWebVR().add(function (event) {
  72665. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72666. return;
  72667. }
  72668. _this._vrDevice = event.vrDisplay;
  72669. //reset the rig parameters.
  72670. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72671. if (_this._attached) {
  72672. _this.getEngine().enableVR();
  72673. }
  72674. });
  72675. if (typeof (VRFrameData) !== "undefined")
  72676. _this._frameData = new VRFrameData();
  72677. /**
  72678. * The idea behind the following lines:
  72679. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72680. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72681. * the second will not show it correctly.
  72682. *
  72683. * To solve this - each object that has the camera as parent will be added to a protected array.
  72684. * When the rig camera renders, it will take this array and set all of those to be its children.
  72685. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72686. * Amazing!
  72687. */
  72688. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72689. if (camera.parent === _this && _this.rigParenting) {
  72690. _this._descendants = _this.getDescendants(true, function (n) {
  72691. // don't take the cameras or the controllers!
  72692. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72693. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72694. return !isController && !isRigCamera;
  72695. });
  72696. _this._descendants.forEach(function (node) {
  72697. node.parent = camera;
  72698. });
  72699. }
  72700. });
  72701. scene.onAfterCameraRenderObservable.add(function (camera) {
  72702. if (camera.parent === _this && _this.rigParenting) {
  72703. _this._descendants.forEach(function (node) {
  72704. node.parent = _this;
  72705. });
  72706. }
  72707. });
  72708. return _this;
  72709. }
  72710. WebVRFreeCamera.prototype.dispose = function () {
  72711. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72712. _super.prototype.dispose.call(this);
  72713. };
  72714. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72715. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72716. var gp = _a[_i];
  72717. if (gp.hand === name) {
  72718. return gp;
  72719. }
  72720. }
  72721. return null;
  72722. };
  72723. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72724. get: function () {
  72725. if (!this._leftController) {
  72726. this._leftController = this.getControllerByName("left");
  72727. }
  72728. return this._leftController;
  72729. },
  72730. enumerable: true,
  72731. configurable: true
  72732. });
  72733. ;
  72734. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72735. get: function () {
  72736. if (!this._rightController) {
  72737. this._rightController = this.getControllerByName("right");
  72738. }
  72739. return this._rightController;
  72740. },
  72741. enumerable: true,
  72742. configurable: true
  72743. });
  72744. ;
  72745. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72746. if (length === void 0) { length = 100; }
  72747. if (this.leftCamera) {
  72748. // Use left eye to avoid computation to compute center on every call
  72749. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72750. }
  72751. else {
  72752. return _super.prototype.getForwardRay.call(this, length);
  72753. }
  72754. };
  72755. WebVRFreeCamera.prototype._checkInputs = function () {
  72756. if (this._vrDevice && this._vrDevice.isPresenting) {
  72757. this._vrDevice.getFrameData(this._frameData);
  72758. this.updateFromDevice(this._frameData.pose);
  72759. }
  72760. _super.prototype._checkInputs.call(this);
  72761. };
  72762. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72763. if (poseData && poseData.orientation) {
  72764. this.rawPose = poseData;
  72765. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72766. if (this.getScene().useRightHandedSystem) {
  72767. this._deviceRoomRotationQuaternion.z *= -1;
  72768. this._deviceRoomRotationQuaternion.w *= -1;
  72769. }
  72770. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72771. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72772. if (this.getScene().useRightHandedSystem) {
  72773. this._deviceRoomPosition.z *= -1;
  72774. }
  72775. }
  72776. }
  72777. };
  72778. /**
  72779. * WebVR's attach control will start broadcasting frames to the device.
  72780. * Note that in certain browsers (chrome for example) this function must be called
  72781. * within a user-interaction callback. Example:
  72782. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72783. *
  72784. * @param {HTMLElement} element
  72785. * @param {boolean} [noPreventDefault]
  72786. *
  72787. * @memberOf WebVRFreeCamera
  72788. */
  72789. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72790. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72791. this._attached = true;
  72792. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72793. if (this._vrDevice) {
  72794. this.getEngine().enableVR();
  72795. }
  72796. };
  72797. WebVRFreeCamera.prototype.detachControl = function (element) {
  72798. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72799. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72800. _super.prototype.detachControl.call(this, element);
  72801. this._attached = false;
  72802. this.getEngine().disableVR();
  72803. };
  72804. WebVRFreeCamera.prototype.getClassName = function () {
  72805. return "WebVRFreeCamera";
  72806. };
  72807. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72808. //uses the vrDisplay's "resetPose()".
  72809. //pitch and roll won't be affected.
  72810. this._vrDevice.resetPose();
  72811. };
  72812. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72813. var camLeft = this._rigCameras[0];
  72814. var camRight = this._rigCameras[1];
  72815. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72816. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72817. camLeft.position.copyFrom(this._deviceRoomPosition);
  72818. camRight.position.copyFrom(this._deviceRoomPosition);
  72819. };
  72820. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72821. var _this = this;
  72822. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72823. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72824. if (!this.updateCacheCalled) {
  72825. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72826. this.updateCacheCalled = true;
  72827. this.update();
  72828. }
  72829. // Set working vector to the device position in room space rotated by the new rotation
  72830. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72831. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72832. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72833. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72834. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72835. // Add translation from anchor position
  72836. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72837. this._workingVector.addInPlace(this.position);
  72838. this._workingVector.subtractInPlace(this._cache.position);
  72839. this._deviceToWorld.setTranslation(this._workingVector);
  72840. // Set an inverted matrix to be used when updating the camera
  72841. this._deviceToWorld.invertToRef(this._worldToDevice);
  72842. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72843. this.controllers.forEach(function (controller) {
  72844. controller._deviceToWorld = _this._deviceToWorld;
  72845. controller.update();
  72846. });
  72847. }
  72848. if (!ignoreParentClass) {
  72849. _super.prototype._updateCache.call(this);
  72850. }
  72851. this.updateCacheCalled = false;
  72852. };
  72853. WebVRFreeCamera.prototype.update = function () {
  72854. // Get current device position in babylon world
  72855. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72856. // Get current device rotation in babylon world
  72857. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72858. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72859. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72860. _super.prototype.update.call(this);
  72861. };
  72862. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72863. return BABYLON.Matrix.Identity();
  72864. };
  72865. /**
  72866. * This function is called by the two RIG cameras.
  72867. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72868. */
  72869. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72870. var _this = this;
  72871. //WebVR 1.1
  72872. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72873. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72874. if (!this.getScene().useRightHandedSystem) {
  72875. [2, 6, 8, 9, 14].forEach(function (num) {
  72876. _this._webvrViewMatrix.m[num] *= -1;
  72877. });
  72878. }
  72879. // update the camera rotation matrix
  72880. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72881. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72882. // Computing target and final matrix
  72883. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72884. var parentCamera = this._cameraRigParams["parentCamera"];
  72885. // should the view matrix be updated with scale and position offset?
  72886. if (parentCamera.deviceScaleFactor !== 1) {
  72887. this._webvrViewMatrix.invert();
  72888. // scale the position, if set
  72889. if (parentCamera.deviceScaleFactor) {
  72890. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72891. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72892. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72893. }
  72894. this._webvrViewMatrix.invert();
  72895. }
  72896. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72897. return this._webvrViewMatrix;
  72898. };
  72899. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72900. var _this = this;
  72901. var parentCamera = this.parent;
  72902. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72903. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72904. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72905. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72906. //babylon compatible matrix
  72907. if (!this.getScene().useRightHandedSystem) {
  72908. [8, 9, 10, 11].forEach(function (num) {
  72909. _this._projectionMatrix.m[num] *= -1;
  72910. });
  72911. }
  72912. return this._projectionMatrix;
  72913. };
  72914. WebVRFreeCamera.prototype.initControllers = function () {
  72915. var _this = this;
  72916. this.controllers = [];
  72917. var manager = this.getScene().gamepadManager;
  72918. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72919. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72920. var webVrController = gamepad;
  72921. if (webVrController.defaultModel) {
  72922. webVrController.defaultModel.setEnabled(false);
  72923. }
  72924. if (webVrController.hand === "right") {
  72925. _this._rightController = null;
  72926. }
  72927. if (webVrController.hand === "left") {
  72928. _this._rightController = null;
  72929. }
  72930. var controllerIndex = _this.controllers.indexOf(webVrController);
  72931. if (controllerIndex !== -1) {
  72932. _this.controllers.splice(controllerIndex, 1);
  72933. }
  72934. }
  72935. });
  72936. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72937. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72938. var webVrController_1 = gamepad;
  72939. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72940. if (_this.webVROptions.controllerMeshes) {
  72941. if (webVrController_1.defaultModel) {
  72942. webVrController_1.defaultModel.setEnabled(true);
  72943. }
  72944. else {
  72945. // Load the meshes
  72946. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72947. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72948. if (_this.webVROptions.defaultLightingOnControllers) {
  72949. if (!_this._lightOnControllers) {
  72950. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72951. }
  72952. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72953. var children = mesh.getChildren();
  72954. if (children.length !== 0) {
  72955. children.forEach(function (mesh) {
  72956. light.includedOnlyMeshes.push(mesh);
  72957. activateLightOnSubMeshes_1(mesh, light);
  72958. });
  72959. }
  72960. };
  72961. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72962. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72963. }
  72964. });
  72965. }
  72966. }
  72967. webVrController_1.attachToPoseControlledCamera(_this);
  72968. // since this is async - sanity check. Is the controller already stored?
  72969. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72970. //add to the controllers array
  72971. _this.controllers.push(webVrController_1);
  72972. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72973. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72974. // So we're overriding setting left & right manually to be sure
  72975. var firstViveWandDetected = false;
  72976. for (var i = 0; i < _this.controllers.length; i++) {
  72977. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72978. if (!firstViveWandDetected) {
  72979. firstViveWandDetected = true;
  72980. _this.controllers[i].hand = "left";
  72981. }
  72982. else {
  72983. _this.controllers[i].hand = "right";
  72984. }
  72985. }
  72986. }
  72987. //did we find enough controllers? Great! let the developer know.
  72988. if (_this.controllers.length >= 2) {
  72989. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72990. }
  72991. }
  72992. }
  72993. });
  72994. };
  72995. return WebVRFreeCamera;
  72996. }(BABYLON.FreeCamera));
  72997. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72998. })(BABYLON || (BABYLON = {}));
  72999. //# sourceMappingURL=babylon.webVRCamera.js.map
  73000. var BABYLON;
  73001. (function (BABYLON) {
  73002. // We're mainly based on the logic defined into the FreeCamera code
  73003. var DeviceOrientationCamera = /** @class */ (function (_super) {
  73004. __extends(DeviceOrientationCamera, _super);
  73005. function DeviceOrientationCamera(name, position, scene) {
  73006. var _this = _super.call(this, name, position, scene) || this;
  73007. _this._quaternionCache = new BABYLON.Quaternion();
  73008. _this.inputs.addDeviceOrientation();
  73009. return _this;
  73010. }
  73011. DeviceOrientationCamera.prototype.getClassName = function () {
  73012. return "DeviceOrientationCamera";
  73013. };
  73014. DeviceOrientationCamera.prototype._checkInputs = function () {
  73015. _super.prototype._checkInputs.call(this);
  73016. this._quaternionCache.copyFrom(this.rotationQuaternion);
  73017. if (this._initialQuaternion) {
  73018. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73019. }
  73020. };
  73021. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  73022. var _this = this;
  73023. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  73024. //can only work if this camera has a rotation quaternion already.
  73025. if (!this.rotationQuaternion)
  73026. return;
  73027. if (!this._initialQuaternion) {
  73028. this._initialQuaternion = new BABYLON.Quaternion();
  73029. }
  73030. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  73031. ['x', 'y', 'z'].forEach(function (axisName) {
  73032. if (!axis[axisName]) {
  73033. _this._initialQuaternion[axisName] = 0;
  73034. }
  73035. else {
  73036. _this._initialQuaternion[axisName] *= -1;
  73037. }
  73038. });
  73039. this._initialQuaternion.normalize();
  73040. //force rotation update
  73041. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73042. };
  73043. return DeviceOrientationCamera;
  73044. }(BABYLON.FreeCamera));
  73045. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  73046. })(BABYLON || (BABYLON = {}));
  73047. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  73048. var BABYLON;
  73049. (function (BABYLON) {
  73050. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  73051. __extends(VRDeviceOrientationFreeCamera, _super);
  73052. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73053. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73054. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73055. var _this = _super.call(this, name, position, scene) || this;
  73056. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73057. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73058. return _this;
  73059. }
  73060. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  73061. return "VRDeviceOrientationFreeCamera";
  73062. };
  73063. return VRDeviceOrientationFreeCamera;
  73064. }(BABYLON.DeviceOrientationCamera));
  73065. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  73066. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  73067. __extends(VRDeviceOrientationGamepadCamera, _super);
  73068. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73069. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73070. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73071. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  73072. _this.inputs.addGamepad();
  73073. return _this;
  73074. }
  73075. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  73076. return "VRDeviceOrientationGamepadCamera";
  73077. };
  73078. return VRDeviceOrientationGamepadCamera;
  73079. }(VRDeviceOrientationFreeCamera));
  73080. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  73081. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  73082. __extends(VRDeviceOrientationArcRotateCamera, _super);
  73083. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  73084. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73085. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73086. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73087. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73088. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73089. _this.inputs.addVRDeviceOrientation();
  73090. return _this;
  73091. }
  73092. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  73093. return "VRDeviceOrientationArcRotateCamera";
  73094. };
  73095. return VRDeviceOrientationArcRotateCamera;
  73096. }(BABYLON.ArcRotateCamera));
  73097. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  73098. })(BABYLON || (BABYLON = {}));
  73099. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  73100. var BABYLON;
  73101. (function (BABYLON) {
  73102. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  73103. __extends(AnaglyphFreeCamera, _super);
  73104. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  73105. var _this = _super.call(this, name, position, scene) || this;
  73106. _this.interaxialDistance = interaxialDistance;
  73107. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73108. return _this;
  73109. }
  73110. AnaglyphFreeCamera.prototype.getClassName = function () {
  73111. return "AnaglyphFreeCamera";
  73112. };
  73113. return AnaglyphFreeCamera;
  73114. }(BABYLON.FreeCamera));
  73115. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  73116. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  73117. __extends(AnaglyphArcRotateCamera, _super);
  73118. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  73119. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73120. _this.interaxialDistance = interaxialDistance;
  73121. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73122. return _this;
  73123. }
  73124. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  73125. return "AnaglyphArcRotateCamera";
  73126. };
  73127. return AnaglyphArcRotateCamera;
  73128. }(BABYLON.ArcRotateCamera));
  73129. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  73130. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  73131. __extends(AnaglyphGamepadCamera, _super);
  73132. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73133. var _this = _super.call(this, name, position, scene) || this;
  73134. _this.interaxialDistance = interaxialDistance;
  73135. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73136. return _this;
  73137. }
  73138. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73139. return "AnaglyphGamepadCamera";
  73140. };
  73141. return AnaglyphGamepadCamera;
  73142. }(BABYLON.GamepadCamera));
  73143. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73144. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73145. __extends(AnaglyphUniversalCamera, _super);
  73146. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73147. var _this = _super.call(this, name, position, scene) || this;
  73148. _this.interaxialDistance = interaxialDistance;
  73149. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73150. return _this;
  73151. }
  73152. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73153. return "AnaglyphUniversalCamera";
  73154. };
  73155. return AnaglyphUniversalCamera;
  73156. }(BABYLON.UniversalCamera));
  73157. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73158. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73159. __extends(StereoscopicFreeCamera, _super);
  73160. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73161. var _this = _super.call(this, name, position, scene) || this;
  73162. _this.interaxialDistance = interaxialDistance;
  73163. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73164. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73165. return _this;
  73166. }
  73167. StereoscopicFreeCamera.prototype.getClassName = function () {
  73168. return "StereoscopicFreeCamera";
  73169. };
  73170. return StereoscopicFreeCamera;
  73171. }(BABYLON.FreeCamera));
  73172. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73173. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73174. __extends(StereoscopicArcRotateCamera, _super);
  73175. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73176. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73177. _this.interaxialDistance = interaxialDistance;
  73178. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73179. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73180. return _this;
  73181. }
  73182. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73183. return "StereoscopicArcRotateCamera";
  73184. };
  73185. return StereoscopicArcRotateCamera;
  73186. }(BABYLON.ArcRotateCamera));
  73187. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73188. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73189. __extends(StereoscopicGamepadCamera, _super);
  73190. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73191. var _this = _super.call(this, name, position, scene) || this;
  73192. _this.interaxialDistance = interaxialDistance;
  73193. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73194. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73195. return _this;
  73196. }
  73197. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73198. return "StereoscopicGamepadCamera";
  73199. };
  73200. return StereoscopicGamepadCamera;
  73201. }(BABYLON.GamepadCamera));
  73202. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73203. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73204. __extends(StereoscopicUniversalCamera, _super);
  73205. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73206. var _this = _super.call(this, name, position, scene) || this;
  73207. _this.interaxialDistance = interaxialDistance;
  73208. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73209. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73210. return _this;
  73211. }
  73212. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73213. return "StereoscopicUniversalCamera";
  73214. };
  73215. return StereoscopicUniversalCamera;
  73216. }(BABYLON.UniversalCamera));
  73217. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73218. })(BABYLON || (BABYLON = {}));
  73219. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73220. var BABYLON;
  73221. (function (BABYLON) {
  73222. var VRExperienceHelper = /** @class */ (function () {
  73223. function VRExperienceHelper(scene, webVROptions) {
  73224. if (webVROptions === void 0) { webVROptions = {}; }
  73225. var _this = this;
  73226. this.webVROptions = webVROptions;
  73227. // Can the system support WebVR, even if a headset isn't plugged in?
  73228. this._webVRsupported = false;
  73229. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73230. this._webVRready = false;
  73231. // Are we waiting for the requestPresent callback to complete?
  73232. this._webVRrequesting = false;
  73233. // Are we presenting to the headset right now?
  73234. this._webVRpresenting = false;
  73235. // Are we presenting in the fullscreen fallback?
  73236. this._fullscreenVRpresenting = false;
  73237. /**
  73238. * Observable raised when entering VR.
  73239. */
  73240. this.onEnteringVRObservable = new BABYLON.Observable();
  73241. /**
  73242. * Observable raised when exiting VR.
  73243. */
  73244. this.onExitingVRObservable = new BABYLON.Observable();
  73245. /**
  73246. * Observable raised when controller mesh is loaded.
  73247. */
  73248. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73249. this._useCustomVRButton = false;
  73250. this._teleportationRequested = false;
  73251. this._teleportationEnabledOnLeftController = false;
  73252. this._teleportationEnabledOnRightController = false;
  73253. this._interactionsEnabledOnLeftController = false;
  73254. this._interactionsEnabledOnRightController = false;
  73255. this._leftControllerReady = false;
  73256. this._rightControllerReady = false;
  73257. this._floorMeshesCollection = [];
  73258. this._teleportationAllowed = false;
  73259. this._rotationAllowed = true;
  73260. this._teleportationRequestInitiated = false;
  73261. this._teleportationBackRequestInitiated = false;
  73262. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73263. this._rotationRightAsked = false;
  73264. this._rotationLeftAsked = false;
  73265. this._isDefaultTeleportationTarget = true;
  73266. this._teleportationFillColor = "#444444";
  73267. this._teleportationBorderColor = "#FFFFFF";
  73268. this._rotationAngle = 0;
  73269. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73270. this._padSensibilityUp = 0.65;
  73271. this._padSensibilityDown = 0.35;
  73272. /**
  73273. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73274. */
  73275. this.onNewMeshSelected = new BABYLON.Observable();
  73276. /**
  73277. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73278. */
  73279. this.onNewMeshPicked = new BABYLON.Observable();
  73280. /**
  73281. * Observable raised before camera teleportation
  73282. */
  73283. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73284. /**
  73285. * Observable raised after camera teleportation
  73286. */
  73287. this.onAfterCameraTeleport = new BABYLON.Observable();
  73288. /**
  73289. * Observable raised when current selected mesh gets unselected
  73290. */
  73291. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73292. /**
  73293. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73294. */
  73295. this.teleportationEnabled = true;
  73296. this._pointerDownOnMeshAsked = false;
  73297. this._isActionableMesh = false;
  73298. this._teleportationInitialized = false;
  73299. this._interactionsEnabled = false;
  73300. this._interactionsRequested = false;
  73301. this._displayGaze = true;
  73302. this._displayLaserPointer = true;
  73303. this._dpadPressed = true;
  73304. this._onResize = function () {
  73305. _this.moveButtonToBottomRight();
  73306. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73307. _this.exitVR();
  73308. }
  73309. };
  73310. this._onFullscreenChange = function () {
  73311. if (document.fullscreen !== undefined) {
  73312. _this._fullscreenVRpresenting = document.fullscreen;
  73313. }
  73314. else if (document.mozFullScreen !== undefined) {
  73315. _this._fullscreenVRpresenting = document.mozFullScreen;
  73316. }
  73317. else if (document.webkitIsFullScreen !== undefined) {
  73318. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73319. }
  73320. else if (document.msIsFullScreen !== undefined) {
  73321. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73322. }
  73323. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73324. _this.exitVR();
  73325. if (!_this._useCustomVRButton) {
  73326. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73327. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73328. }
  73329. }
  73330. };
  73331. this.beforeRender = function () {
  73332. _this._castRayAndSelectObject();
  73333. };
  73334. this._onNewGamepadConnected = function (gamepad) {
  73335. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73336. if (gamepad.leftStick) {
  73337. gamepad.onleftstickchanged(function (stickValues) {
  73338. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73339. // Listening to classic/xbox gamepad only if no VR controller is active
  73340. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73341. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73342. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73343. _this._checkTeleportWithRay(stickValues);
  73344. _this._checkTeleportBackwards(stickValues);
  73345. }
  73346. }
  73347. });
  73348. }
  73349. if (gamepad.rightStick) {
  73350. gamepad.onrightstickchanged(function (stickValues) {
  73351. if (_this._teleportationInitialized) {
  73352. _this._checkRotate(stickValues);
  73353. }
  73354. });
  73355. }
  73356. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73357. gamepad.onbuttondown(function (buttonPressed) {
  73358. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73359. _this._selectionPointerDown();
  73360. }
  73361. });
  73362. gamepad.onbuttonup(function (buttonPressed) {
  73363. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73364. _this._selectionPointerUp();
  73365. }
  73366. });
  73367. }
  73368. }
  73369. else {
  73370. var webVRController = gamepad;
  73371. _this._tryEnableInteractionOnController(webVRController);
  73372. }
  73373. };
  73374. // 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
  73375. this._tryEnableInteractionOnController = function (webVRController) {
  73376. if (webVRController.hand === "left") {
  73377. _this._leftControllerReady = true;
  73378. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73379. _this._enableInteractionOnController(webVRController);
  73380. }
  73381. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73382. _this._enableTeleportationOnController(webVRController);
  73383. }
  73384. }
  73385. if (webVRController.hand === "right") {
  73386. _this._rightControllerReady = true;
  73387. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73388. _this._enableInteractionOnController(webVRController);
  73389. }
  73390. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73391. _this._enableTeleportationOnController(webVRController);
  73392. }
  73393. }
  73394. };
  73395. this._onNewGamepadDisconnected = function (gamepad) {
  73396. if (gamepad instanceof BABYLON.WebVRController) {
  73397. if (gamepad.hand === "left") {
  73398. _this._interactionsEnabledOnLeftController = false;
  73399. _this._teleportationEnabledOnLeftController = false;
  73400. _this._leftControllerReady = false;
  73401. if (_this._leftLaserPointer) {
  73402. _this._leftLaserPointer.dispose();
  73403. }
  73404. }
  73405. if (gamepad.hand === "right") {
  73406. _this._interactionsEnabledOnRightController = false;
  73407. _this._teleportationEnabledOnRightController = false;
  73408. _this._rightControllerReady = false;
  73409. if (_this._rightLaserPointer) {
  73410. _this._rightLaserPointer.dispose();
  73411. }
  73412. }
  73413. }
  73414. };
  73415. this._workingVector = BABYLON.Vector3.Zero();
  73416. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73417. this._workingMatrix = BABYLON.Matrix.Identity();
  73418. this._scene = scene;
  73419. this._canvas = scene.getEngine().getRenderingCanvas();
  73420. // Parse options
  73421. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73422. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73423. }
  73424. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73425. webVROptions.createDeviceOrientationCamera = true;
  73426. }
  73427. if (webVROptions.defaultHeight === undefined) {
  73428. webVROptions.defaultHeight = 1.7;
  73429. }
  73430. if (webVROptions.useCustomVRButton) {
  73431. this._useCustomVRButton = true;
  73432. if (webVROptions.customVRButton) {
  73433. this._btnVR = webVROptions.customVRButton;
  73434. }
  73435. }
  73436. if (webVROptions.rayLength) {
  73437. this._rayLength = webVROptions.rayLength;
  73438. }
  73439. this._defaultHeight = webVROptions.defaultHeight;
  73440. // Set position
  73441. if (this._scene.activeCamera) {
  73442. this._position = this._scene.activeCamera.position.clone();
  73443. }
  73444. else {
  73445. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73446. }
  73447. // Set non-vr camera
  73448. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73449. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73450. // Copy data from existing camera
  73451. if (this._scene.activeCamera) {
  73452. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73453. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73454. // Set rotation from previous camera
  73455. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73456. var targetCamera = this._scene.activeCamera;
  73457. if (targetCamera.rotationQuaternion) {
  73458. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73459. }
  73460. else {
  73461. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73462. }
  73463. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73464. }
  73465. }
  73466. this._scene.activeCamera = this._deviceOrientationCamera;
  73467. if (this._canvas) {
  73468. this._scene.activeCamera.attachControl(this._canvas);
  73469. }
  73470. }
  73471. else {
  73472. this._existingCamera = this._scene.activeCamera;
  73473. }
  73474. // Create VR cameras
  73475. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73476. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73477. }
  73478. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73479. this._webVRCamera.useStandingMatrix();
  73480. // Create default button
  73481. if (!this._useCustomVRButton) {
  73482. this._btnVR = document.createElement("BUTTON");
  73483. this._btnVR.className = "babylonVRicon";
  73484. this._btnVR.id = "babylonVRiconbtn";
  73485. this._btnVR.title = "Click to switch to VR";
  73486. 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) }";
  73487. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73488. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73489. // css += ".babylonVRicon.vrdisplaysupported { }";
  73490. // css += ".babylonVRicon.vrdisplayready { }";
  73491. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73492. var style = document.createElement('style');
  73493. style.appendChild(document.createTextNode(css));
  73494. document.getElementsByTagName('head')[0].appendChild(style);
  73495. this.moveButtonToBottomRight();
  73496. }
  73497. // VR button click event
  73498. if (this._btnVR) {
  73499. this._btnVR.addEventListener("click", function () {
  73500. if (!_this.isInVRMode) {
  73501. _this.enterVR();
  73502. }
  73503. else {
  73504. _this.exitVR();
  73505. }
  73506. });
  73507. }
  73508. // Window events
  73509. window.addEventListener("resize", this._onResize);
  73510. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73511. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73512. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73513. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73514. // Display vr button when headset is connected
  73515. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73516. this.displayVRButton();
  73517. }
  73518. else {
  73519. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73520. if (e.vrDisplay) {
  73521. _this.displayVRButton();
  73522. }
  73523. });
  73524. }
  73525. // Exiting VR mode using 'ESC' key on desktop
  73526. this._onKeyDown = function (event) {
  73527. if (event.keyCode === 27 && _this.isInVRMode) {
  73528. _this.exitVR();
  73529. }
  73530. };
  73531. document.addEventListener("keydown", this._onKeyDown);
  73532. // Exiting VR mode double tapping the touch screen
  73533. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73534. if (_this.isInVRMode) {
  73535. _this.exitVR();
  73536. if (_this._fullscreenVRpresenting) {
  73537. _this._scene.getEngine().switchFullscreen(true);
  73538. }
  73539. }
  73540. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73541. // Listen for WebVR display changes
  73542. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73543. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73544. this._onVRRequestPresentStart = function () {
  73545. _this._webVRrequesting = true;
  73546. _this.updateButtonVisibility();
  73547. };
  73548. this._onVRRequestPresentComplete = function (success) {
  73549. _this._webVRrequesting = false;
  73550. _this.updateButtonVisibility();
  73551. };
  73552. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73553. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73554. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73555. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73556. scene.onDisposeObservable.add(function () {
  73557. _this.dispose();
  73558. });
  73559. // Gamepad connection events
  73560. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73561. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73562. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73563. this.updateButtonVisibility();
  73564. //create easing functions
  73565. this._circleEase = new BABYLON.CircleEase();
  73566. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73567. }
  73568. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73569. /** Return this.onEnteringVRObservable
  73570. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73571. */
  73572. get: function () {
  73573. return this.onEnteringVRObservable;
  73574. },
  73575. enumerable: true,
  73576. configurable: true
  73577. });
  73578. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73579. /** Return this.onExitingVRObservable
  73580. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73581. */
  73582. get: function () {
  73583. return this.onExitingVRObservable;
  73584. },
  73585. enumerable: true,
  73586. configurable: true
  73587. });
  73588. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73589. /** Return this.onControllerMeshLoadedObservable
  73590. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73591. */
  73592. get: function () {
  73593. return this.onControllerMeshLoadedObservable;
  73594. },
  73595. enumerable: true,
  73596. configurable: true
  73597. });
  73598. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73599. get: function () {
  73600. return this._teleportationTarget;
  73601. },
  73602. set: function (value) {
  73603. if (value) {
  73604. value.name = "teleportationTarget";
  73605. this._isDefaultTeleportationTarget = false;
  73606. this._teleportationTarget = value;
  73607. }
  73608. },
  73609. enumerable: true,
  73610. configurable: true
  73611. });
  73612. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73613. get: function () {
  73614. return this._displayGaze;
  73615. },
  73616. set: function (value) {
  73617. this._displayGaze = value;
  73618. if (!value) {
  73619. this._gazeTracker.isVisible = false;
  73620. }
  73621. },
  73622. enumerable: true,
  73623. configurable: true
  73624. });
  73625. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73626. get: function () {
  73627. return this._displayLaserPointer;
  73628. },
  73629. set: function (value) {
  73630. this._displayLaserPointer = value;
  73631. if (!value) {
  73632. if (this._rightLaserPointer) {
  73633. this._rightLaserPointer.isVisible = false;
  73634. }
  73635. if (this._leftLaserPointer) {
  73636. this._leftLaserPointer.isVisible = false;
  73637. }
  73638. }
  73639. else {
  73640. if (this._rightLaserPointer) {
  73641. this._rightLaserPointer.isVisible = true;
  73642. }
  73643. else if (this._leftLaserPointer) {
  73644. this._leftLaserPointer.isVisible = true;
  73645. }
  73646. }
  73647. },
  73648. enumerable: true,
  73649. configurable: true
  73650. });
  73651. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73652. get: function () {
  73653. return this._deviceOrientationCamera;
  73654. },
  73655. enumerable: true,
  73656. configurable: true
  73657. });
  73658. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73659. // Based on the current WebVR support, returns the current VR camera used
  73660. get: function () {
  73661. if (this._webVRready) {
  73662. return this._webVRCamera;
  73663. }
  73664. else {
  73665. return this._scene.activeCamera;
  73666. }
  73667. },
  73668. enumerable: true,
  73669. configurable: true
  73670. });
  73671. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73672. get: function () {
  73673. return this._webVRCamera;
  73674. },
  73675. enumerable: true,
  73676. configurable: true
  73677. });
  73678. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73679. get: function () {
  73680. return this._vrDeviceOrientationCamera;
  73681. },
  73682. enumerable: true,
  73683. configurable: true
  73684. });
  73685. // Raised when one of the controller has loaded successfully its associated default mesh
  73686. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73687. this._tryEnableInteractionOnController(webVRController);
  73688. try {
  73689. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73690. }
  73691. catch (err) {
  73692. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73693. }
  73694. };
  73695. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73696. /**
  73697. * Gets a value indicating if we are currently in VR mode.
  73698. */
  73699. get: function () {
  73700. return this._webVRpresenting || this._fullscreenVRpresenting;
  73701. },
  73702. enumerable: true,
  73703. configurable: true
  73704. });
  73705. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73706. var vrDisplay = this._scene.getEngine().getVRDevice();
  73707. if (vrDisplay) {
  73708. var wasPresenting = this._webVRpresenting;
  73709. // A VR display is connected
  73710. this._webVRpresenting = vrDisplay.isPresenting;
  73711. if (wasPresenting && !this._webVRpresenting)
  73712. this.exitVR();
  73713. }
  73714. else {
  73715. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73716. }
  73717. this.updateButtonVisibility();
  73718. };
  73719. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73720. this._webVRsupported = eventArgs.vrSupported;
  73721. this._webVRready = !!eventArgs.vrDisplay;
  73722. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73723. this.updateButtonVisibility();
  73724. };
  73725. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73726. if (this._canvas && !this._useCustomVRButton) {
  73727. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73728. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73729. }
  73730. };
  73731. VRExperienceHelper.prototype.displayVRButton = function () {
  73732. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73733. document.body.appendChild(this._btnVR);
  73734. this._btnVRDisplayed = true;
  73735. }
  73736. };
  73737. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73738. if (!this._btnVR || this._useCustomVRButton) {
  73739. return;
  73740. }
  73741. this._btnVR.className = "babylonVRicon";
  73742. if (this.isInVRMode) {
  73743. this._btnVR.className += " vrdisplaypresenting";
  73744. }
  73745. else {
  73746. if (this._webVRready)
  73747. this._btnVR.className += " vrdisplayready";
  73748. if (this._webVRsupported)
  73749. this._btnVR.className += " vrdisplaysupported";
  73750. if (this._webVRrequesting)
  73751. this._btnVR.className += " vrdisplayrequesting";
  73752. }
  73753. };
  73754. /**
  73755. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73756. * Otherwise, will use the fullscreen API.
  73757. */
  73758. VRExperienceHelper.prototype.enterVR = function () {
  73759. if (this.onEnteringVRObservable) {
  73760. try {
  73761. this.onEnteringVRObservable.notifyObservers(this);
  73762. }
  73763. catch (err) {
  73764. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73765. }
  73766. }
  73767. if (this._scene.activeCamera) {
  73768. this._position = this._scene.activeCamera.position.clone();
  73769. // make sure that we return to the last active camera
  73770. this._existingCamera = this._scene.activeCamera;
  73771. }
  73772. if (this._webVRrequesting)
  73773. return;
  73774. // If WebVR is supported and a headset is connected
  73775. if (this._webVRready) {
  73776. if (!this._webVRpresenting) {
  73777. this._webVRCamera.position = this._position;
  73778. this._scene.activeCamera = this._webVRCamera;
  73779. }
  73780. }
  73781. else if (this._vrDeviceOrientationCamera) {
  73782. this._vrDeviceOrientationCamera.position = this._position;
  73783. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73784. this._scene.getEngine().switchFullscreen(true);
  73785. this.updateButtonVisibility();
  73786. }
  73787. if (this._scene.activeCamera && this._canvas) {
  73788. this._scene.activeCamera.attachControl(this._canvas);
  73789. }
  73790. if (this._interactionsEnabled) {
  73791. this._scene.registerBeforeRender(this.beforeRender);
  73792. }
  73793. };
  73794. /**
  73795. * Attempt to exit VR, or fullscreen.
  73796. */
  73797. VRExperienceHelper.prototype.exitVR = function () {
  73798. if (this.onExitingVRObservable) {
  73799. try {
  73800. this.onExitingVRObservable.notifyObservers(this);
  73801. }
  73802. catch (err) {
  73803. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73804. }
  73805. }
  73806. if (this._webVRpresenting) {
  73807. this._scene.getEngine().disableVR();
  73808. }
  73809. if (this._scene.activeCamera) {
  73810. this._position = this._scene.activeCamera.position.clone();
  73811. }
  73812. if (this._deviceOrientationCamera) {
  73813. this._deviceOrientationCamera.position = this._position;
  73814. this._scene.activeCamera = this._deviceOrientationCamera;
  73815. if (this._canvas) {
  73816. this._scene.activeCamera.attachControl(this._canvas);
  73817. }
  73818. }
  73819. else if (this._existingCamera) {
  73820. this._existingCamera.position = this._position;
  73821. this._scene.activeCamera = this._existingCamera;
  73822. }
  73823. this.updateButtonVisibility();
  73824. if (this._interactionsEnabled) {
  73825. this._scene.unregisterBeforeRender(this.beforeRender);
  73826. }
  73827. };
  73828. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73829. get: function () {
  73830. return this._position;
  73831. },
  73832. set: function (value) {
  73833. this._position = value;
  73834. if (this._scene.activeCamera) {
  73835. this._scene.activeCamera.position = value;
  73836. }
  73837. },
  73838. enumerable: true,
  73839. configurable: true
  73840. });
  73841. VRExperienceHelper.prototype.enableInteractions = function () {
  73842. var _this = this;
  73843. if (!this._interactionsEnabled) {
  73844. this._interactionsRequested = true;
  73845. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73846. this._enableInteractionOnController(this._webVRCamera.leftController);
  73847. }
  73848. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73849. this._enableInteractionOnController(this._webVRCamera.rightController);
  73850. }
  73851. this._createGazeTracker();
  73852. this.raySelectionPredicate = function (mesh) {
  73853. return mesh.isVisible;
  73854. };
  73855. this.meshSelectionPredicate = function (mesh) {
  73856. return true;
  73857. };
  73858. this._raySelectionPredicate = function (mesh) {
  73859. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73860. && mesh.name.indexOf("teleportationTarget") === -1
  73861. && mesh.name.indexOf("torusTeleportation") === -1
  73862. && mesh.name.indexOf("laserPointer") === -1)) {
  73863. return _this.raySelectionPredicate(mesh);
  73864. }
  73865. return false;
  73866. };
  73867. this._interactionsEnabled = true;
  73868. }
  73869. };
  73870. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73871. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73872. if (this._floorMeshesCollection[i].id === mesh.id) {
  73873. return true;
  73874. }
  73875. }
  73876. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73877. return true;
  73878. }
  73879. return false;
  73880. };
  73881. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73882. if (!this._floorMeshesCollection) {
  73883. return;
  73884. }
  73885. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73886. return;
  73887. }
  73888. this._floorMeshesCollection.push(floorMesh);
  73889. };
  73890. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73891. if (!this._floorMeshesCollection) {
  73892. return;
  73893. }
  73894. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73895. if (meshIndex !== -1) {
  73896. this._floorMeshesCollection.splice(meshIndex, 1);
  73897. }
  73898. };
  73899. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73900. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73901. if (!this._teleportationInitialized) {
  73902. this._teleportationRequested = true;
  73903. this.enableInteractions();
  73904. if (vrTeleportationOptions.floorMeshName) {
  73905. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73906. }
  73907. if (vrTeleportationOptions.floorMeshes) {
  73908. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73909. }
  73910. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73911. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73912. }
  73913. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73914. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73915. }
  73916. // Creates an image processing post process for the vignette not relying
  73917. // on the main scene configuration for image processing to reduce setup and spaces
  73918. // (gamma/linear) conflicts.
  73919. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73920. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73921. imageProcessingConfiguration.vignetteEnabled = true;
  73922. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73923. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73924. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73925. this._teleportationInitialized = true;
  73926. if (this._isDefaultTeleportationTarget) {
  73927. this._createTeleportationCircles();
  73928. }
  73929. }
  73930. };
  73931. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73932. var _this = this;
  73933. var controllerMesh = webVRController.mesh;
  73934. if (controllerMesh) {
  73935. var makeNotPick = function (root) {
  73936. root.name += " laserPointer";
  73937. root.getChildMeshes().forEach(function (c) {
  73938. makeNotPick(c);
  73939. });
  73940. };
  73941. makeNotPick(controllerMesh);
  73942. var childMeshes = controllerMesh.getChildMeshes();
  73943. for (var i = 0; i < childMeshes.length; i++) {
  73944. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73945. controllerMesh = childMeshes[i];
  73946. break;
  73947. }
  73948. }
  73949. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73950. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73951. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73952. laserPointerMaterial.alpha = 0.6;
  73953. laserPointer.material = laserPointerMaterial;
  73954. laserPointer.rotation.x = Math.PI / 2;
  73955. laserPointer.parent = controllerMesh;
  73956. laserPointer.position.z = -0.5;
  73957. laserPointer.isVisible = false;
  73958. if (webVRController.hand === "left") {
  73959. this._leftLaserPointer = laserPointer;
  73960. this._interactionsEnabledOnLeftController = true;
  73961. if (!this._rightLaserPointer) {
  73962. this._leftLaserPointer.isVisible = true;
  73963. }
  73964. }
  73965. else {
  73966. this._rightLaserPointer = laserPointer;
  73967. this._interactionsEnabledOnRightController = true;
  73968. if (!this._leftLaserPointer) {
  73969. this._rightLaserPointer.isVisible = true;
  73970. }
  73971. }
  73972. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73973. // Enabling / disabling laserPointer
  73974. if (_this._displayLaserPointer && stateObject.value === 1) {
  73975. laserPointer.isVisible = !laserPointer.isVisible;
  73976. // Laser pointer can only be active on left or right, not both at the same time
  73977. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73978. _this._rightLaserPointer.isVisible = false;
  73979. }
  73980. else if (_this._leftLaserPointer) {
  73981. _this._leftLaserPointer.isVisible = false;
  73982. }
  73983. }
  73984. });
  73985. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73986. if (!_this._pointerDownOnMeshAsked) {
  73987. if (stateObject.value > _this._padSensibilityUp) {
  73988. _this._selectionPointerDown();
  73989. }
  73990. }
  73991. else if (stateObject.value < _this._padSensibilityDown) {
  73992. _this._selectionPointerUp();
  73993. }
  73994. });
  73995. }
  73996. };
  73997. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73998. if (webVRController === void 0) { webVRController = null; }
  73999. if (!this._teleportationRequestInitiated) {
  74000. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  74001. if (webVRController) {
  74002. // If laser pointer wasn't enabled yet
  74003. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  74004. this._leftLaserPointer.isVisible = true;
  74005. if (this._rightLaserPointer) {
  74006. this._rightLaserPointer.isVisible = false;
  74007. }
  74008. }
  74009. else if (this._displayLaserPointer && this._rightLaserPointer) {
  74010. this._rightLaserPointer.isVisible = true;
  74011. if (this._leftLaserPointer) {
  74012. this._leftLaserPointer.isVisible = false;
  74013. }
  74014. }
  74015. }
  74016. this._teleportationRequestInitiated = true;
  74017. }
  74018. }
  74019. else {
  74020. // Listening to the proper controller values changes to confirm teleportation
  74021. if (webVRController == null
  74022. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  74023. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  74024. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  74025. if (this._teleportationAllowed) {
  74026. this._teleportationAllowed = false;
  74027. this._teleportCamera();
  74028. }
  74029. this._teleportationRequestInitiated = false;
  74030. }
  74031. }
  74032. }
  74033. };
  74034. VRExperienceHelper.prototype._selectionPointerDown = function () {
  74035. this._pointerDownOnMeshAsked = true;
  74036. if (this._currentMeshSelected && this._currentHit) {
  74037. this._scene.simulatePointerDown(this._currentHit);
  74038. }
  74039. };
  74040. VRExperienceHelper.prototype._selectionPointerUp = function () {
  74041. if (this._currentMeshSelected && this._currentHit) {
  74042. this._scene.simulatePointerUp(this._currentHit);
  74043. }
  74044. this._pointerDownOnMeshAsked = false;
  74045. };
  74046. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  74047. // Only rotate when user is not currently selecting a teleportation location
  74048. if (this._teleportationRequestInitiated) {
  74049. return;
  74050. }
  74051. if (!this._rotationLeftAsked) {
  74052. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  74053. this._rotationLeftAsked = true;
  74054. if (this._rotationAllowed) {
  74055. this._rotateCamera(false);
  74056. }
  74057. }
  74058. }
  74059. else {
  74060. if (stateObject.x > -this._padSensibilityDown) {
  74061. this._rotationLeftAsked = false;
  74062. }
  74063. }
  74064. if (!this._rotationRightAsked) {
  74065. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  74066. this._rotationRightAsked = true;
  74067. if (this._rotationAllowed) {
  74068. this._rotateCamera(true);
  74069. }
  74070. }
  74071. }
  74072. else {
  74073. if (stateObject.x < this._padSensibilityDown) {
  74074. this._rotationRightAsked = false;
  74075. }
  74076. }
  74077. };
  74078. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  74079. // Only teleport backwards when user is not currently selecting a teleportation location
  74080. if (this._teleportationRequestInitiated) {
  74081. return;
  74082. }
  74083. // Teleport backwards
  74084. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  74085. if (!this._teleportationBackRequestInitiated) {
  74086. if (!this.currentVRCamera) {
  74087. return;
  74088. }
  74089. // Get rotation and position of the current camera
  74090. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  74091. var position = this.currentVRCamera.position;
  74092. // If the camera has device position, use that instead
  74093. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  74094. rotation = this.currentVRCamera.deviceRotationQuaternion;
  74095. position = this.currentVRCamera.devicePosition;
  74096. }
  74097. // Get matrix with only the y rotation of the device rotation
  74098. rotation.toEulerAnglesToRef(this._workingVector);
  74099. this._workingVector.z = 0;
  74100. this._workingVector.x = 0;
  74101. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  74102. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  74103. // Rotate backwards ray by device rotation to cast at the ground behind the user
  74104. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  74105. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  74106. var ray = new BABYLON.Ray(position, this._workingVector);
  74107. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74108. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  74109. this._teleportCamera(hit.pickedPoint);
  74110. }
  74111. this._teleportationBackRequestInitiated = true;
  74112. }
  74113. }
  74114. else {
  74115. this._teleportationBackRequestInitiated = false;
  74116. }
  74117. };
  74118. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  74119. var _this = this;
  74120. var controllerMesh = webVRController.mesh;
  74121. if (controllerMesh) {
  74122. if (webVRController.hand === "left") {
  74123. if (!this._interactionsEnabledOnLeftController) {
  74124. this._enableInteractionOnController(webVRController);
  74125. }
  74126. this._teleportationEnabledOnLeftController = true;
  74127. }
  74128. else {
  74129. if (!this._interactionsEnabledOnRightController) {
  74130. this._enableInteractionOnController(webVRController);
  74131. }
  74132. this._teleportationEnabledOnRightController = true;
  74133. }
  74134. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74135. this._dpadPressed = false;
  74136. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74137. _this._dpadPressed = stateObject.pressed;
  74138. if (!_this._dpadPressed) {
  74139. _this._rotationLeftAsked = false;
  74140. _this._rotationRightAsked = false;
  74141. _this._teleportationBackRequestInitiated = false;
  74142. }
  74143. });
  74144. }
  74145. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74146. if (_this.teleportationEnabled) {
  74147. _this._checkTeleportBackwards(stateObject);
  74148. _this._checkTeleportWithRay(stateObject, webVRController);
  74149. }
  74150. _this._checkRotate(stateObject);
  74151. });
  74152. }
  74153. };
  74154. // Gaze support used to point to teleport or to interact with an object
  74155. VRExperienceHelper.prototype._createGazeTracker = function () {
  74156. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74157. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74158. this._gazeTracker.isPickable = false;
  74159. this._gazeTracker.isVisible = false;
  74160. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74161. targetMat.specularColor = BABYLON.Color3.Black();
  74162. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74163. targetMat.backFaceCulling = false;
  74164. this._gazeTracker.material = targetMat;
  74165. };
  74166. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74167. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74168. this._teleportationTarget.isPickable = false;
  74169. var length = 512;
  74170. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74171. dynamicTexture.hasAlpha = true;
  74172. var context = dynamicTexture.getContext();
  74173. var centerX = length / 2;
  74174. var centerY = length / 2;
  74175. var radius = 200;
  74176. context.beginPath();
  74177. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74178. context.fillStyle = this._teleportationFillColor;
  74179. context.fill();
  74180. context.lineWidth = 10;
  74181. context.strokeStyle = this._teleportationBorderColor;
  74182. context.stroke();
  74183. context.closePath();
  74184. dynamicTexture.update();
  74185. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74186. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74187. this._teleportationTarget.material = teleportationCircleMaterial;
  74188. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74189. torus.isPickable = false;
  74190. torus.parent = this._teleportationTarget;
  74191. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74192. var keys = [];
  74193. keys.push({
  74194. frame: 0,
  74195. value: 0
  74196. });
  74197. keys.push({
  74198. frame: 30,
  74199. value: 0.4
  74200. });
  74201. keys.push({
  74202. frame: 60,
  74203. value: 0
  74204. });
  74205. animationInnerCircle.setKeys(keys);
  74206. var easingFunction = new BABYLON.SineEase();
  74207. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74208. animationInnerCircle.setEasingFunction(easingFunction);
  74209. torus.animations = [];
  74210. torus.animations.push(animationInnerCircle);
  74211. this._scene.beginAnimation(torus, 0, 60, true);
  74212. this._hideTeleportationTarget();
  74213. };
  74214. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74215. if (this._teleportationInitialized) {
  74216. this._teleportationTarget.isVisible = true;
  74217. if (this._isDefaultTeleportationTarget) {
  74218. this._teleportationTarget.getChildren()[0].isVisible = true;
  74219. }
  74220. }
  74221. };
  74222. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74223. if (this._teleportationInitialized) {
  74224. this._teleportationTarget.isVisible = false;
  74225. if (this._isDefaultTeleportationTarget) {
  74226. this._teleportationTarget.getChildren()[0].isVisible = false;
  74227. }
  74228. }
  74229. };
  74230. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74231. var _this = this;
  74232. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74233. return;
  74234. }
  74235. if (right) {
  74236. this._rotationAngle++;
  74237. }
  74238. else {
  74239. this._rotationAngle--;
  74240. }
  74241. this.currentVRCamera.animations = [];
  74242. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74243. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74244. var animationRotationKeys = [];
  74245. animationRotationKeys.push({
  74246. frame: 0,
  74247. value: this.currentVRCamera.rotationQuaternion
  74248. });
  74249. animationRotationKeys.push({
  74250. frame: 6,
  74251. value: target
  74252. });
  74253. animationRotation.setKeys(animationRotationKeys);
  74254. animationRotation.setEasingFunction(this._circleEase);
  74255. this.currentVRCamera.animations.push(animationRotation);
  74256. this._postProcessMove.animations = [];
  74257. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74258. var vignetteWeightKeys = [];
  74259. vignetteWeightKeys.push({
  74260. frame: 0,
  74261. value: 0
  74262. });
  74263. vignetteWeightKeys.push({
  74264. frame: 3,
  74265. value: 4
  74266. });
  74267. vignetteWeightKeys.push({
  74268. frame: 6,
  74269. value: 0
  74270. });
  74271. animationPP.setKeys(vignetteWeightKeys);
  74272. animationPP.setEasingFunction(this._circleEase);
  74273. this._postProcessMove.animations.push(animationPP);
  74274. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74275. var vignetteStretchKeys = [];
  74276. vignetteStretchKeys.push({
  74277. frame: 0,
  74278. value: 0
  74279. });
  74280. vignetteStretchKeys.push({
  74281. frame: 3,
  74282. value: 10
  74283. });
  74284. vignetteStretchKeys.push({
  74285. frame: 6,
  74286. value: 0
  74287. });
  74288. animationPP2.setKeys(vignetteStretchKeys);
  74289. animationPP2.setEasingFunction(this._circleEase);
  74290. this._postProcessMove.animations.push(animationPP2);
  74291. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74292. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74293. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74294. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74295. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74296. });
  74297. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74298. };
  74299. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74300. if (hit.pickedPoint) {
  74301. this._teleportationAllowed = true;
  74302. if (this._teleportationRequestInitiated) {
  74303. this._displayTeleportationTarget();
  74304. }
  74305. else {
  74306. this._hideTeleportationTarget();
  74307. }
  74308. this._haloCenter.copyFrom(hit.pickedPoint);
  74309. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74310. var pickNormal = hit.getNormal(true, false);
  74311. if (pickNormal) {
  74312. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74313. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74314. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74315. }
  74316. this._teleportationTarget.position.y += 0.1;
  74317. }
  74318. };
  74319. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74320. var _this = this;
  74321. if (location === void 0) { location = null; }
  74322. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74323. return;
  74324. }
  74325. if (!location) {
  74326. location = this._haloCenter;
  74327. }
  74328. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74329. // offset of the headset from the anchor.
  74330. if (this.webVRCamera.leftCamera) {
  74331. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74332. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74333. location.subtractToRef(this._workingVector, this._workingVector);
  74334. }
  74335. else {
  74336. this._workingVector.copyFrom(location);
  74337. }
  74338. // Add height to account for user's height offset
  74339. if (this.isInVRMode) {
  74340. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74341. }
  74342. else {
  74343. this._workingVector.y += this._defaultHeight;
  74344. }
  74345. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74346. // Create animation from the camera's position to the new location
  74347. this.currentVRCamera.animations = [];
  74348. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74349. var animationCameraTeleportationKeys = [{
  74350. frame: 0,
  74351. value: this.currentVRCamera.position
  74352. },
  74353. {
  74354. frame: 11,
  74355. value: this._workingVector
  74356. }
  74357. ];
  74358. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74359. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74360. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74361. this._postProcessMove.animations = [];
  74362. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74363. var vignetteWeightKeys = [];
  74364. vignetteWeightKeys.push({
  74365. frame: 0,
  74366. value: 0
  74367. });
  74368. vignetteWeightKeys.push({
  74369. frame: 5,
  74370. value: 8
  74371. });
  74372. vignetteWeightKeys.push({
  74373. frame: 11,
  74374. value: 0
  74375. });
  74376. animationPP.setKeys(vignetteWeightKeys);
  74377. this._postProcessMove.animations.push(animationPP);
  74378. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74379. var vignetteStretchKeys = [];
  74380. vignetteStretchKeys.push({
  74381. frame: 0,
  74382. value: 0
  74383. });
  74384. vignetteStretchKeys.push({
  74385. frame: 5,
  74386. value: 10
  74387. });
  74388. vignetteStretchKeys.push({
  74389. frame: 11,
  74390. value: 0
  74391. });
  74392. animationPP2.setKeys(vignetteStretchKeys);
  74393. this._postProcessMove.animations.push(animationPP2);
  74394. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74395. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74396. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74397. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74398. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74399. });
  74400. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74401. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74402. });
  74403. };
  74404. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74405. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74406. return;
  74407. }
  74408. var ray;
  74409. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74410. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74411. }
  74412. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74413. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74414. }
  74415. else {
  74416. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74417. }
  74418. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74419. // Moving the gazeTracker on the mesh face targetted
  74420. if (hit && hit.pickedPoint) {
  74421. if (this._displayGaze) {
  74422. var multiplier = 1;
  74423. this._gazeTracker.isVisible = true;
  74424. if (this._isActionableMesh) {
  74425. multiplier = 3;
  74426. }
  74427. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74428. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74429. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74430. var pickNormal = hit.getNormal();
  74431. // To avoid z-fighting
  74432. var deltaFighting = 0.002;
  74433. if (pickNormal) {
  74434. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74435. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74436. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74437. }
  74438. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74439. if (this._gazeTracker.position.x < 0) {
  74440. this._gazeTracker.position.x += deltaFighting;
  74441. }
  74442. else {
  74443. this._gazeTracker.position.x -= deltaFighting;
  74444. }
  74445. if (this._gazeTracker.position.y < 0) {
  74446. this._gazeTracker.position.y += deltaFighting;
  74447. }
  74448. else {
  74449. this._gazeTracker.position.y -= deltaFighting;
  74450. }
  74451. if (this._gazeTracker.position.z < 0) {
  74452. this._gazeTracker.position.z += deltaFighting;
  74453. }
  74454. else {
  74455. this._gazeTracker.position.z -= deltaFighting;
  74456. }
  74457. }
  74458. // Changing the size of the laser pointer based on the distance from the targetted point
  74459. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74460. this._rightLaserPointer.scaling.y = hit.distance;
  74461. this._rightLaserPointer.position.z = -hit.distance / 2;
  74462. }
  74463. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74464. this._leftLaserPointer.scaling.y = hit.distance;
  74465. this._leftLaserPointer.position.z = -hit.distance / 2;
  74466. }
  74467. }
  74468. else {
  74469. this._gazeTracker.isVisible = false;
  74470. }
  74471. if (hit && hit.pickedMesh) {
  74472. this._currentHit = hit;
  74473. if (this._pointerDownOnMeshAsked) {
  74474. this._scene.simulatePointerMove(this._currentHit);
  74475. }
  74476. // The object selected is the floor, we're in a teleportation scenario
  74477. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74478. // Moving the teleportation area to this targetted point
  74479. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74480. if (this._currentMeshSelected &&
  74481. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74482. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74483. }
  74484. this._currentMeshSelected = null;
  74485. this._moveTeleportationSelectorTo(hit);
  74486. return;
  74487. }
  74488. // If not, we're in a selection scenario
  74489. this._hideTeleportationTarget();
  74490. this._teleportationAllowed = false;
  74491. if (hit.pickedMesh !== this._currentMeshSelected) {
  74492. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74493. this.onNewMeshPicked.notifyObservers(hit);
  74494. this._currentMeshSelected = hit.pickedMesh;
  74495. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74496. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74497. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74498. this._isActionableMesh = true;
  74499. }
  74500. else {
  74501. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74502. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74503. this._isActionableMesh = false;
  74504. }
  74505. try {
  74506. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74507. }
  74508. catch (err) {
  74509. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74510. }
  74511. }
  74512. else {
  74513. if (this._currentMeshSelected) {
  74514. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74515. }
  74516. this._currentMeshSelected = null;
  74517. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74518. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74519. }
  74520. }
  74521. }
  74522. else {
  74523. this._currentHit = null;
  74524. this._currentMeshSelected = null;
  74525. this._teleportationAllowed = false;
  74526. this._hideTeleportationTarget();
  74527. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74528. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74529. }
  74530. };
  74531. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74532. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74533. this._leftLaserPointer.material.emissiveColor = color;
  74534. }
  74535. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74536. this._rightLaserPointer.material.emissiveColor = color;
  74537. }
  74538. };
  74539. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74540. if (this._gazeTracker.material) {
  74541. this._gazeTracker.material.emissiveColor = color;
  74542. }
  74543. };
  74544. VRExperienceHelper.prototype.dispose = function () {
  74545. if (this.isInVRMode) {
  74546. this.exitVR();
  74547. }
  74548. if (this._passProcessMove) {
  74549. this._passProcessMove.dispose();
  74550. }
  74551. if (this._postProcessMove) {
  74552. this._postProcessMove.dispose();
  74553. }
  74554. if (this._webVRCamera) {
  74555. this._webVRCamera.dispose();
  74556. }
  74557. if (this._vrDeviceOrientationCamera) {
  74558. this._vrDeviceOrientationCamera.dispose();
  74559. }
  74560. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74561. document.body.removeChild(this._btnVR);
  74562. }
  74563. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74564. this._deviceOrientationCamera.dispose();
  74565. }
  74566. if (this._gazeTracker) {
  74567. this._gazeTracker.dispose();
  74568. }
  74569. if (this._teleportationTarget) {
  74570. this._teleportationTarget.dispose();
  74571. }
  74572. this._floorMeshesCollection = [];
  74573. document.removeEventListener("keydown", this._onKeyDown);
  74574. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74575. window.removeEventListener("resize", this._onResize);
  74576. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74577. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74578. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74579. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74580. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74581. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74582. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74583. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74584. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74585. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74586. this._scene.unregisterBeforeRender(this.beforeRender);
  74587. };
  74588. VRExperienceHelper.prototype.getClassName = function () {
  74589. return "VRExperienceHelper";
  74590. };
  74591. return VRExperienceHelper;
  74592. }());
  74593. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74594. })(BABYLON || (BABYLON = {}));
  74595. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74596. // Mainly based on these 2 articles :
  74597. // 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
  74598. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74599. var BABYLON;
  74600. (function (BABYLON) {
  74601. var JoystickAxis;
  74602. (function (JoystickAxis) {
  74603. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74604. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74605. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74606. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74607. var VirtualJoystick = /** @class */ (function () {
  74608. function VirtualJoystick(leftJoystick) {
  74609. var _this = this;
  74610. if (leftJoystick) {
  74611. this._leftJoystick = true;
  74612. }
  74613. else {
  74614. this._leftJoystick = false;
  74615. }
  74616. VirtualJoystick._globalJoystickIndex++;
  74617. // By default left & right arrow keys are moving the X
  74618. // and up & down keys are moving the Y
  74619. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74620. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74621. this.reverseLeftRight = false;
  74622. this.reverseUpDown = false;
  74623. // collections of pointers
  74624. this._touches = new BABYLON.StringDictionary();
  74625. this.deltaPosition = BABYLON.Vector3.Zero();
  74626. this._joystickSensibility = 25;
  74627. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74628. this._onResize = function (evt) {
  74629. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74630. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74631. if (VirtualJoystick.vjCanvas) {
  74632. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74633. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74634. }
  74635. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74636. };
  74637. // injecting a canvas element on top of the canvas 3D game
  74638. if (!VirtualJoystick.vjCanvas) {
  74639. window.addEventListener("resize", this._onResize, false);
  74640. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74641. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74642. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74643. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74644. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74645. VirtualJoystick.vjCanvas.style.width = "100%";
  74646. VirtualJoystick.vjCanvas.style.height = "100%";
  74647. VirtualJoystick.vjCanvas.style.position = "absolute";
  74648. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74649. VirtualJoystick.vjCanvas.style.top = "0px";
  74650. VirtualJoystick.vjCanvas.style.left = "0px";
  74651. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74652. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74653. // Support for jQuery PEP polyfill
  74654. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74655. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74656. if (!context) {
  74657. throw new Error("Unable to create canvas for virtual joystick");
  74658. }
  74659. VirtualJoystick.vjCanvasContext = context;
  74660. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74661. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74662. document.body.appendChild(VirtualJoystick.vjCanvas);
  74663. }
  74664. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74665. this.pressed = false;
  74666. // default joystick color
  74667. this._joystickColor = "cyan";
  74668. this._joystickPointerID = -1;
  74669. // current joystick position
  74670. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74671. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74672. // origin joystick position
  74673. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74674. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74675. this._onPointerDownHandlerRef = function (evt) {
  74676. _this._onPointerDown(evt);
  74677. };
  74678. this._onPointerMoveHandlerRef = function (evt) {
  74679. _this._onPointerMove(evt);
  74680. };
  74681. this._onPointerUpHandlerRef = function (evt) {
  74682. _this._onPointerUp(evt);
  74683. };
  74684. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74685. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74686. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74687. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74688. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74689. evt.preventDefault(); // Disables system menu
  74690. }, false);
  74691. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74692. }
  74693. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74694. this._joystickSensibility = newJoystickSensibility;
  74695. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74696. };
  74697. VirtualJoystick.prototype._onPointerDown = function (e) {
  74698. var positionOnScreenCondition;
  74699. e.preventDefault();
  74700. if (this._leftJoystick === true) {
  74701. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74702. }
  74703. else {
  74704. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74705. }
  74706. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74707. // First contact will be dedicated to the virtual joystick
  74708. this._joystickPointerID = e.pointerId;
  74709. this._joystickPointerStartPos.x = e.clientX;
  74710. this._joystickPointerStartPos.y = e.clientY;
  74711. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74712. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74713. this._deltaJoystickVector.x = 0;
  74714. this._deltaJoystickVector.y = 0;
  74715. this.pressed = true;
  74716. this._touches.add(e.pointerId.toString(), e);
  74717. }
  74718. else {
  74719. // You can only trigger the action buttons with a joystick declared
  74720. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74721. this._action();
  74722. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74723. }
  74724. }
  74725. };
  74726. VirtualJoystick.prototype._onPointerMove = function (e) {
  74727. // If the current pointer is the one associated to the joystick (first touch contact)
  74728. if (this._joystickPointerID == e.pointerId) {
  74729. this._joystickPointerPos.x = e.clientX;
  74730. this._joystickPointerPos.y = e.clientY;
  74731. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74732. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74733. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74734. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74735. switch (this._axisTargetedByLeftAndRight) {
  74736. case JoystickAxis.X:
  74737. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74738. break;
  74739. case JoystickAxis.Y:
  74740. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74741. break;
  74742. case JoystickAxis.Z:
  74743. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74744. break;
  74745. }
  74746. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74747. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74748. switch (this._axisTargetedByUpAndDown) {
  74749. case JoystickAxis.X:
  74750. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74751. break;
  74752. case JoystickAxis.Y:
  74753. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74754. break;
  74755. case JoystickAxis.Z:
  74756. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74757. break;
  74758. }
  74759. }
  74760. else {
  74761. var data = this._touches.get(e.pointerId.toString());
  74762. if (data) {
  74763. data.x = e.clientX;
  74764. data.y = e.clientY;
  74765. }
  74766. }
  74767. };
  74768. VirtualJoystick.prototype._onPointerUp = function (e) {
  74769. if (this._joystickPointerID == e.pointerId) {
  74770. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74771. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74772. this._joystickPointerID = -1;
  74773. this.pressed = false;
  74774. }
  74775. else {
  74776. var touch = this._touches.get(e.pointerId.toString());
  74777. if (touch) {
  74778. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74779. }
  74780. }
  74781. this._deltaJoystickVector.x = 0;
  74782. this._deltaJoystickVector.y = 0;
  74783. this._touches.remove(e.pointerId.toString());
  74784. };
  74785. /**
  74786. * Change the color of the virtual joystick
  74787. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74788. */
  74789. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74790. this._joystickColor = newColor;
  74791. };
  74792. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74793. this._action = action;
  74794. };
  74795. // Define which axis you'd like to control for left & right
  74796. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74797. switch (axis) {
  74798. case JoystickAxis.X:
  74799. case JoystickAxis.Y:
  74800. case JoystickAxis.Z:
  74801. this._axisTargetedByLeftAndRight = axis;
  74802. break;
  74803. default:
  74804. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74805. break;
  74806. }
  74807. };
  74808. // Define which axis you'd like to control for up & down
  74809. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74810. switch (axis) {
  74811. case JoystickAxis.X:
  74812. case JoystickAxis.Y:
  74813. case JoystickAxis.Z:
  74814. this._axisTargetedByUpAndDown = axis;
  74815. break;
  74816. default:
  74817. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74818. break;
  74819. }
  74820. };
  74821. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74822. var _this = this;
  74823. if (this.pressed) {
  74824. this._touches.forEach(function (key, touch) {
  74825. if (touch.pointerId === _this._joystickPointerID) {
  74826. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74827. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74828. VirtualJoystick.vjCanvasContext.beginPath();
  74829. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74830. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74831. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74832. VirtualJoystick.vjCanvasContext.stroke();
  74833. VirtualJoystick.vjCanvasContext.closePath();
  74834. VirtualJoystick.vjCanvasContext.beginPath();
  74835. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74836. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74837. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74838. VirtualJoystick.vjCanvasContext.stroke();
  74839. VirtualJoystick.vjCanvasContext.closePath();
  74840. VirtualJoystick.vjCanvasContext.beginPath();
  74841. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74842. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74843. VirtualJoystick.vjCanvasContext.stroke();
  74844. VirtualJoystick.vjCanvasContext.closePath();
  74845. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74846. }
  74847. else {
  74848. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74849. VirtualJoystick.vjCanvasContext.beginPath();
  74850. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74851. VirtualJoystick.vjCanvasContext.beginPath();
  74852. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74853. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74854. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74855. VirtualJoystick.vjCanvasContext.stroke();
  74856. VirtualJoystick.vjCanvasContext.closePath();
  74857. touch.prevX = touch.x;
  74858. touch.prevY = touch.y;
  74859. }
  74860. ;
  74861. });
  74862. }
  74863. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74864. };
  74865. VirtualJoystick.prototype.releaseCanvas = function () {
  74866. if (VirtualJoystick.vjCanvas) {
  74867. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74868. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74869. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74870. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74871. window.removeEventListener("resize", this._onResize);
  74872. document.body.removeChild(VirtualJoystick.vjCanvas);
  74873. VirtualJoystick.vjCanvas = null;
  74874. }
  74875. };
  74876. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74877. VirtualJoystick._globalJoystickIndex = 0;
  74878. return VirtualJoystick;
  74879. }());
  74880. BABYLON.VirtualJoystick = VirtualJoystick;
  74881. })(BABYLON || (BABYLON = {}));
  74882. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74883. var BABYLON;
  74884. (function (BABYLON) {
  74885. // We're mainly based on the logic defined into the FreeCamera code
  74886. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74887. __extends(VirtualJoysticksCamera, _super);
  74888. function VirtualJoysticksCamera(name, position, scene) {
  74889. var _this = _super.call(this, name, position, scene) || this;
  74890. _this.inputs.addVirtualJoystick();
  74891. return _this;
  74892. }
  74893. VirtualJoysticksCamera.prototype.getClassName = function () {
  74894. return "VirtualJoysticksCamera";
  74895. };
  74896. return VirtualJoysticksCamera;
  74897. }(BABYLON.FreeCamera));
  74898. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74899. })(BABYLON || (BABYLON = {}));
  74900. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74901. var BABYLON;
  74902. (function (BABYLON) {
  74903. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74904. function FreeCameraVirtualJoystickInput() {
  74905. }
  74906. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74907. return this._leftjoystick;
  74908. };
  74909. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74910. return this._rightjoystick;
  74911. };
  74912. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74913. if (this._leftjoystick) {
  74914. var camera = this.camera;
  74915. var speed = camera._computeLocalCameraSpeed() * 50;
  74916. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74917. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74918. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74919. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74920. if (!this._leftjoystick.pressed) {
  74921. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74922. }
  74923. if (!this._rightjoystick.pressed) {
  74924. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74925. }
  74926. }
  74927. };
  74928. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74929. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74930. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74931. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74932. this._leftjoystick.setJoystickSensibility(0.15);
  74933. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74934. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74935. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74936. this._rightjoystick.reverseUpDown = true;
  74937. this._rightjoystick.setJoystickSensibility(0.05);
  74938. this._rightjoystick.setJoystickColor("yellow");
  74939. };
  74940. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74941. this._leftjoystick.releaseCanvas();
  74942. this._rightjoystick.releaseCanvas();
  74943. };
  74944. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74945. return "FreeCameraVirtualJoystickInput";
  74946. };
  74947. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74948. return "virtualJoystick";
  74949. };
  74950. return FreeCameraVirtualJoystickInput;
  74951. }());
  74952. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74953. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74954. })(BABYLON || (BABYLON = {}));
  74955. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74956. var BABYLON;
  74957. (function (BABYLON) {
  74958. var SimplificationSettings = /** @class */ (function () {
  74959. function SimplificationSettings(quality, distance, optimizeMesh) {
  74960. this.quality = quality;
  74961. this.distance = distance;
  74962. this.optimizeMesh = optimizeMesh;
  74963. }
  74964. return SimplificationSettings;
  74965. }());
  74966. BABYLON.SimplificationSettings = SimplificationSettings;
  74967. var SimplificationQueue = /** @class */ (function () {
  74968. function SimplificationQueue() {
  74969. this.running = false;
  74970. this._simplificationArray = [];
  74971. }
  74972. SimplificationQueue.prototype.addTask = function (task) {
  74973. this._simplificationArray.push(task);
  74974. };
  74975. SimplificationQueue.prototype.executeNext = function () {
  74976. var task = this._simplificationArray.pop();
  74977. if (task) {
  74978. this.running = true;
  74979. this.runSimplification(task);
  74980. }
  74981. else {
  74982. this.running = false;
  74983. }
  74984. };
  74985. SimplificationQueue.prototype.runSimplification = function (task) {
  74986. var _this = this;
  74987. if (task.parallelProcessing) {
  74988. //parallel simplifier
  74989. task.settings.forEach(function (setting) {
  74990. var simplifier = _this.getSimplifier(task);
  74991. simplifier.simplify(setting, function (newMesh) {
  74992. task.mesh.addLODLevel(setting.distance, newMesh);
  74993. newMesh.isVisible = true;
  74994. //check if it is the last
  74995. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74996. //all done, run the success callback.
  74997. task.successCallback();
  74998. }
  74999. _this.executeNext();
  75000. });
  75001. });
  75002. }
  75003. else {
  75004. //single simplifier.
  75005. var simplifier = this.getSimplifier(task);
  75006. var runDecimation = function (setting, callback) {
  75007. simplifier.simplify(setting, function (newMesh) {
  75008. task.mesh.addLODLevel(setting.distance, newMesh);
  75009. newMesh.isVisible = true;
  75010. //run the next quality level
  75011. callback();
  75012. });
  75013. };
  75014. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  75015. runDecimation(task.settings[loop.index], function () {
  75016. loop.executeNext();
  75017. });
  75018. }, function () {
  75019. //execution ended, run the success callback.
  75020. if (task.successCallback) {
  75021. task.successCallback();
  75022. }
  75023. _this.executeNext();
  75024. });
  75025. }
  75026. };
  75027. SimplificationQueue.prototype.getSimplifier = function (task) {
  75028. switch (task.simplificationType) {
  75029. case SimplificationType.QUADRATIC:
  75030. default:
  75031. return new QuadraticErrorSimplification(task.mesh);
  75032. }
  75033. };
  75034. return SimplificationQueue;
  75035. }());
  75036. BABYLON.SimplificationQueue = SimplificationQueue;
  75037. /**
  75038. * The implemented types of simplification.
  75039. * At the moment only Quadratic Error Decimation is implemented.
  75040. */
  75041. var SimplificationType;
  75042. (function (SimplificationType) {
  75043. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  75044. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  75045. var DecimationTriangle = /** @class */ (function () {
  75046. function DecimationTriangle(vertices) {
  75047. this.vertices = vertices;
  75048. this.error = new Array(4);
  75049. this.deleted = false;
  75050. this.isDirty = false;
  75051. this.deletePending = false;
  75052. this.borderFactor = 0;
  75053. }
  75054. return DecimationTriangle;
  75055. }());
  75056. BABYLON.DecimationTriangle = DecimationTriangle;
  75057. var DecimationVertex = /** @class */ (function () {
  75058. function DecimationVertex(position, id) {
  75059. this.position = position;
  75060. this.id = id;
  75061. this.isBorder = true;
  75062. this.q = new QuadraticMatrix();
  75063. this.triangleCount = 0;
  75064. this.triangleStart = 0;
  75065. this.originalOffsets = [];
  75066. }
  75067. DecimationVertex.prototype.updatePosition = function (newPosition) {
  75068. this.position.copyFrom(newPosition);
  75069. };
  75070. return DecimationVertex;
  75071. }());
  75072. BABYLON.DecimationVertex = DecimationVertex;
  75073. var QuadraticMatrix = /** @class */ (function () {
  75074. function QuadraticMatrix(data) {
  75075. this.data = new Array(10);
  75076. for (var i = 0; i < 10; ++i) {
  75077. if (data && data[i]) {
  75078. this.data[i] = data[i];
  75079. }
  75080. else {
  75081. this.data[i] = 0;
  75082. }
  75083. }
  75084. }
  75085. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  75086. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  75087. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  75088. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  75089. return det;
  75090. };
  75091. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  75092. for (var i = 0; i < 10; ++i) {
  75093. this.data[i] += matrix.data[i];
  75094. }
  75095. };
  75096. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  75097. for (var i = 0; i < 10; ++i) {
  75098. this.data[i] += data[i];
  75099. }
  75100. };
  75101. QuadraticMatrix.prototype.add = function (matrix) {
  75102. var m = new QuadraticMatrix();
  75103. for (var i = 0; i < 10; ++i) {
  75104. m.data[i] = this.data[i] + matrix.data[i];
  75105. }
  75106. return m;
  75107. };
  75108. QuadraticMatrix.FromData = function (a, b, c, d) {
  75109. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  75110. };
  75111. //returning an array to avoid garbage collection
  75112. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  75113. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  75114. };
  75115. return QuadraticMatrix;
  75116. }());
  75117. BABYLON.QuadraticMatrix = QuadraticMatrix;
  75118. var Reference = /** @class */ (function () {
  75119. function Reference(vertexId, triangleId) {
  75120. this.vertexId = vertexId;
  75121. this.triangleId = triangleId;
  75122. }
  75123. return Reference;
  75124. }());
  75125. BABYLON.Reference = Reference;
  75126. /**
  75127. * An implementation of the Quadratic Error simplification algorithm.
  75128. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  75129. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  75130. * @author RaananW
  75131. */
  75132. var QuadraticErrorSimplification = /** @class */ (function () {
  75133. function QuadraticErrorSimplification(_mesh) {
  75134. this._mesh = _mesh;
  75135. this.syncIterations = 5000;
  75136. this.aggressiveness = 7;
  75137. this.decimationIterations = 100;
  75138. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75139. }
  75140. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75141. var _this = this;
  75142. this.initDecimatedMesh();
  75143. //iterating through the submeshes array, one after the other.
  75144. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75145. _this.initWithMesh(loop.index, function () {
  75146. _this.runDecimation(settings, loop.index, function () {
  75147. loop.executeNext();
  75148. });
  75149. }, settings.optimizeMesh);
  75150. }, function () {
  75151. setTimeout(function () {
  75152. successCallback(_this._reconstructedMesh);
  75153. }, 0);
  75154. });
  75155. };
  75156. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75157. var _this = this;
  75158. var targetCount = ~~(this.triangles.length * settings.quality);
  75159. var deletedTriangles = 0;
  75160. var triangleCount = this.triangles.length;
  75161. var iterationFunction = function (iteration, callback) {
  75162. setTimeout(function () {
  75163. if (iteration % 5 === 0) {
  75164. _this.updateMesh(iteration === 0);
  75165. }
  75166. for (var i = 0; i < _this.triangles.length; ++i) {
  75167. _this.triangles[i].isDirty = false;
  75168. }
  75169. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75170. var trianglesIterator = function (i) {
  75171. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75172. var t = _this.triangles[tIdx];
  75173. if (!t)
  75174. return;
  75175. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75176. return;
  75177. }
  75178. for (var j = 0; j < 3; ++j) {
  75179. if (t.error[j] < threshold) {
  75180. var deleted0 = [];
  75181. var deleted1 = [];
  75182. var v0 = t.vertices[j];
  75183. var v1 = t.vertices[(j + 1) % 3];
  75184. if (v0.isBorder || v1.isBorder)
  75185. continue;
  75186. var p = BABYLON.Vector3.Zero();
  75187. var n = BABYLON.Vector3.Zero();
  75188. var uv = BABYLON.Vector2.Zero();
  75189. var color = new BABYLON.Color4(0, 0, 0, 1);
  75190. _this.calculateError(v0, v1, p, n, uv, color);
  75191. var delTr = new Array();
  75192. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75193. continue;
  75194. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75195. continue;
  75196. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75197. continue;
  75198. var uniqueArray = new Array();
  75199. delTr.forEach(function (deletedT) {
  75200. if (uniqueArray.indexOf(deletedT) === -1) {
  75201. deletedT.deletePending = true;
  75202. uniqueArray.push(deletedT);
  75203. }
  75204. });
  75205. if (uniqueArray.length % 2 !== 0) {
  75206. continue;
  75207. }
  75208. v0.q = v1.q.add(v0.q);
  75209. v0.updatePosition(p);
  75210. var tStart = _this.references.length;
  75211. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75212. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75213. var tCount = _this.references.length - tStart;
  75214. if (tCount <= v0.triangleCount) {
  75215. if (tCount) {
  75216. for (var c = 0; c < tCount; c++) {
  75217. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75218. }
  75219. }
  75220. }
  75221. else {
  75222. v0.triangleStart = tStart;
  75223. }
  75224. v0.triangleCount = tCount;
  75225. break;
  75226. }
  75227. }
  75228. };
  75229. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75230. }, 0);
  75231. };
  75232. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75233. if (triangleCount - deletedTriangles <= targetCount)
  75234. loop.breakLoop();
  75235. else {
  75236. iterationFunction(loop.index, function () {
  75237. loop.executeNext();
  75238. });
  75239. }
  75240. }, function () {
  75241. setTimeout(function () {
  75242. //reconstruct this part of the mesh
  75243. _this.reconstructMesh(submeshIndex);
  75244. successCallback();
  75245. }, 0);
  75246. });
  75247. };
  75248. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75249. var _this = this;
  75250. this.vertices = [];
  75251. this.triangles = [];
  75252. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75253. var indices = this._mesh.getIndices();
  75254. var submesh = this._mesh.subMeshes[submeshIndex];
  75255. var findInVertices = function (positionToSearch) {
  75256. if (optimizeMesh) {
  75257. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75258. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75259. return _this.vertices[ii];
  75260. }
  75261. }
  75262. }
  75263. return null;
  75264. };
  75265. var vertexReferences = [];
  75266. var vertexInit = function (i) {
  75267. if (!positionData) {
  75268. return;
  75269. }
  75270. var offset = i + submesh.verticesStart;
  75271. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75272. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75273. vertex.originalOffsets.push(offset);
  75274. if (vertex.id === _this.vertices.length) {
  75275. _this.vertices.push(vertex);
  75276. }
  75277. vertexReferences.push(vertex.id);
  75278. };
  75279. //var totalVertices = mesh.getTotalVertices();
  75280. var totalVertices = submesh.verticesCount;
  75281. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75282. var indicesInit = function (i) {
  75283. if (!indices) {
  75284. return;
  75285. }
  75286. var offset = (submesh.indexStart / 3) + i;
  75287. var pos = (offset * 3);
  75288. var i0 = indices[pos + 0];
  75289. var i1 = indices[pos + 1];
  75290. var i2 = indices[pos + 2];
  75291. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75292. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75293. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75294. var triangle = new DecimationTriangle([v0, v1, v2]);
  75295. triangle.originalOffset = pos;
  75296. _this.triangles.push(triangle);
  75297. };
  75298. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75299. _this.init(callback);
  75300. });
  75301. });
  75302. };
  75303. QuadraticErrorSimplification.prototype.init = function (callback) {
  75304. var _this = this;
  75305. var triangleInit1 = function (i) {
  75306. var t = _this.triangles[i];
  75307. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75308. for (var j = 0; j < 3; j++) {
  75309. 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))));
  75310. }
  75311. };
  75312. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75313. var triangleInit2 = function (i) {
  75314. var t = _this.triangles[i];
  75315. for (var j = 0; j < 3; ++j) {
  75316. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75317. }
  75318. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75319. };
  75320. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75321. callback();
  75322. });
  75323. });
  75324. };
  75325. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75326. var newTriangles = [];
  75327. var i;
  75328. for (i = 0; i < this.vertices.length; ++i) {
  75329. this.vertices[i].triangleCount = 0;
  75330. }
  75331. var t;
  75332. var j;
  75333. for (i = 0; i < this.triangles.length; ++i) {
  75334. if (!this.triangles[i].deleted) {
  75335. t = this.triangles[i];
  75336. for (j = 0; j < 3; ++j) {
  75337. t.vertices[j].triangleCount = 1;
  75338. }
  75339. newTriangles.push(t);
  75340. }
  75341. }
  75342. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75343. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75344. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75345. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75346. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75347. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75348. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75349. var vertexCount = 0;
  75350. for (i = 0; i < this.vertices.length; ++i) {
  75351. var vertex = this.vertices[i];
  75352. vertex.id = vertexCount;
  75353. if (vertex.triangleCount) {
  75354. vertex.originalOffsets.forEach(function (originalOffset) {
  75355. if (!normalData) {
  75356. return;
  75357. }
  75358. newPositionData.push(vertex.position.x);
  75359. newPositionData.push(vertex.position.y);
  75360. newPositionData.push(vertex.position.z);
  75361. newNormalData.push(normalData[originalOffset * 3]);
  75362. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75363. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75364. if (uvs && uvs.length) {
  75365. newUVsData.push(uvs[(originalOffset * 2)]);
  75366. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75367. }
  75368. else if (colorsData && colorsData.length) {
  75369. newColorsData.push(colorsData[(originalOffset * 4)]);
  75370. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75371. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75372. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75373. }
  75374. ++vertexCount;
  75375. });
  75376. }
  75377. }
  75378. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75379. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75380. var submeshesArray = this._reconstructedMesh.subMeshes;
  75381. this._reconstructedMesh.subMeshes = [];
  75382. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75383. var originalIndices = this._mesh.getIndices();
  75384. for (i = 0; i < newTriangles.length; ++i) {
  75385. t = newTriangles[i]; //now get the new referencing point for each vertex
  75386. [0, 1, 2].forEach(function (idx) {
  75387. var id = originalIndices[t.originalOffset + idx];
  75388. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75389. if (offset < 0)
  75390. offset = 0;
  75391. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75392. });
  75393. }
  75394. //overwriting the old vertex buffers and indices.
  75395. this._reconstructedMesh.setIndices(newIndicesArray);
  75396. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75397. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75398. if (newUVsData.length > 0)
  75399. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75400. if (newColorsData.length > 0)
  75401. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75402. //create submesh
  75403. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75404. if (submeshIndex > 0) {
  75405. this._reconstructedMesh.subMeshes = [];
  75406. submeshesArray.forEach(function (submesh) {
  75407. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75408. });
  75409. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75410. }
  75411. };
  75412. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75413. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75414. this._reconstructedMesh.material = this._mesh.material;
  75415. this._reconstructedMesh.parent = this._mesh.parent;
  75416. this._reconstructedMesh.isVisible = false;
  75417. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75418. };
  75419. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75420. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75421. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75422. if (t.deleted)
  75423. continue;
  75424. var s = this.references[vertex1.triangleStart + i].vertexId;
  75425. var v1 = t.vertices[(s + 1) % 3];
  75426. var v2 = t.vertices[(s + 2) % 3];
  75427. if ((v1 === vertex2 || v2 === vertex2)) {
  75428. deletedArray[i] = true;
  75429. delTr.push(t);
  75430. continue;
  75431. }
  75432. var d1 = v1.position.subtract(point);
  75433. d1 = d1.normalize();
  75434. var d2 = v2.position.subtract(point);
  75435. d2 = d2.normalize();
  75436. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75437. return true;
  75438. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75439. deletedArray[i] = false;
  75440. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75441. return true;
  75442. }
  75443. return false;
  75444. };
  75445. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75446. var newDeleted = deletedTriangles;
  75447. for (var i = 0; i < vertex.triangleCount; ++i) {
  75448. var ref = this.references[vertex.triangleStart + i];
  75449. var t = this.triangles[ref.triangleId];
  75450. if (t.deleted)
  75451. continue;
  75452. if (deletedArray[i] && t.deletePending) {
  75453. t.deleted = true;
  75454. newDeleted++;
  75455. continue;
  75456. }
  75457. t.vertices[ref.vertexId] = origVertex;
  75458. t.isDirty = true;
  75459. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75460. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75461. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75462. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75463. this.references.push(ref);
  75464. }
  75465. return newDeleted;
  75466. };
  75467. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75468. for (var i = 0; i < this.vertices.length; ++i) {
  75469. var vCount = [];
  75470. var vId = [];
  75471. var v = this.vertices[i];
  75472. var j;
  75473. for (j = 0; j < v.triangleCount; ++j) {
  75474. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75475. for (var ii = 0; ii < 3; ii++) {
  75476. var ofs = 0;
  75477. var vv = triangle.vertices[ii];
  75478. while (ofs < vCount.length) {
  75479. if (vId[ofs] === vv.id)
  75480. break;
  75481. ++ofs;
  75482. }
  75483. if (ofs === vCount.length) {
  75484. vCount.push(1);
  75485. vId.push(vv.id);
  75486. }
  75487. else {
  75488. vCount[ofs]++;
  75489. }
  75490. }
  75491. }
  75492. for (j = 0; j < vCount.length; ++j) {
  75493. if (vCount[j] === 1) {
  75494. this.vertices[vId[j]].isBorder = true;
  75495. }
  75496. else {
  75497. this.vertices[vId[j]].isBorder = false;
  75498. }
  75499. }
  75500. }
  75501. };
  75502. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75503. if (identifyBorders === void 0) { identifyBorders = false; }
  75504. var i;
  75505. if (!identifyBorders) {
  75506. var newTrianglesVector = [];
  75507. for (i = 0; i < this.triangles.length; ++i) {
  75508. if (!this.triangles[i].deleted) {
  75509. newTrianglesVector.push(this.triangles[i]);
  75510. }
  75511. }
  75512. this.triangles = newTrianglesVector;
  75513. }
  75514. for (i = 0; i < this.vertices.length; ++i) {
  75515. this.vertices[i].triangleCount = 0;
  75516. this.vertices[i].triangleStart = 0;
  75517. }
  75518. var t;
  75519. var j;
  75520. var v;
  75521. for (i = 0; i < this.triangles.length; ++i) {
  75522. t = this.triangles[i];
  75523. for (j = 0; j < 3; ++j) {
  75524. v = t.vertices[j];
  75525. v.triangleCount++;
  75526. }
  75527. }
  75528. var tStart = 0;
  75529. for (i = 0; i < this.vertices.length; ++i) {
  75530. this.vertices[i].triangleStart = tStart;
  75531. tStart += this.vertices[i].triangleCount;
  75532. this.vertices[i].triangleCount = 0;
  75533. }
  75534. var newReferences = new Array(this.triangles.length * 3);
  75535. for (i = 0; i < this.triangles.length; ++i) {
  75536. t = this.triangles[i];
  75537. for (j = 0; j < 3; ++j) {
  75538. v = t.vertices[j];
  75539. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75540. v.triangleCount++;
  75541. }
  75542. }
  75543. this.references = newReferences;
  75544. if (identifyBorders) {
  75545. this.identifyBorder();
  75546. }
  75547. };
  75548. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75549. var x = point.x;
  75550. var y = point.y;
  75551. var z = point.z;
  75552. 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
  75553. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75554. };
  75555. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75556. var q = vertex1.q.add(vertex2.q);
  75557. var border = vertex1.isBorder && vertex2.isBorder;
  75558. var error = 0;
  75559. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75560. if (qDet !== 0 && !border) {
  75561. if (!pointResult) {
  75562. pointResult = BABYLON.Vector3.Zero();
  75563. }
  75564. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75565. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75566. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75567. error = this.vertexError(q, pointResult);
  75568. }
  75569. else {
  75570. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75571. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75572. var error1 = this.vertexError(q, vertex1.position);
  75573. var error2 = this.vertexError(q, vertex2.position);
  75574. var error3 = this.vertexError(q, p3);
  75575. error = Math.min(error1, error2, error3);
  75576. if (error === error1) {
  75577. if (pointResult) {
  75578. pointResult.copyFrom(vertex1.position);
  75579. }
  75580. }
  75581. else if (error === error2) {
  75582. if (pointResult) {
  75583. pointResult.copyFrom(vertex2.position);
  75584. }
  75585. }
  75586. else {
  75587. if (pointResult) {
  75588. pointResult.copyFrom(p3);
  75589. }
  75590. }
  75591. }
  75592. return error;
  75593. };
  75594. return QuadraticErrorSimplification;
  75595. }());
  75596. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75597. })(BABYLON || (BABYLON = {}));
  75598. //# sourceMappingURL=babylon.meshSimplification.js.map
  75599. var BABYLON;
  75600. (function (BABYLON) {
  75601. var MeshLODLevel = /** @class */ (function () {
  75602. function MeshLODLevel(distance, mesh) {
  75603. this.distance = distance;
  75604. this.mesh = mesh;
  75605. }
  75606. return MeshLODLevel;
  75607. }());
  75608. BABYLON.MeshLODLevel = MeshLODLevel;
  75609. })(BABYLON || (BABYLON = {}));
  75610. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75611. var BABYLON;
  75612. (function (BABYLON) {
  75613. /**
  75614. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75615. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75616. */
  75617. var SceneOptimization = /** @class */ (function () {
  75618. /**
  75619. * Creates the SceneOptimization object
  75620. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75621. * @param desc defines the description associated with the optimization
  75622. */
  75623. function SceneOptimization(priority) {
  75624. if (priority === void 0) { priority = 0; }
  75625. this.priority = priority;
  75626. }
  75627. /**
  75628. * Gets a string describing the action executed by the current optimization
  75629. */
  75630. SceneOptimization.prototype.getDescription = function () {
  75631. return "";
  75632. };
  75633. /**
  75634. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75635. * @param scene defines the current scene where to apply this optimization
  75636. * @returnstrue if everything that can be done was applied
  75637. */
  75638. SceneOptimization.prototype.apply = function (scene) {
  75639. return true;
  75640. };
  75641. ;
  75642. return SceneOptimization;
  75643. }());
  75644. BABYLON.SceneOptimization = SceneOptimization;
  75645. /**
  75646. * Defines an optimization used to reduce the size of render target textures
  75647. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75648. */
  75649. var TextureOptimization = /** @class */ (function (_super) {
  75650. __extends(TextureOptimization, _super);
  75651. /**
  75652. * Creates the TextureOptimization object
  75653. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75654. * @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
  75655. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75656. */
  75657. function TextureOptimization(priority, maximumSize, step) {
  75658. if (priority === void 0) { priority = 0; }
  75659. if (maximumSize === void 0) { maximumSize = 1024; }
  75660. if (step === void 0) { step = 0.5; }
  75661. var _this = _super.call(this, priority) || this;
  75662. _this.priority = priority;
  75663. _this.maximumSize = maximumSize;
  75664. _this.step = step;
  75665. return _this;
  75666. }
  75667. /**
  75668. * Gets a string describing the action executed by the current optimization
  75669. */
  75670. TextureOptimization.prototype.getDescription = function () {
  75671. return "Reducing render target texture size to " + this.maximumSize;
  75672. };
  75673. /**
  75674. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75675. * @param scene defines the current scene where to apply this optimization
  75676. */
  75677. TextureOptimization.prototype.apply = function (scene) {
  75678. var allDone = true;
  75679. for (var index = 0; index < scene.textures.length; index++) {
  75680. var texture = scene.textures[index];
  75681. if (!texture.canRescale || texture.getContext) {
  75682. continue;
  75683. }
  75684. var currentSize = texture.getSize();
  75685. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75686. if (maxDimension > this.maximumSize) {
  75687. texture.scale(this.step);
  75688. allDone = false;
  75689. }
  75690. }
  75691. return allDone;
  75692. };
  75693. return TextureOptimization;
  75694. }(SceneOptimization));
  75695. BABYLON.TextureOptimization = TextureOptimization;
  75696. /**
  75697. * Defines an optimization used to increase or decrease the rendering resolution
  75698. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75699. */
  75700. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75701. __extends(HardwareScalingOptimization, _super);
  75702. /**
  75703. * Creates the HardwareScalingOptimization object
  75704. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75705. * @param maximumScale
  75706. * @param step
  75707. */
  75708. function HardwareScalingOptimization(priority, maximumScale, step) {
  75709. if (priority === void 0) { priority = 0; }
  75710. if (maximumScale === void 0) { maximumScale = 2; }
  75711. if (step === void 0) { step = 0.25; }
  75712. var _this = _super.call(this, priority) || this;
  75713. _this.priority = priority;
  75714. _this.maximumScale = maximumScale;
  75715. _this.step = step;
  75716. _this._currentScale = -1;
  75717. _this._directionOffset = 1;
  75718. return _this;
  75719. }
  75720. /**
  75721. * Gets a string describing the action executed by the current optimization
  75722. */
  75723. HardwareScalingOptimization.prototype.getDescription = function () {
  75724. return "Setting hardware scaling level to " + this._currentScale;
  75725. };
  75726. /**
  75727. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75728. * @param scene defines the current scene where to apply this optimization
  75729. */
  75730. HardwareScalingOptimization.prototype.apply = function (scene) {
  75731. if (this._currentScale === -1) {
  75732. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75733. if (this._currentScale > this.maximumScale) {
  75734. this._directionOffset = -1;
  75735. }
  75736. }
  75737. this._currentScale += this._directionOffset * this.step;
  75738. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75739. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75740. };
  75741. ;
  75742. return HardwareScalingOptimization;
  75743. }(SceneOptimization));
  75744. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75745. /**
  75746. * Defines an optimization used to remove shadows
  75747. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75748. */
  75749. var ShadowsOptimization = /** @class */ (function (_super) {
  75750. __extends(ShadowsOptimization, _super);
  75751. function ShadowsOptimization() {
  75752. return _super !== null && _super.apply(this, arguments) || this;
  75753. }
  75754. /**
  75755. * Gets a string describing the action executed by the current optimization
  75756. */
  75757. ShadowsOptimization.prototype.getDescription = function () {
  75758. return "Turning shadows off";
  75759. };
  75760. /**
  75761. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75762. * @param scene defines the current scene where to apply this optimization
  75763. */
  75764. ShadowsOptimization.prototype.apply = function (scene) {
  75765. scene.shadowsEnabled = false;
  75766. return true;
  75767. };
  75768. ;
  75769. return ShadowsOptimization;
  75770. }(SceneOptimization));
  75771. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75772. /**
  75773. * Defines an optimization used to turn post-processes off
  75774. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75775. */
  75776. var PostProcessesOptimization = /** @class */ (function (_super) {
  75777. __extends(PostProcessesOptimization, _super);
  75778. function PostProcessesOptimization() {
  75779. return _super !== null && _super.apply(this, arguments) || this;
  75780. }
  75781. /**
  75782. * Gets a string describing the action executed by the current optimization
  75783. */
  75784. PostProcessesOptimization.prototype.getDescription = function () {
  75785. return "Turning post-processes off";
  75786. };
  75787. /**
  75788. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75789. * @param scene defines the current scene where to apply this optimization
  75790. */
  75791. PostProcessesOptimization.prototype.apply = function (scene) {
  75792. scene.postProcessesEnabled = false;
  75793. return true;
  75794. };
  75795. ;
  75796. return PostProcessesOptimization;
  75797. }(SceneOptimization));
  75798. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75799. /**
  75800. * Defines an optimization used to turn lens flares off
  75801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75802. */
  75803. var LensFlaresOptimization = /** @class */ (function (_super) {
  75804. __extends(LensFlaresOptimization, _super);
  75805. function LensFlaresOptimization() {
  75806. return _super !== null && _super.apply(this, arguments) || this;
  75807. }
  75808. /**
  75809. * Gets a string describing the action executed by the current optimization
  75810. */
  75811. LensFlaresOptimization.prototype.getDescription = function () {
  75812. return "Turning lens flares off";
  75813. };
  75814. /**
  75815. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75816. * @param scene defines the current scene where to apply this optimization
  75817. */
  75818. LensFlaresOptimization.prototype.apply = function (scene) {
  75819. scene.lensFlaresEnabled = false;
  75820. return true;
  75821. };
  75822. ;
  75823. return LensFlaresOptimization;
  75824. }(SceneOptimization));
  75825. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75826. /**
  75827. * Defines an optimization based on user defined callback.
  75828. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75829. */
  75830. var CustomOptimization = /** @class */ (function (_super) {
  75831. __extends(CustomOptimization, _super);
  75832. function CustomOptimization() {
  75833. return _super !== null && _super.apply(this, arguments) || this;
  75834. }
  75835. /**
  75836. * Gets a string describing the action executed by the current optimization
  75837. */
  75838. CustomOptimization.prototype.getDescription = function () {
  75839. if (this.onGetDescription) {
  75840. return this.onGetDescription();
  75841. }
  75842. return "Running user defined callback";
  75843. };
  75844. /**
  75845. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75846. * @param scene defines the current scene where to apply this optimization
  75847. */
  75848. CustomOptimization.prototype.apply = function (scene) {
  75849. if (this.onApply) {
  75850. return this.onApply(scene);
  75851. }
  75852. return true;
  75853. };
  75854. ;
  75855. return CustomOptimization;
  75856. }(SceneOptimization));
  75857. BABYLON.CustomOptimization = CustomOptimization;
  75858. /**
  75859. * Defines an optimization used to turn particles off
  75860. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75861. */
  75862. var ParticlesOptimization = /** @class */ (function (_super) {
  75863. __extends(ParticlesOptimization, _super);
  75864. function ParticlesOptimization() {
  75865. return _super !== null && _super.apply(this, arguments) || this;
  75866. }
  75867. /**
  75868. * Gets a string describing the action executed by the current optimization
  75869. */
  75870. ParticlesOptimization.prototype.getDescription = function () {
  75871. return "Turning particles off";
  75872. };
  75873. /**
  75874. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75875. * @param scene defines the current scene where to apply this optimization
  75876. */
  75877. ParticlesOptimization.prototype.apply = function (scene) {
  75878. scene.particlesEnabled = false;
  75879. return true;
  75880. };
  75881. ;
  75882. return ParticlesOptimization;
  75883. }(SceneOptimization));
  75884. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75885. /**
  75886. * Defines an optimization used to turn render targets off
  75887. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75888. */
  75889. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75890. __extends(RenderTargetsOptimization, _super);
  75891. function RenderTargetsOptimization() {
  75892. return _super !== null && _super.apply(this, arguments) || this;
  75893. }
  75894. /**
  75895. * Gets a string describing the action executed by the current optimization
  75896. */
  75897. RenderTargetsOptimization.prototype.getDescription = function () {
  75898. return "Turning render targets off";
  75899. };
  75900. /**
  75901. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75902. * @param scene defines the current scene where to apply this optimization
  75903. */
  75904. RenderTargetsOptimization.prototype.apply = function (scene) {
  75905. scene.renderTargetsEnabled = false;
  75906. return true;
  75907. };
  75908. ;
  75909. return RenderTargetsOptimization;
  75910. }(SceneOptimization));
  75911. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75912. /**
  75913. * Defines an optimization used to merge meshes with compatible materials
  75914. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75915. */
  75916. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75917. __extends(MergeMeshesOptimization, _super);
  75918. function MergeMeshesOptimization() {
  75919. var _this = _super !== null && _super.apply(this, arguments) || this;
  75920. _this._canBeMerged = function (abstractMesh) {
  75921. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75922. return false;
  75923. }
  75924. var mesh = abstractMesh;
  75925. if (!mesh.isVisible || !mesh.isEnabled()) {
  75926. return false;
  75927. }
  75928. if (mesh.instances.length > 0) {
  75929. return false;
  75930. }
  75931. if (mesh.skeleton || mesh.hasLODLevels) {
  75932. return false;
  75933. }
  75934. if (mesh.parent) {
  75935. return false;
  75936. }
  75937. return true;
  75938. };
  75939. return _this;
  75940. }
  75941. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75942. /**
  75943. * Gets or sets a boolean which defines if optimization octree has to be updated
  75944. */
  75945. get: function () {
  75946. return MergeMeshesOptimization._UpdateSelectionTree;
  75947. },
  75948. /**
  75949. * Gets or sets a boolean which defines if optimization octree has to be updated
  75950. */
  75951. set: function (value) {
  75952. MergeMeshesOptimization._UpdateSelectionTree = value;
  75953. },
  75954. enumerable: true,
  75955. configurable: true
  75956. });
  75957. /**
  75958. * Gets a string describing the action executed by the current optimization
  75959. */
  75960. MergeMeshesOptimization.prototype.getDescription = function () {
  75961. return "Merging similar meshes together";
  75962. };
  75963. /**
  75964. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75965. * @param scene defines the current scene where to apply this optimization
  75966. */
  75967. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75968. var globalPool = scene.meshes.slice(0);
  75969. var globalLength = globalPool.length;
  75970. for (var index = 0; index < globalLength; index++) {
  75971. var currentPool = new Array();
  75972. var current = globalPool[index];
  75973. // Checks
  75974. if (!this._canBeMerged(current)) {
  75975. continue;
  75976. }
  75977. currentPool.push(current);
  75978. // Find compatible meshes
  75979. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75980. var otherMesh = globalPool[subIndex];
  75981. if (!this._canBeMerged(otherMesh)) {
  75982. continue;
  75983. }
  75984. if (otherMesh.material !== current.material) {
  75985. continue;
  75986. }
  75987. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75988. continue;
  75989. }
  75990. currentPool.push(otherMesh);
  75991. globalLength--;
  75992. globalPool.splice(subIndex, 1);
  75993. subIndex--;
  75994. }
  75995. if (currentPool.length < 2) {
  75996. continue;
  75997. }
  75998. // Merge meshes
  75999. BABYLON.Mesh.MergeMeshes(currentPool);
  76000. }
  76001. if (updateSelectionTree != undefined) {
  76002. if (updateSelectionTree) {
  76003. scene.createOrUpdateSelectionOctree();
  76004. }
  76005. }
  76006. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  76007. scene.createOrUpdateSelectionOctree();
  76008. }
  76009. return true;
  76010. };
  76011. ;
  76012. MergeMeshesOptimization._UpdateSelectionTree = false;
  76013. return MergeMeshesOptimization;
  76014. }(SceneOptimization));
  76015. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  76016. /**
  76017. * Defines a list of options used by SceneOptimizer
  76018. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76019. */
  76020. var SceneOptimizerOptions = /** @class */ (function () {
  76021. /**
  76022. * Creates a new list of options used by SceneOptimizer
  76023. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  76024. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  76025. */
  76026. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  76027. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  76028. if (trackerDuration === void 0) { trackerDuration = 2000; }
  76029. this.targetFrameRate = targetFrameRate;
  76030. this.trackerDuration = trackerDuration;
  76031. /**
  76032. * Gets the list of optimizations to apply
  76033. */
  76034. this.optimizations = new Array();
  76035. }
  76036. /**
  76037. * Add a new optimization
  76038. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  76039. */
  76040. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  76041. this.optimizations.push(optimization);
  76042. return this;
  76043. };
  76044. /**
  76045. * Add a new custom optimization
  76046. * @param onApply defines the callback called to apply the custom optimization.
  76047. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  76048. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  76049. */
  76050. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  76051. if (priority === void 0) { priority = 0; }
  76052. var optimization = new CustomOptimization(priority);
  76053. optimization.onApply = onApply;
  76054. optimization.onGetDescription = onGetDescription;
  76055. this.optimizations.push(optimization);
  76056. return this;
  76057. };
  76058. /**
  76059. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  76060. * @param targetFrameRate defines the target frame rate (60 by default)
  76061. * @returns a SceneOptimizerOptions object
  76062. */
  76063. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  76064. var result = new SceneOptimizerOptions(targetFrameRate);
  76065. var priority = 0;
  76066. result.addOptimization(new MergeMeshesOptimization(priority));
  76067. result.addOptimization(new ShadowsOptimization(priority));
  76068. result.addOptimization(new LensFlaresOptimization(priority));
  76069. // Next priority
  76070. priority++;
  76071. result.addOptimization(new PostProcessesOptimization(priority));
  76072. result.addOptimization(new ParticlesOptimization(priority));
  76073. // Next priority
  76074. priority++;
  76075. result.addOptimization(new TextureOptimization(priority, 1024));
  76076. return result;
  76077. };
  76078. /**
  76079. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  76080. * @param targetFrameRate defines the target frame rate (60 by default)
  76081. * @returns a SceneOptimizerOptions object
  76082. */
  76083. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  76084. var result = new SceneOptimizerOptions(targetFrameRate);
  76085. var priority = 0;
  76086. result.addOptimization(new MergeMeshesOptimization(priority));
  76087. result.addOptimization(new ShadowsOptimization(priority));
  76088. result.addOptimization(new LensFlaresOptimization(priority));
  76089. // Next priority
  76090. priority++;
  76091. result.addOptimization(new PostProcessesOptimization(priority));
  76092. result.addOptimization(new ParticlesOptimization(priority));
  76093. // Next priority
  76094. priority++;
  76095. result.addOptimization(new TextureOptimization(priority, 512));
  76096. // Next priority
  76097. priority++;
  76098. result.addOptimization(new RenderTargetsOptimization(priority));
  76099. // Next priority
  76100. priority++;
  76101. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  76102. return result;
  76103. };
  76104. /**
  76105. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  76106. * @param targetFrameRate defines the target frame rate (60 by default)
  76107. * @returns a SceneOptimizerOptions object
  76108. */
  76109. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  76110. var result = new SceneOptimizerOptions(targetFrameRate);
  76111. var priority = 0;
  76112. result.addOptimization(new MergeMeshesOptimization(priority));
  76113. result.addOptimization(new ShadowsOptimization(priority));
  76114. result.addOptimization(new LensFlaresOptimization(priority));
  76115. // Next priority
  76116. priority++;
  76117. result.addOptimization(new PostProcessesOptimization(priority));
  76118. result.addOptimization(new ParticlesOptimization(priority));
  76119. // Next priority
  76120. priority++;
  76121. result.addOptimization(new TextureOptimization(priority, 256));
  76122. // Next priority
  76123. priority++;
  76124. result.addOptimization(new RenderTargetsOptimization(priority));
  76125. // Next priority
  76126. priority++;
  76127. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  76128. return result;
  76129. };
  76130. return SceneOptimizerOptions;
  76131. }());
  76132. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76133. /**
  76134. * Class used to run optimizations in order to reach a target frame rate
  76135. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76136. */
  76137. var SceneOptimizer = /** @class */ (function () {
  76138. /**
  76139. * Creates a new SceneOptimizer
  76140. * @param scene defines the scene to work on
  76141. * @param options defines the options to use with the SceneOptimizer
  76142. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76143. */
  76144. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76145. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76146. var _this = this;
  76147. this._isRunning = false;
  76148. this._currentPriorityLevel = 0;
  76149. this._targetFrameRate = 60;
  76150. this._trackerDuration = 2000;
  76151. this._currentFrameRate = 0;
  76152. /**
  76153. * Defines an observable called when the optimizer reaches the target frame rate
  76154. */
  76155. this.onSuccessObservable = new BABYLON.Observable();
  76156. /**
  76157. * Defines an observable called when the optimizer enables an optimization
  76158. */
  76159. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76160. /**
  76161. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76162. */
  76163. this.onFailureObservable = new BABYLON.Observable();
  76164. if (!options) {
  76165. this._options = new SceneOptimizerOptions();
  76166. }
  76167. else {
  76168. this._options = options;
  76169. }
  76170. if (this._options.targetFrameRate) {
  76171. this._targetFrameRate = this._options.targetFrameRate;
  76172. }
  76173. if (this._options.trackerDuration) {
  76174. this._trackerDuration = this._options.trackerDuration;
  76175. }
  76176. if (autoGeneratePriorities) {
  76177. var priority = 0;
  76178. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76179. var optim = _a[_i];
  76180. optim.priority = priority++;
  76181. }
  76182. }
  76183. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76184. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76185. _this._sceneDisposeObserver = null;
  76186. _this.dispose();
  76187. });
  76188. }
  76189. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76190. /**
  76191. * Gets the current priority level (0 at start)
  76192. */
  76193. get: function () {
  76194. return this._currentPriorityLevel;
  76195. },
  76196. enumerable: true,
  76197. configurable: true
  76198. });
  76199. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76200. /**
  76201. * Gets the current frame rate checked by the SceneOptimizer
  76202. */
  76203. get: function () {
  76204. return this._currentFrameRate;
  76205. },
  76206. enumerable: true,
  76207. configurable: true
  76208. });
  76209. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76210. /**
  76211. * Gets or sets the current target frame rate (60 by default)
  76212. */
  76213. get: function () {
  76214. return this._targetFrameRate;
  76215. },
  76216. /**
  76217. * Gets or sets the current target frame rate (60 by default)
  76218. */
  76219. set: function (value) {
  76220. this._targetFrameRate = value;
  76221. },
  76222. enumerable: true,
  76223. configurable: true
  76224. });
  76225. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76226. /**
  76227. * Gets or sets the current interval between two checks (every 2000ms by default)
  76228. */
  76229. get: function () {
  76230. return this._trackerDuration;
  76231. },
  76232. /**
  76233. * Gets or sets the current interval between two checks (every 2000ms by default)
  76234. */
  76235. set: function (value) {
  76236. this._trackerDuration = value;
  76237. },
  76238. enumerable: true,
  76239. configurable: true
  76240. });
  76241. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76242. /**
  76243. * Gets the list of active optimizations
  76244. */
  76245. get: function () {
  76246. return this._options.optimizations;
  76247. },
  76248. enumerable: true,
  76249. configurable: true
  76250. });
  76251. /**
  76252. * Stops the current optimizer
  76253. */
  76254. SceneOptimizer.prototype.stop = function () {
  76255. this._isRunning = false;
  76256. };
  76257. SceneOptimizer.prototype.reset = function () {
  76258. this._currentPriorityLevel = 0;
  76259. };
  76260. SceneOptimizer.prototype.start = function () {
  76261. var _this = this;
  76262. if (this._isRunning) {
  76263. return;
  76264. }
  76265. this._isRunning = true;
  76266. // Let's wait for the scene to be ready before running our check
  76267. this._scene.executeWhenReady(function () {
  76268. setTimeout(function () {
  76269. _this._checkCurrentState();
  76270. }, _this._trackerDuration);
  76271. });
  76272. };
  76273. SceneOptimizer.prototype._checkCurrentState = function () {
  76274. var _this = this;
  76275. if (!this._isRunning) {
  76276. return;
  76277. }
  76278. var scene = this._scene;
  76279. var options = this._options;
  76280. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76281. if (this._currentFrameRate >= this._targetFrameRate) {
  76282. this._isRunning = false;
  76283. this.onSuccessObservable.notifyObservers(this);
  76284. return;
  76285. }
  76286. // Apply current level of optimizations
  76287. var allDone = true;
  76288. var noOptimizationApplied = true;
  76289. for (var index = 0; index < options.optimizations.length; index++) {
  76290. var optimization = options.optimizations[index];
  76291. if (optimization.priority === this._currentPriorityLevel) {
  76292. noOptimizationApplied = false;
  76293. allDone = allDone && optimization.apply(scene);
  76294. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76295. }
  76296. }
  76297. // If no optimization was applied, this is a failure :(
  76298. if (noOptimizationApplied) {
  76299. this._isRunning = false;
  76300. this.onFailureObservable.notifyObservers(this);
  76301. return;
  76302. }
  76303. // If all optimizations were done, move to next level
  76304. if (allDone) {
  76305. this._currentPriorityLevel++;
  76306. }
  76307. // Let's the system running for a specific amount of time before checking FPS
  76308. scene.executeWhenReady(function () {
  76309. setTimeout(function () {
  76310. _this._checkCurrentState();
  76311. }, _this._trackerDuration);
  76312. });
  76313. };
  76314. /**
  76315. * Release all resources
  76316. */
  76317. SceneOptimizer.prototype.dispose = function () {
  76318. this.stop();
  76319. this.onSuccessObservable.clear();
  76320. this.onFailureObservable.clear();
  76321. this.onNewOptimizationAppliedObservable.clear();
  76322. if (this._sceneDisposeObserver) {
  76323. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76324. }
  76325. };
  76326. /**
  76327. * Helper function to create a SceneOptimizer with one single line of code
  76328. * @param scene defines the scene to work on
  76329. * @param options defines the options to use with the SceneOptimizer
  76330. * @param onSuccess defines a callback to call on success
  76331. * @param onFailure defines a callback to call on failure
  76332. */
  76333. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76334. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76335. if (onSuccess) {
  76336. optimizer.onSuccessObservable.add(function () {
  76337. onSuccess();
  76338. });
  76339. }
  76340. if (onFailure) {
  76341. optimizer.onFailureObservable.add(function () {
  76342. onFailure();
  76343. });
  76344. }
  76345. optimizer.start();
  76346. return optimizer;
  76347. };
  76348. return SceneOptimizer;
  76349. }());
  76350. BABYLON.SceneOptimizer = SceneOptimizer;
  76351. })(BABYLON || (BABYLON = {}));
  76352. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76353. var BABYLON;
  76354. (function (BABYLON) {
  76355. var OutlineRenderer = /** @class */ (function () {
  76356. function OutlineRenderer(scene) {
  76357. this.zOffset = 1;
  76358. this._scene = scene;
  76359. }
  76360. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76361. var _this = this;
  76362. if (useOverlay === void 0) { useOverlay = false; }
  76363. var scene = this._scene;
  76364. var engine = this._scene.getEngine();
  76365. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76366. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76367. return;
  76368. }
  76369. var mesh = subMesh.getRenderingMesh();
  76370. var material = subMesh.getMaterial();
  76371. if (!material || !scene.activeCamera) {
  76372. return;
  76373. }
  76374. engine.enableEffect(this._effect);
  76375. // Logarithmic depth
  76376. if (material.useLogarithmicDepth) {
  76377. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76378. }
  76379. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76380. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76381. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76382. // Bones
  76383. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76384. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76385. }
  76386. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76387. // Alpha test
  76388. if (material && material.needAlphaTesting()) {
  76389. var alphaTexture = material.getAlphaTestTexture();
  76390. if (alphaTexture) {
  76391. this._effect.setTexture("diffuseSampler", alphaTexture);
  76392. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76393. }
  76394. }
  76395. engine.setZOffset(-this.zOffset);
  76396. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76397. engine.setZOffset(0);
  76398. };
  76399. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76400. var defines = [];
  76401. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76402. var mesh = subMesh.getMesh();
  76403. var material = subMesh.getMaterial();
  76404. if (material) {
  76405. // Alpha test
  76406. if (material.needAlphaTesting()) {
  76407. defines.push("#define ALPHATEST");
  76408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76409. attribs.push(BABYLON.VertexBuffer.UVKind);
  76410. defines.push("#define UV1");
  76411. }
  76412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76413. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76414. defines.push("#define UV2");
  76415. }
  76416. }
  76417. //Logarithmic depth
  76418. if (material.useLogarithmicDepth) {
  76419. defines.push("#define LOGARITHMICDEPTH");
  76420. }
  76421. }
  76422. // Bones
  76423. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76426. if (mesh.numBoneInfluencers > 4) {
  76427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76429. }
  76430. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76431. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76432. }
  76433. else {
  76434. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76435. }
  76436. // Instances
  76437. if (useInstances) {
  76438. defines.push("#define INSTANCES");
  76439. attribs.push("world0");
  76440. attribs.push("world1");
  76441. attribs.push("world2");
  76442. attribs.push("world3");
  76443. }
  76444. // Get correct effect
  76445. var join = defines.join("\n");
  76446. if (this._cachedDefines !== join) {
  76447. this._cachedDefines = join;
  76448. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76449. }
  76450. return this._effect.isReady();
  76451. };
  76452. return OutlineRenderer;
  76453. }());
  76454. BABYLON.OutlineRenderer = OutlineRenderer;
  76455. })(BABYLON || (BABYLON = {}));
  76456. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76457. var BABYLON;
  76458. (function (BABYLON) {
  76459. var FaceAdjacencies = /** @class */ (function () {
  76460. function FaceAdjacencies() {
  76461. this.edges = new Array();
  76462. this.edgesConnectedCount = 0;
  76463. }
  76464. return FaceAdjacencies;
  76465. }());
  76466. var EdgesRenderer = /** @class */ (function () {
  76467. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76468. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76469. if (epsilon === void 0) { epsilon = 0.95; }
  76470. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76471. this.edgesWidthScalerForOrthographic = 1000.0;
  76472. this.edgesWidthScalerForPerspective = 50.0;
  76473. this._linesPositions = new Array();
  76474. this._linesNormals = new Array();
  76475. this._linesIndices = new Array();
  76476. this._buffers = {};
  76477. this._checkVerticesInsteadOfIndices = false;
  76478. this._source = source;
  76479. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76480. this._epsilon = epsilon;
  76481. this._prepareRessources();
  76482. this._generateEdgesLines();
  76483. }
  76484. EdgesRenderer.prototype._prepareRessources = function () {
  76485. if (this._lineShader) {
  76486. return;
  76487. }
  76488. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76489. attributes: ["position", "normal"],
  76490. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76491. });
  76492. this._lineShader.disableDepthWrite = true;
  76493. this._lineShader.backFaceCulling = false;
  76494. };
  76495. EdgesRenderer.prototype._rebuild = function () {
  76496. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76497. if (buffer) {
  76498. buffer._rebuild();
  76499. }
  76500. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76501. if (buffer) {
  76502. buffer._rebuild();
  76503. }
  76504. var scene = this._source.getScene();
  76505. var engine = scene.getEngine();
  76506. this._ib = engine.createIndexBuffer(this._linesIndices);
  76507. };
  76508. EdgesRenderer.prototype.dispose = function () {
  76509. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76510. if (buffer) {
  76511. buffer.dispose();
  76512. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76513. }
  76514. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76515. if (buffer) {
  76516. buffer.dispose();
  76517. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76518. }
  76519. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76520. this._lineShader.dispose();
  76521. };
  76522. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76523. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76524. return 0;
  76525. }
  76526. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76527. return 1;
  76528. }
  76529. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76530. return 2;
  76531. }
  76532. return -1;
  76533. };
  76534. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76535. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76536. return 0;
  76537. }
  76538. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76539. return 1;
  76540. }
  76541. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76542. return 2;
  76543. }
  76544. return -1;
  76545. };
  76546. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76547. var needToCreateLine;
  76548. if (edge === undefined) {
  76549. needToCreateLine = true;
  76550. }
  76551. else {
  76552. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76553. needToCreateLine = dotProduct < this._epsilon;
  76554. }
  76555. if (needToCreateLine) {
  76556. var offset = this._linesPositions.length / 3;
  76557. var normal = p0.subtract(p1);
  76558. normal.normalize();
  76559. // Positions
  76560. this._linesPositions.push(p0.x);
  76561. this._linesPositions.push(p0.y);
  76562. this._linesPositions.push(p0.z);
  76563. this._linesPositions.push(p0.x);
  76564. this._linesPositions.push(p0.y);
  76565. this._linesPositions.push(p0.z);
  76566. this._linesPositions.push(p1.x);
  76567. this._linesPositions.push(p1.y);
  76568. this._linesPositions.push(p1.z);
  76569. this._linesPositions.push(p1.x);
  76570. this._linesPositions.push(p1.y);
  76571. this._linesPositions.push(p1.z);
  76572. // Normals
  76573. this._linesNormals.push(p1.x);
  76574. this._linesNormals.push(p1.y);
  76575. this._linesNormals.push(p1.z);
  76576. this._linesNormals.push(-1);
  76577. this._linesNormals.push(p1.x);
  76578. this._linesNormals.push(p1.y);
  76579. this._linesNormals.push(p1.z);
  76580. this._linesNormals.push(1);
  76581. this._linesNormals.push(p0.x);
  76582. this._linesNormals.push(p0.y);
  76583. this._linesNormals.push(p0.z);
  76584. this._linesNormals.push(-1);
  76585. this._linesNormals.push(p0.x);
  76586. this._linesNormals.push(p0.y);
  76587. this._linesNormals.push(p0.z);
  76588. this._linesNormals.push(1);
  76589. // Indices
  76590. this._linesIndices.push(offset);
  76591. this._linesIndices.push(offset + 1);
  76592. this._linesIndices.push(offset + 2);
  76593. this._linesIndices.push(offset);
  76594. this._linesIndices.push(offset + 2);
  76595. this._linesIndices.push(offset + 3);
  76596. }
  76597. };
  76598. EdgesRenderer.prototype._generateEdgesLines = function () {
  76599. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76600. var indices = this._source.getIndices();
  76601. if (!indices || !positions) {
  76602. return;
  76603. }
  76604. // First let's find adjacencies
  76605. var adjacencies = new Array();
  76606. var faceNormals = new Array();
  76607. var index;
  76608. var faceAdjacencies;
  76609. // Prepare faces
  76610. for (index = 0; index < indices.length; index += 3) {
  76611. faceAdjacencies = new FaceAdjacencies();
  76612. var p0Index = indices[index];
  76613. var p1Index = indices[index + 1];
  76614. var p2Index = indices[index + 2];
  76615. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76616. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76617. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76618. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76619. faceNormal.normalize();
  76620. faceNormals.push(faceNormal);
  76621. adjacencies.push(faceAdjacencies);
  76622. }
  76623. // Scan
  76624. for (index = 0; index < adjacencies.length; index++) {
  76625. faceAdjacencies = adjacencies[index];
  76626. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76627. var otherFaceAdjacencies = adjacencies[otherIndex];
  76628. if (faceAdjacencies.edgesConnectedCount === 3) {
  76629. break;
  76630. }
  76631. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76632. continue;
  76633. }
  76634. var otherP0 = indices[otherIndex * 3];
  76635. var otherP1 = indices[otherIndex * 3 + 1];
  76636. var otherP2 = indices[otherIndex * 3 + 2];
  76637. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76638. var otherEdgeIndex = 0;
  76639. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76640. continue;
  76641. }
  76642. switch (edgeIndex) {
  76643. case 0:
  76644. if (this._checkVerticesInsteadOfIndices) {
  76645. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76646. }
  76647. else {
  76648. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76649. }
  76650. break;
  76651. case 1:
  76652. if (this._checkVerticesInsteadOfIndices) {
  76653. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76654. }
  76655. else {
  76656. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76657. }
  76658. break;
  76659. case 2:
  76660. if (this._checkVerticesInsteadOfIndices) {
  76661. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76662. }
  76663. else {
  76664. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76665. }
  76666. break;
  76667. }
  76668. if (otherEdgeIndex === -1) {
  76669. continue;
  76670. }
  76671. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76672. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76673. faceAdjacencies.edgesConnectedCount++;
  76674. otherFaceAdjacencies.edgesConnectedCount++;
  76675. if (faceAdjacencies.edgesConnectedCount === 3) {
  76676. break;
  76677. }
  76678. }
  76679. }
  76680. }
  76681. // Create lines
  76682. for (index = 0; index < adjacencies.length; index++) {
  76683. // 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
  76684. var current = adjacencies[index];
  76685. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76686. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76687. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76688. }
  76689. // Merge into a single mesh
  76690. var engine = this._source.getScene().getEngine();
  76691. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76692. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76693. this._ib = engine.createIndexBuffer(this._linesIndices);
  76694. this._indicesCount = this._linesIndices.length;
  76695. };
  76696. EdgesRenderer.prototype.render = function () {
  76697. var scene = this._source.getScene();
  76698. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76699. return;
  76700. }
  76701. var engine = scene.getEngine();
  76702. this._lineShader._preBind();
  76703. // VBOs
  76704. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76705. scene.resetCachedMaterial();
  76706. this._lineShader.setColor4("color", this._source.edgesColor);
  76707. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76708. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76709. }
  76710. else {
  76711. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76712. }
  76713. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76714. this._lineShader.bind(this._source.getWorldMatrix());
  76715. // Draw order
  76716. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76717. this._lineShader.unbind();
  76718. engine.setDepthWrite(true);
  76719. };
  76720. return EdgesRenderer;
  76721. }());
  76722. BABYLON.EdgesRenderer = EdgesRenderer;
  76723. })(BABYLON || (BABYLON = {}));
  76724. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76725. var BABYLON;
  76726. (function (BABYLON) {
  76727. /**
  76728. * Special Glow Blur post process only blurring the alpha channel
  76729. * It enforces keeping the most luminous color in the color channel.
  76730. */
  76731. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76732. __extends(GlowBlurPostProcess, _super);
  76733. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76735. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76736. _this.direction = direction;
  76737. _this.kernel = kernel;
  76738. _this.onApplyObservable.add(function (effect) {
  76739. effect.setFloat2("screenSize", _this.width, _this.height);
  76740. effect.setVector2("direction", _this.direction);
  76741. effect.setFloat("blurWidth", _this.kernel);
  76742. });
  76743. return _this;
  76744. }
  76745. return GlowBlurPostProcess;
  76746. }(BABYLON.PostProcess));
  76747. /**
  76748. * The highlight layer Helps adding a glow effect around a mesh.
  76749. *
  76750. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76751. * glowy meshes to your scene.
  76752. *
  76753. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76754. */
  76755. var HighlightLayer = /** @class */ (function () {
  76756. /**
  76757. * Instantiates a new highlight Layer and references it to the scene..
  76758. * @param name The name of the layer
  76759. * @param scene The scene to use the layer in
  76760. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76761. */
  76762. function HighlightLayer(name, scene, options) {
  76763. this.name = name;
  76764. this._vertexBuffers = {};
  76765. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76766. this._meshes = {};
  76767. this._maxSize = 0;
  76768. this._shouldRender = false;
  76769. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76770. this._excludedMeshes = {};
  76771. /**
  76772. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76773. */
  76774. this.innerGlow = true;
  76775. /**
  76776. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76777. */
  76778. this.outerGlow = true;
  76779. /**
  76780. * Specifies wether the highlight layer is enabled or not.
  76781. */
  76782. this.isEnabled = true;
  76783. /**
  76784. * An event triggered when the highlight layer has been disposed.
  76785. * @type {BABYLON.Observable}
  76786. */
  76787. this.onDisposeObservable = new BABYLON.Observable();
  76788. /**
  76789. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76790. * @type {BABYLON.Observable}
  76791. */
  76792. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76793. /**
  76794. * An event triggered when the highlight layer is being blurred.
  76795. * @type {BABYLON.Observable}
  76796. */
  76797. this.onBeforeBlurObservable = new BABYLON.Observable();
  76798. /**
  76799. * An event triggered when the highlight layer has been blurred.
  76800. * @type {BABYLON.Observable}
  76801. */
  76802. this.onAfterBlurObservable = new BABYLON.Observable();
  76803. /**
  76804. * An event triggered when the glowing blurred texture is being merged in the scene.
  76805. * @type {BABYLON.Observable}
  76806. */
  76807. this.onBeforeComposeObservable = new BABYLON.Observable();
  76808. /**
  76809. * An event triggered when the glowing blurred texture has been merged in the scene.
  76810. * @type {BABYLON.Observable}
  76811. */
  76812. this.onAfterComposeObservable = new BABYLON.Observable();
  76813. /**
  76814. * An event triggered when the highlight layer changes its size.
  76815. * @type {BABYLON.Observable}
  76816. */
  76817. this.onSizeChangedObservable = new BABYLON.Observable();
  76818. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76819. var engine = scene.getEngine();
  76820. this._engine = engine;
  76821. this._maxSize = this._engine.getCaps().maxTextureSize;
  76822. this._scene.highlightLayers.push(this);
  76823. // Warn on stencil.
  76824. if (!this._engine.isStencilEnable) {
  76825. 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 }");
  76826. }
  76827. // Adapt options
  76828. this._options = options || {
  76829. mainTextureRatio: 0.5,
  76830. blurTextureSizeRatio: 0.5,
  76831. blurHorizontalSize: 1.0,
  76832. blurVerticalSize: 1.0,
  76833. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76834. camera: null
  76835. };
  76836. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76837. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76838. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76839. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76840. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76841. // VBO
  76842. var vertices = [];
  76843. vertices.push(1, 1);
  76844. vertices.push(-1, 1);
  76845. vertices.push(-1, -1);
  76846. vertices.push(1, -1);
  76847. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76849. this._createIndexBuffer();
  76850. // Effect
  76851. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76852. // Render target
  76853. this.setMainTextureSize();
  76854. // Create Textures and post processes
  76855. this.createTextureAndPostProcesses();
  76856. }
  76857. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76858. /**
  76859. * Gets the horizontal size of the blur.
  76860. */
  76861. get: function () {
  76862. return this._horizontalBlurPostprocess.kernel;
  76863. },
  76864. /**
  76865. * Specifies the horizontal size of the blur.
  76866. */
  76867. set: function (value) {
  76868. this._horizontalBlurPostprocess.kernel = value;
  76869. },
  76870. enumerable: true,
  76871. configurable: true
  76872. });
  76873. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76874. /**
  76875. * Gets the vertical size of the blur.
  76876. */
  76877. get: function () {
  76878. return this._verticalBlurPostprocess.kernel;
  76879. },
  76880. /**
  76881. * Specifies the vertical size of the blur.
  76882. */
  76883. set: function (value) {
  76884. this._verticalBlurPostprocess.kernel = value;
  76885. },
  76886. enumerable: true,
  76887. configurable: true
  76888. });
  76889. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76890. /**
  76891. * Gets the camera attached to the layer.
  76892. */
  76893. get: function () {
  76894. return this._options.camera;
  76895. },
  76896. enumerable: true,
  76897. configurable: true
  76898. });
  76899. HighlightLayer.prototype._createIndexBuffer = function () {
  76900. var engine = this._scene.getEngine();
  76901. // Indices
  76902. var indices = [];
  76903. indices.push(0);
  76904. indices.push(1);
  76905. indices.push(2);
  76906. indices.push(0);
  76907. indices.push(2);
  76908. indices.push(3);
  76909. this._indexBuffer = engine.createIndexBuffer(indices);
  76910. };
  76911. HighlightLayer.prototype._rebuild = function () {
  76912. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76913. if (vb) {
  76914. vb._rebuild();
  76915. }
  76916. this._createIndexBuffer();
  76917. };
  76918. /**
  76919. * Creates the render target textures and post processes used in the highlight layer.
  76920. */
  76921. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76922. var _this = this;
  76923. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76924. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76925. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76926. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76927. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76928. width: this._mainTextureDesiredSize.width,
  76929. height: this._mainTextureDesiredSize.height
  76930. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76931. this._mainTexture.activeCamera = this._options.camera;
  76932. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76933. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76934. this._mainTexture.anisotropicFilteringLevel = 1;
  76935. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76936. this._mainTexture.renderParticles = false;
  76937. this._mainTexture.renderList = null;
  76938. this._mainTexture.ignoreCameraViewport = true;
  76939. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76940. width: blurTextureWidth,
  76941. height: blurTextureHeight
  76942. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76943. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76944. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76945. this._blurTexture.anisotropicFilteringLevel = 16;
  76946. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76947. this._blurTexture.renderParticles = false;
  76948. this._blurTexture.ignoreCameraViewport = true;
  76949. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76950. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76951. effect.setTexture("textureSampler", _this._mainTexture);
  76952. });
  76953. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76954. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76955. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76956. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76957. });
  76958. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76959. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76960. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76961. });
  76962. }
  76963. else {
  76964. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76965. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76966. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76967. });
  76968. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76969. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76970. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76971. });
  76972. }
  76973. this._mainTexture.onAfterUnbindObservable.add(function () {
  76974. _this.onBeforeBlurObservable.notifyObservers(_this);
  76975. var internalTexture = _this._blurTexture.getInternalTexture();
  76976. if (internalTexture) {
  76977. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76978. }
  76979. _this.onAfterBlurObservable.notifyObservers(_this);
  76980. });
  76981. // Custom render function
  76982. var renderSubMesh = function (subMesh) {
  76983. if (!_this._meshes) {
  76984. return;
  76985. }
  76986. var material = subMesh.getMaterial();
  76987. var mesh = subMesh.getRenderingMesh();
  76988. var scene = _this._scene;
  76989. var engine = scene.getEngine();
  76990. if (!material) {
  76991. return;
  76992. }
  76993. // Do not block in blend mode.
  76994. if (material.needAlphaBlendingForMesh(mesh)) {
  76995. return;
  76996. }
  76997. // Culling
  76998. engine.setState(material.backFaceCulling);
  76999. // Managing instances
  77000. var batch = mesh._getInstancesRenderList(subMesh._id);
  77001. if (batch.mustReturn) {
  77002. return;
  77003. }
  77004. // Excluded Mesh
  77005. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77006. return;
  77007. }
  77008. ;
  77009. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77010. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  77011. var emissiveTexture = null;
  77012. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77013. emissiveTexture = material.emissiveTexture;
  77014. }
  77015. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  77016. engine.enableEffect(_this._glowMapGenerationEffect);
  77017. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  77018. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  77019. if (highlightLayerMesh) {
  77020. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  77021. }
  77022. else {
  77023. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  77024. }
  77025. // Alpha test
  77026. if (material && material.needAlphaTesting()) {
  77027. var alphaTexture = material.getAlphaTestTexture();
  77028. if (alphaTexture) {
  77029. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  77030. var textureMatrix = alphaTexture.getTextureMatrix();
  77031. if (textureMatrix) {
  77032. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  77033. }
  77034. }
  77035. }
  77036. // Glow emissive only
  77037. if (emissiveTexture) {
  77038. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  77039. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  77040. }
  77041. // Bones
  77042. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77043. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77044. }
  77045. // Draw
  77046. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  77047. }
  77048. else {
  77049. // Need to reset refresh rate of the shadowMap
  77050. _this._mainTexture.resetRefreshCounter();
  77051. }
  77052. };
  77053. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77054. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  77055. var index;
  77056. var engine = _this._scene.getEngine();
  77057. if (depthOnlySubMeshes.length) {
  77058. engine.setColorWrite(false);
  77059. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77060. renderSubMesh(depthOnlySubMeshes.data[index]);
  77061. }
  77062. engine.setColorWrite(true);
  77063. }
  77064. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77065. renderSubMesh(opaqueSubMeshes.data[index]);
  77066. }
  77067. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77068. renderSubMesh(alphaTestSubMeshes.data[index]);
  77069. }
  77070. for (index = 0; index < transparentSubMeshes.length; index++) {
  77071. renderSubMesh(transparentSubMeshes.data[index]);
  77072. }
  77073. };
  77074. this._mainTexture.onClearObservable.add(function (engine) {
  77075. engine.clear(HighlightLayer.neutralColor, true, true, true);
  77076. });
  77077. };
  77078. /**
  77079. * Checks for the readiness of the element composing the layer.
  77080. * @param subMesh the mesh to check for
  77081. * @param useInstances specify wether or not to use instances to render the mesh
  77082. * @param emissiveTexture the associated emissive texture used to generate the glow
  77083. * @return true if ready otherwise, false
  77084. */
  77085. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  77086. var material = subMesh.getMaterial();
  77087. var mesh = subMesh.getRenderingMesh();
  77088. if (!material || !mesh || !this._meshes) {
  77089. return false;
  77090. }
  77091. var emissiveTexture = null;
  77092. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  77093. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77094. emissiveTexture = material.emissiveTexture;
  77095. }
  77096. return this._isReady(subMesh, useInstances, emissiveTexture);
  77097. };
  77098. /**
  77099. * Checks for the readiness of the element composing the layer.
  77100. * @param subMesh the mesh to check for
  77101. * @param useInstances specify wether or not to use instances to render the mesh
  77102. * @param emissiveTexture the associated emissive texture used to generate the glow
  77103. * @return true if ready otherwise, false
  77104. */
  77105. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  77106. var material = subMesh.getMaterial();
  77107. if (!material) {
  77108. return false;
  77109. }
  77110. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  77111. return false;
  77112. }
  77113. var defines = [];
  77114. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77115. var mesh = subMesh.getMesh();
  77116. var uv1 = false;
  77117. var uv2 = false;
  77118. // Alpha test
  77119. if (material && material.needAlphaTesting()) {
  77120. var alphaTexture = material.getAlphaTestTexture();
  77121. if (alphaTexture) {
  77122. defines.push("#define ALPHATEST");
  77123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77124. alphaTexture.coordinatesIndex === 1) {
  77125. defines.push("#define DIFFUSEUV2");
  77126. uv2 = true;
  77127. }
  77128. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77129. defines.push("#define DIFFUSEUV1");
  77130. uv1 = true;
  77131. }
  77132. }
  77133. }
  77134. // Emissive
  77135. if (emissiveTexture) {
  77136. defines.push("#define EMISSIVE");
  77137. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77138. emissiveTexture.coordinatesIndex === 1) {
  77139. defines.push("#define EMISSIVEUV2");
  77140. uv2 = true;
  77141. }
  77142. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77143. defines.push("#define EMISSIVEUV1");
  77144. uv1 = true;
  77145. }
  77146. }
  77147. if (uv1) {
  77148. attribs.push(BABYLON.VertexBuffer.UVKind);
  77149. defines.push("#define UV1");
  77150. }
  77151. if (uv2) {
  77152. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77153. defines.push("#define UV2");
  77154. }
  77155. // Bones
  77156. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77157. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77158. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77159. if (mesh.numBoneInfluencers > 4) {
  77160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77162. }
  77163. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77164. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77165. }
  77166. else {
  77167. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77168. }
  77169. // Instances
  77170. if (useInstances) {
  77171. defines.push("#define INSTANCES");
  77172. attribs.push("world0");
  77173. attribs.push("world1");
  77174. attribs.push("world2");
  77175. attribs.push("world3");
  77176. }
  77177. // Get correct effect
  77178. var join = defines.join("\n");
  77179. if (this._cachedDefines !== join) {
  77180. this._cachedDefines = join;
  77181. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77182. }
  77183. return this._glowMapGenerationEffect.isReady();
  77184. };
  77185. /**
  77186. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77187. */
  77188. HighlightLayer.prototype.render = function () {
  77189. var currentEffect = this._glowMapMergeEffect;
  77190. // Check
  77191. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77192. return;
  77193. var engine = this._scene.getEngine();
  77194. this.onBeforeComposeObservable.notifyObservers(this);
  77195. // Render
  77196. engine.enableEffect(currentEffect);
  77197. engine.setState(false);
  77198. // Cache
  77199. var previousStencilBuffer = engine.getStencilBuffer();
  77200. var previousStencilFunction = engine.getStencilFunction();
  77201. var previousStencilMask = engine.getStencilMask();
  77202. var previousStencilOperationPass = engine.getStencilOperationPass();
  77203. var previousStencilOperationFail = engine.getStencilOperationFail();
  77204. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77205. var previousAlphaMode = engine.getAlphaMode();
  77206. // Texture
  77207. currentEffect.setTexture("textureSampler", this._blurTexture);
  77208. // VBOs
  77209. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77210. // Stencil operations
  77211. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77212. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77213. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77214. // Draw order
  77215. engine.setAlphaMode(this._options.alphaBlendingMode);
  77216. engine.setStencilMask(0x00);
  77217. engine.setStencilBuffer(true);
  77218. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77219. if (this.outerGlow) {
  77220. currentEffect.setFloat("offset", 0);
  77221. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77222. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77223. }
  77224. if (this.innerGlow) {
  77225. currentEffect.setFloat("offset", 1);
  77226. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77227. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77228. }
  77229. // Restore Cache
  77230. engine.setStencilFunction(previousStencilFunction);
  77231. engine.setStencilMask(previousStencilMask);
  77232. engine.setAlphaMode(previousAlphaMode);
  77233. engine.setStencilBuffer(previousStencilBuffer);
  77234. engine.setStencilOperationPass(previousStencilOperationPass);
  77235. engine.setStencilOperationFail(previousStencilOperationFail);
  77236. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77237. engine._stencilState.reset();
  77238. this.onAfterComposeObservable.notifyObservers(this);
  77239. // Handle size changes.
  77240. var size = this._mainTexture.getSize();
  77241. this.setMainTextureSize();
  77242. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77243. // Recreate RTT and post processes on size change.
  77244. this.onSizeChangedObservable.notifyObservers(this);
  77245. this.disposeTextureAndPostProcesses();
  77246. this.createTextureAndPostProcesses();
  77247. }
  77248. };
  77249. /**
  77250. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77251. * @param mesh The mesh to exclude from the highlight layer
  77252. */
  77253. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77254. if (!this._excludedMeshes) {
  77255. return;
  77256. }
  77257. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77258. if (!meshExcluded) {
  77259. this._excludedMeshes[mesh.uniqueId] = {
  77260. mesh: mesh,
  77261. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77262. mesh.getEngine().setStencilBuffer(false);
  77263. }),
  77264. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77265. mesh.getEngine().setStencilBuffer(true);
  77266. }),
  77267. };
  77268. }
  77269. };
  77270. /**
  77271. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77272. * @param mesh The mesh to highlight
  77273. */
  77274. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77275. if (!this._excludedMeshes) {
  77276. return;
  77277. }
  77278. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77279. if (meshExcluded) {
  77280. if (meshExcluded.beforeRender) {
  77281. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77282. }
  77283. if (meshExcluded.afterRender) {
  77284. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77285. }
  77286. }
  77287. this._excludedMeshes[mesh.uniqueId] = null;
  77288. };
  77289. /**
  77290. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77291. * @param mesh mesh to test
  77292. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77293. */
  77294. HighlightLayer.prototype.hasMesh = function (mesh) {
  77295. if (!this._meshes) {
  77296. return false;
  77297. }
  77298. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77299. };
  77300. /**
  77301. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77302. * @param mesh The mesh to highlight
  77303. * @param color The color of the highlight
  77304. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77305. */
  77306. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77307. var _this = this;
  77308. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77309. if (!this._meshes) {
  77310. return;
  77311. }
  77312. var meshHighlight = this._meshes[mesh.uniqueId];
  77313. if (meshHighlight) {
  77314. meshHighlight.color = color;
  77315. }
  77316. else {
  77317. this._meshes[mesh.uniqueId] = {
  77318. mesh: mesh,
  77319. color: color,
  77320. // Lambda required for capture due to Observable this context
  77321. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77322. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77323. _this.defaultStencilReference(mesh);
  77324. }
  77325. else {
  77326. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77327. }
  77328. }),
  77329. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77330. glowEmissiveOnly: glowEmissiveOnly
  77331. };
  77332. }
  77333. this._shouldRender = true;
  77334. };
  77335. /**
  77336. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77337. * @param mesh The mesh to highlight
  77338. */
  77339. HighlightLayer.prototype.removeMesh = function (mesh) {
  77340. if (!this._meshes) {
  77341. return;
  77342. }
  77343. var meshHighlight = this._meshes[mesh.uniqueId];
  77344. if (meshHighlight) {
  77345. if (meshHighlight.observerHighlight) {
  77346. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77347. }
  77348. if (meshHighlight.observerDefault) {
  77349. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77350. }
  77351. delete this._meshes[mesh.uniqueId];
  77352. }
  77353. this._shouldRender = false;
  77354. for (var meshHighlightToCheck in this._meshes) {
  77355. if (this._meshes[meshHighlightToCheck]) {
  77356. this._shouldRender = true;
  77357. break;
  77358. }
  77359. }
  77360. };
  77361. /**
  77362. * Returns true if the layer contains information to display, otherwise false.
  77363. */
  77364. HighlightLayer.prototype.shouldRender = function () {
  77365. return this.isEnabled && this._shouldRender;
  77366. };
  77367. /**
  77368. * Sets the main texture desired size which is the closest power of two
  77369. * of the engine canvas size.
  77370. */
  77371. HighlightLayer.prototype.setMainTextureSize = function () {
  77372. if (this._options.mainTextureFixedSize) {
  77373. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77374. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77375. }
  77376. else {
  77377. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77378. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77379. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77380. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77381. }
  77382. };
  77383. /**
  77384. * Force the stencil to the normal expected value for none glowing parts
  77385. */
  77386. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77387. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77388. };
  77389. /**
  77390. * Dispose only the render target textures and post process.
  77391. */
  77392. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77393. this._blurTexture.dispose();
  77394. this._mainTexture.dispose();
  77395. this._downSamplePostprocess.dispose();
  77396. this._horizontalBlurPostprocess.dispose();
  77397. this._verticalBlurPostprocess.dispose();
  77398. };
  77399. /**
  77400. * Dispose the highlight layer and free resources.
  77401. */
  77402. HighlightLayer.prototype.dispose = function () {
  77403. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77404. if (vertexBuffer) {
  77405. vertexBuffer.dispose();
  77406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77407. }
  77408. if (this._indexBuffer) {
  77409. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77410. this._indexBuffer = null;
  77411. }
  77412. // Clean textures and post processes
  77413. this.disposeTextureAndPostProcesses();
  77414. if (this._meshes) {
  77415. // Clean mesh references
  77416. for (var id in this._meshes) {
  77417. var meshHighlight = this._meshes[id];
  77418. if (meshHighlight && meshHighlight.mesh) {
  77419. if (meshHighlight.observerHighlight) {
  77420. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77421. }
  77422. if (meshHighlight.observerDefault) {
  77423. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77424. }
  77425. }
  77426. }
  77427. this._meshes = null;
  77428. }
  77429. if (this._excludedMeshes) {
  77430. for (var id in this._excludedMeshes) {
  77431. var meshHighlight = this._excludedMeshes[id];
  77432. if (meshHighlight) {
  77433. if (meshHighlight.beforeRender) {
  77434. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77435. }
  77436. if (meshHighlight.afterRender) {
  77437. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77438. }
  77439. }
  77440. }
  77441. this._excludedMeshes = null;
  77442. }
  77443. // Remove from scene
  77444. var index = this._scene.highlightLayers.indexOf(this, 0);
  77445. if (index > -1) {
  77446. this._scene.highlightLayers.splice(index, 1);
  77447. }
  77448. // Callback
  77449. this.onDisposeObservable.notifyObservers(this);
  77450. this.onDisposeObservable.clear();
  77451. this.onBeforeRenderMainTextureObservable.clear();
  77452. this.onBeforeBlurObservable.clear();
  77453. this.onBeforeComposeObservable.clear();
  77454. this.onAfterComposeObservable.clear();
  77455. this.onSizeChangedObservable.clear();
  77456. };
  77457. /**
  77458. * The neutral color used during the preparation of the glow effect.
  77459. * This is black by default as the blend operation is a blend operation.
  77460. */
  77461. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77462. /**
  77463. * Stencil value used for glowing meshes.
  77464. */
  77465. HighlightLayer.glowingMeshStencilReference = 0x02;
  77466. /**
  77467. * Stencil value used for the other meshes in the scene.
  77468. */
  77469. HighlightLayer.normalMeshStencilReference = 0x01;
  77470. return HighlightLayer;
  77471. }());
  77472. BABYLON.HighlightLayer = HighlightLayer;
  77473. })(BABYLON || (BABYLON = {}));
  77474. //# sourceMappingURL=babylon.highlightlayer.js.map
  77475. var BABYLON;
  77476. (function (BABYLON) {
  77477. /**
  77478. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  77479. */
  77480. var AssetTaskState;
  77481. (function (AssetTaskState) {
  77482. /**
  77483. * Initialization
  77484. */
  77485. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77486. /**
  77487. * Running
  77488. */
  77489. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77490. /**
  77491. * Done
  77492. */
  77493. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77494. /**
  77495. * Error
  77496. */
  77497. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77498. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77499. /**
  77500. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  77501. */
  77502. var AbstractAssetTask = /** @class */ (function () {
  77503. /**
  77504. * Creates a new {BABYLON.AssetsManager}
  77505. * @param name defines the name of the task
  77506. */
  77507. function AbstractAssetTask(
  77508. /**
  77509. * Task name
  77510. */ name) {
  77511. this.name = name;
  77512. this._isCompleted = false;
  77513. this._taskState = AssetTaskState.INIT;
  77514. }
  77515. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  77516. /**
  77517. * Get if the task is completed
  77518. */
  77519. get: function () {
  77520. return this._isCompleted;
  77521. },
  77522. enumerable: true,
  77523. configurable: true
  77524. });
  77525. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  77526. /**
  77527. * Gets the current state of the task
  77528. */
  77529. get: function () {
  77530. return this._taskState;
  77531. },
  77532. enumerable: true,
  77533. configurable: true
  77534. });
  77535. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  77536. /**
  77537. * Gets the current error object (if task is in error)
  77538. */
  77539. get: function () {
  77540. return this._errorObject;
  77541. },
  77542. enumerable: true,
  77543. configurable: true
  77544. });
  77545. /**
  77546. * Internal only
  77547. * @ignore
  77548. */
  77549. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  77550. if (this._errorObject) {
  77551. return;
  77552. }
  77553. this._errorObject = {
  77554. message: message,
  77555. exception: exception
  77556. };
  77557. };
  77558. /**
  77559. * Execute the current task
  77560. * @param scene defines the scene where you want your assets to be loaded
  77561. * @param onSuccess is a callback called when the task is successfully executed
  77562. * @param onError is a callback called if an error occurs
  77563. */
  77564. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77565. var _this = this;
  77566. this._taskState = AssetTaskState.RUNNING;
  77567. this.runTask(scene, function () {
  77568. _this.onDoneCallback(onSuccess, onError);
  77569. }, function (msg, exception) {
  77570. _this.onErrorCallback(onError, msg, exception);
  77571. });
  77572. };
  77573. /**
  77574. * Execute the current task
  77575. * @param scene defines the scene where you want your assets to be loaded
  77576. * @param onSuccess is a callback called when the task is successfully executed
  77577. * @param onError is a callback called if an error occurs
  77578. */
  77579. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77580. throw new Error("runTask is not implemented");
  77581. };
  77582. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77583. this._taskState = AssetTaskState.ERROR;
  77584. this._errorObject = {
  77585. message: message,
  77586. exception: exception
  77587. };
  77588. if (this.onError) {
  77589. this.onError(this, message, exception);
  77590. }
  77591. onError();
  77592. };
  77593. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77594. try {
  77595. this._taskState = AssetTaskState.DONE;
  77596. this._isCompleted = true;
  77597. if (this.onSuccess) {
  77598. this.onSuccess(this);
  77599. }
  77600. onSuccess();
  77601. }
  77602. catch (e) {
  77603. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77604. }
  77605. };
  77606. return AbstractAssetTask;
  77607. }());
  77608. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77609. /**
  77610. * Class used to share progress information about assets loading
  77611. */
  77612. var AssetsProgressEvent = /** @class */ (function () {
  77613. /**
  77614. * Creates a {BABYLON.AssetsProgressEvent}
  77615. * @param remainingCount defines the number of remaining tasks to process
  77616. * @param totalCount defines the total number of tasks
  77617. * @param task defines the task that was just processed
  77618. */
  77619. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77620. this.remainingCount = remainingCount;
  77621. this.totalCount = totalCount;
  77622. this.task = task;
  77623. }
  77624. return AssetsProgressEvent;
  77625. }());
  77626. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77627. /**
  77628. * Define a task used by {BABYLON.AssetsManager} to load meshes
  77629. */
  77630. var MeshAssetTask = /** @class */ (function (_super) {
  77631. __extends(MeshAssetTask, _super);
  77632. /**
  77633. * Creates a new {BABYLON.MeshAssetTask}
  77634. * @param name defines the name of the task
  77635. * @param meshesNames defines the list of mesh's names you want to load
  77636. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  77637. * @param sceneFilename defines the filename of the scene to load from
  77638. */
  77639. function MeshAssetTask(
  77640. /**
  77641. * Defines the name of the task
  77642. */
  77643. name,
  77644. /**
  77645. * Defines the list of mesh's names you want to load
  77646. */
  77647. meshesNames,
  77648. /**
  77649. * Defines the root url to use as a base to load your meshes and associated resources
  77650. */
  77651. rootUrl,
  77652. /**
  77653. * Defines the filename of the scene to load from
  77654. */
  77655. sceneFilename) {
  77656. var _this = _super.call(this, name) || this;
  77657. _this.name = name;
  77658. _this.meshesNames = meshesNames;
  77659. _this.rootUrl = rootUrl;
  77660. _this.sceneFilename = sceneFilename;
  77661. return _this;
  77662. }
  77663. /**
  77664. * Execute the current task
  77665. * @param scene defines the scene where you want your assets to be loaded
  77666. * @param onSuccess is a callback called when the task is successfully executed
  77667. * @param onError is a callback called if an error occurs
  77668. */
  77669. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77670. var _this = this;
  77671. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77672. _this.loadedMeshes = meshes;
  77673. _this.loadedParticleSystems = particleSystems;
  77674. _this.loadedSkeletons = skeletons;
  77675. onSuccess();
  77676. }, null, function (scene, message, exception) {
  77677. onError(message, exception);
  77678. });
  77679. };
  77680. return MeshAssetTask;
  77681. }(AbstractAssetTask));
  77682. BABYLON.MeshAssetTask = MeshAssetTask;
  77683. /**
  77684. * Define a task used by {BABYLON.AssetsManager} to load text content
  77685. */
  77686. var TextFileAssetTask = /** @class */ (function (_super) {
  77687. __extends(TextFileAssetTask, _super);
  77688. /**
  77689. * Creates a new TextFileAssetTask object
  77690. * @param name defines the name of the task
  77691. * @param url defines the location of the file to load
  77692. */
  77693. function TextFileAssetTask(
  77694. /**
  77695. * Defines the name of the task
  77696. */
  77697. name,
  77698. /**
  77699. * Defines the location of the file to load
  77700. */
  77701. url) {
  77702. var _this = _super.call(this, name) || this;
  77703. _this.name = name;
  77704. _this.url = url;
  77705. return _this;
  77706. }
  77707. /**
  77708. * Execute the current task
  77709. * @param scene defines the scene where you want your assets to be loaded
  77710. * @param onSuccess is a callback called when the task is successfully executed
  77711. * @param onError is a callback called if an error occurs
  77712. */
  77713. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77714. var _this = this;
  77715. scene._loadFile(this.url, function (data) {
  77716. _this.text = data;
  77717. onSuccess();
  77718. }, undefined, false, true, function (request, exception) {
  77719. if (request) {
  77720. onError(request.status + " " + request.statusText, exception);
  77721. }
  77722. });
  77723. };
  77724. return TextFileAssetTask;
  77725. }(AbstractAssetTask));
  77726. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77727. /**
  77728. * Define a task used by {BABYLON.AssetsManager} to load binary data
  77729. */
  77730. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77731. __extends(BinaryFileAssetTask, _super);
  77732. /**
  77733. * Creates a new BinaryFileAssetTask object
  77734. * @param name defines the name of the new task
  77735. * @param url defines the location of the file to load
  77736. */
  77737. function BinaryFileAssetTask(
  77738. /**
  77739. * Defines the name of the task
  77740. */
  77741. name,
  77742. /**
  77743. * Defines the location of the file to load
  77744. */
  77745. url) {
  77746. var _this = _super.call(this, name) || this;
  77747. _this.name = name;
  77748. _this.url = url;
  77749. return _this;
  77750. }
  77751. /**
  77752. * Execute the current task
  77753. * @param scene defines the scene where you want your assets to be loaded
  77754. * @param onSuccess is a callback called when the task is successfully executed
  77755. * @param onError is a callback called if an error occurs
  77756. */
  77757. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77758. var _this = this;
  77759. scene._loadFile(this.url, function (data) {
  77760. _this.data = data;
  77761. onSuccess();
  77762. }, undefined, true, true, function (request, exception) {
  77763. if (request) {
  77764. onError(request.status + " " + request.statusText, exception);
  77765. }
  77766. });
  77767. };
  77768. return BinaryFileAssetTask;
  77769. }(AbstractAssetTask));
  77770. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77771. /**
  77772. * Define a task used by {BABYLON.AssetsManager} to load images
  77773. */
  77774. var ImageAssetTask = /** @class */ (function (_super) {
  77775. __extends(ImageAssetTask, _super);
  77776. /**
  77777. * Creates a new ImageAssetTask
  77778. * @param name defines the name of the task
  77779. * @param url defines the location of the image to load
  77780. */
  77781. function ImageAssetTask(
  77782. /**
  77783. * Defines the name of the task
  77784. */
  77785. name,
  77786. /**
  77787. * Defines the location of the image to load
  77788. */
  77789. url) {
  77790. var _this = _super.call(this, name) || this;
  77791. _this.name = name;
  77792. _this.url = url;
  77793. return _this;
  77794. }
  77795. /**
  77796. * Execute the current task
  77797. * @param scene defines the scene where you want your assets to be loaded
  77798. * @param onSuccess is a callback called when the task is successfully executed
  77799. * @param onError is a callback called if an error occurs
  77800. */
  77801. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77802. var _this = this;
  77803. var img = new Image();
  77804. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77805. img.onload = function () {
  77806. _this.image = img;
  77807. onSuccess();
  77808. };
  77809. img.onerror = function (err) {
  77810. onError("Error loading image", err);
  77811. };
  77812. img.src = this.url;
  77813. };
  77814. return ImageAssetTask;
  77815. }(AbstractAssetTask));
  77816. BABYLON.ImageAssetTask = ImageAssetTask;
  77817. /**
  77818. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  77819. */
  77820. var TextureAssetTask = /** @class */ (function (_super) {
  77821. __extends(TextureAssetTask, _super);
  77822. /**
  77823. * Creates a new TextureAssetTask object
  77824. * @param name defines the name of the task
  77825. * @param url defines the location of the file to load
  77826. * @param noMipmap defines if mipmap should not be generated (default is false)
  77827. * @param invertY defines if texture must be inverted on Y axis (default is false)
  77828. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77829. */
  77830. function TextureAssetTask(
  77831. /**
  77832. * Defines the name of the task
  77833. */
  77834. name,
  77835. /**
  77836. * Defines the location of the file to load
  77837. */
  77838. url,
  77839. /**
  77840. * Defines if mipmap should not be generated (default is false)
  77841. */
  77842. noMipmap,
  77843. /**
  77844. * Defines if texture must be inverted on Y axis (default is false)
  77845. */
  77846. invertY,
  77847. /**
  77848. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77849. */
  77850. samplingMode) {
  77851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77852. var _this = _super.call(this, name) || this;
  77853. _this.name = name;
  77854. _this.url = url;
  77855. _this.noMipmap = noMipmap;
  77856. _this.invertY = invertY;
  77857. _this.samplingMode = samplingMode;
  77858. return _this;
  77859. }
  77860. /**
  77861. * Execute the current task
  77862. * @param scene defines the scene where you want your assets to be loaded
  77863. * @param onSuccess is a callback called when the task is successfully executed
  77864. * @param onError is a callback called if an error occurs
  77865. */
  77866. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77867. var onload = function () {
  77868. onSuccess();
  77869. };
  77870. var onerror = function (message, exception) {
  77871. onError(message, exception);
  77872. };
  77873. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77874. };
  77875. return TextureAssetTask;
  77876. }(AbstractAssetTask));
  77877. BABYLON.TextureAssetTask = TextureAssetTask;
  77878. /**
  77879. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  77880. */
  77881. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77882. __extends(CubeTextureAssetTask, _super);
  77883. /**
  77884. * Creates a new CubeTextureAssetTask
  77885. * @param name defines the name of the task
  77886. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77887. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77888. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77889. * @param files defines the explicit list of files (undefined by default)
  77890. */
  77891. function CubeTextureAssetTask(
  77892. /**
  77893. * Defines the name of the task
  77894. */
  77895. name,
  77896. /**
  77897. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77898. */
  77899. url,
  77900. /**
  77901. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77902. */
  77903. extensions,
  77904. /**
  77905. * Defines if mipmaps should not be generated (default is false)
  77906. */
  77907. noMipmap,
  77908. /**
  77909. * Defines the explicit list of files (undefined by default)
  77910. */
  77911. files) {
  77912. var _this = _super.call(this, name) || this;
  77913. _this.name = name;
  77914. _this.url = url;
  77915. _this.extensions = extensions;
  77916. _this.noMipmap = noMipmap;
  77917. _this.files = files;
  77918. return _this;
  77919. }
  77920. /**
  77921. * Execute the current task
  77922. * @param scene defines the scene where you want your assets to be loaded
  77923. * @param onSuccess is a callback called when the task is successfully executed
  77924. * @param onError is a callback called if an error occurs
  77925. */
  77926. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77927. var onload = function () {
  77928. onSuccess();
  77929. };
  77930. var onerror = function (message, exception) {
  77931. onError(message, exception);
  77932. };
  77933. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77934. };
  77935. return CubeTextureAssetTask;
  77936. }(AbstractAssetTask));
  77937. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77938. /**
  77939. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  77940. */
  77941. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77942. __extends(HDRCubeTextureAssetTask, _super);
  77943. /**
  77944. * Creates a new HDRCubeTextureAssetTask object
  77945. * @param name defines the name of the task
  77946. * @param url defines the location of the file to load
  77947. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  77948. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77949. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77950. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  77951. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77952. */
  77953. function HDRCubeTextureAssetTask(
  77954. /**
  77955. * Defines the name of the task
  77956. */
  77957. name,
  77958. /**
  77959. * Defines the location of the file to load
  77960. */
  77961. url,
  77962. /**
  77963. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  77964. */
  77965. size,
  77966. /**
  77967. * Defines if mipmaps should not be generated (default is false)
  77968. */
  77969. noMipmap,
  77970. /**
  77971. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77972. */
  77973. generateHarmonics,
  77974. /**
  77975. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  77976. */
  77977. useInGammaSpace,
  77978. /**
  77979. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77980. */
  77981. usePMREMGenerator) {
  77982. if (noMipmap === void 0) { noMipmap = false; }
  77983. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77984. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77985. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77986. var _this = _super.call(this, name) || this;
  77987. _this.name = name;
  77988. _this.url = url;
  77989. _this.size = size;
  77990. _this.noMipmap = noMipmap;
  77991. _this.generateHarmonics = generateHarmonics;
  77992. _this.useInGammaSpace = useInGammaSpace;
  77993. _this.usePMREMGenerator = usePMREMGenerator;
  77994. return _this;
  77995. }
  77996. /**
  77997. * Execute the current task
  77998. * @param scene defines the scene where you want your assets to be loaded
  77999. * @param onSuccess is a callback called when the task is successfully executed
  78000. * @param onError is a callback called if an error occurs
  78001. */
  78002. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  78003. var onload = function () {
  78004. onSuccess();
  78005. };
  78006. var onerror = function (message, exception) {
  78007. onError(message, exception);
  78008. };
  78009. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  78010. };
  78011. return HDRCubeTextureAssetTask;
  78012. }(AbstractAssetTask));
  78013. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  78014. /**
  78015. * This class can be used to easily import assets into a scene
  78016. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  78017. */
  78018. var AssetsManager = /** @class */ (function () {
  78019. /**
  78020. * Creates a new AssetsManager
  78021. * @param scene defines the scene to work on
  78022. */
  78023. function AssetsManager(scene) {
  78024. this._isLoading = false;
  78025. this._tasks = new Array();
  78026. this._waitingTasksCount = 0;
  78027. this._totalTasksCount = 0;
  78028. /**
  78029. * Observable called when all tasks are processed
  78030. */
  78031. this.onTaskSuccessObservable = new BABYLON.Observable();
  78032. /**
  78033. * Observable called when a task had an error
  78034. */
  78035. this.onTaskErrorObservable = new BABYLON.Observable();
  78036. /**
  78037. * Observable called when a task is successful
  78038. */
  78039. this.onTasksDoneObservable = new BABYLON.Observable();
  78040. /**
  78041. * Observable called when a task is done (whatever the result is)
  78042. */
  78043. this.onProgressObservable = new BABYLON.Observable();
  78044. /**
  78045. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  78046. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  78047. */
  78048. this.useDefaultLoadingScreen = true;
  78049. this._scene = scene;
  78050. }
  78051. /**
  78052. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  78053. * @param taskName defines the name of the new task
  78054. * @param meshesNames defines the name of meshes to load
  78055. * @param rootUrl defines the root url to use to locate files
  78056. * @param sceneFilename defines the filename of the scene file
  78057. * @returns a new {BABYLON.MeshAssetTask} object
  78058. */
  78059. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  78060. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  78061. this._tasks.push(task);
  78062. return task;
  78063. };
  78064. /**
  78065. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  78066. * @param taskName defines the name of the new task
  78067. * @param url defines the url of the file to load
  78068. * @returns a new {BABYLON.TextFileAssetTask} object
  78069. */
  78070. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  78071. var task = new TextFileAssetTask(taskName, url);
  78072. this._tasks.push(task);
  78073. return task;
  78074. };
  78075. /**
  78076. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  78077. * @param taskName defines the name of the new task
  78078. * @param url defines the url of the file to load
  78079. * @returns a new {BABYLON.BinaryFileAssetTask} object
  78080. */
  78081. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  78082. var task = new BinaryFileAssetTask(taskName, url);
  78083. this._tasks.push(task);
  78084. return task;
  78085. };
  78086. /**
  78087. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  78088. * @param taskName defines the name of the new task
  78089. * @param url defines the url of the file to load
  78090. * @returns a new {BABYLON.ImageAssetTask} object
  78091. */
  78092. AssetsManager.prototype.addImageTask = function (taskName, url) {
  78093. var task = new ImageAssetTask(taskName, url);
  78094. this._tasks.push(task);
  78095. return task;
  78096. };
  78097. /**
  78098. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  78099. * @param taskName defines the name of the new task
  78100. * @param url defines the url of the file to load
  78101. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78102. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  78103. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  78104. * @returns a new {BABYLON.TextureAssetTask} object
  78105. */
  78106. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  78107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  78108. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  78109. this._tasks.push(task);
  78110. return task;
  78111. };
  78112. /**
  78113. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  78114. * @param taskName defines the name of the new task
  78115. * @param url defines the url of the file to load
  78116. * @param extensions defines the extension to use to load the cube map (can be null)
  78117. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78118. * @param files defines the list of files to load (can be null)
  78119. * @returns a new {BABYLON.CubeTextureAssetTask} object
  78120. */
  78121. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  78122. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  78123. this._tasks.push(task);
  78124. return task;
  78125. };
  78126. /**
  78127. *
  78128. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  78129. * @param taskName defines the name of the new task
  78130. * @param url defines the url of the file to load
  78131. * @param size defines the size you want for the cubemap (can be null)
  78132. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78133. * @param generateHarmonics defines if you want to automatically generate (true by default)
  78134. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  78135. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  78136. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  78137. */
  78138. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  78139. if (noMipmap === void 0) { noMipmap = false; }
  78140. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78141. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78142. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78143. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  78144. this._tasks.push(task);
  78145. return task;
  78146. };
  78147. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  78148. var _this = this;
  78149. this._waitingTasksCount--;
  78150. try {
  78151. if (task.taskState === AssetTaskState.DONE) {
  78152. // Let's remove successfull tasks
  78153. BABYLON.Tools.SetImmediate(function () {
  78154. var index = _this._tasks.indexOf(task);
  78155. if (index > -1) {
  78156. _this._tasks.splice(index, 1);
  78157. }
  78158. });
  78159. }
  78160. if (this.onProgress) {
  78161. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  78162. }
  78163. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  78164. }
  78165. catch (e) {
  78166. BABYLON.Tools.Error("Error running progress callbacks.");
  78167. console.log(e);
  78168. }
  78169. if (this._waitingTasksCount === 0) {
  78170. try {
  78171. if (this.onFinish) {
  78172. this.onFinish(this._tasks);
  78173. }
  78174. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78175. }
  78176. catch (e) {
  78177. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  78178. console.log(e);
  78179. }
  78180. this._isLoading = false;
  78181. this._scene.getEngine().hideLoadingUI();
  78182. }
  78183. };
  78184. AssetsManager.prototype._runTask = function (task) {
  78185. var _this = this;
  78186. var done = function () {
  78187. try {
  78188. if (_this.onTaskSuccess) {
  78189. _this.onTaskSuccess(task);
  78190. }
  78191. _this.onTaskSuccessObservable.notifyObservers(task);
  78192. _this._decreaseWaitingTasksCount(task);
  78193. }
  78194. catch (e) {
  78195. error("Error executing task success callbacks", e);
  78196. }
  78197. };
  78198. var error = function (message, exception) {
  78199. task._setErrorObject(message, exception);
  78200. if (_this.onTaskError) {
  78201. _this.onTaskError(task);
  78202. }
  78203. _this.onTaskErrorObservable.notifyObservers(task);
  78204. _this._decreaseWaitingTasksCount(task);
  78205. };
  78206. task.run(this._scene, done, error);
  78207. };
  78208. /**
  78209. * Reset the {BABYLON.AssetsManager} and remove all tasks
  78210. * @return the current instance of the {BABYLON.AssetsManager}
  78211. */
  78212. AssetsManager.prototype.reset = function () {
  78213. this._isLoading = false;
  78214. this._tasks = new Array();
  78215. return this;
  78216. };
  78217. /**
  78218. * Start the loading process
  78219. * @return the current instance of the {BABYLON.AssetsManager}
  78220. */
  78221. AssetsManager.prototype.load = function () {
  78222. if (this._isLoading) {
  78223. return this;
  78224. }
  78225. this._isLoading = true;
  78226. this._waitingTasksCount = this._tasks.length;
  78227. this._totalTasksCount = this._tasks.length;
  78228. if (this._waitingTasksCount === 0) {
  78229. if (this.onFinish) {
  78230. this.onFinish(this._tasks);
  78231. }
  78232. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78233. return this;
  78234. }
  78235. if (this.useDefaultLoadingScreen) {
  78236. this._scene.getEngine().displayLoadingUI();
  78237. }
  78238. for (var index = 0; index < this._tasks.length; index++) {
  78239. var task = this._tasks[index];
  78240. this._runTask(task);
  78241. }
  78242. return this;
  78243. };
  78244. return AssetsManager;
  78245. }());
  78246. BABYLON.AssetsManager = AssetsManager;
  78247. })(BABYLON || (BABYLON = {}));
  78248. //# sourceMappingURL=babylon.assetsManager.js.map
  78249. var BABYLON;
  78250. (function (BABYLON) {
  78251. var serializedGeometries = [];
  78252. var serializeGeometry = function (geometry, serializationGeometries) {
  78253. if (serializedGeometries[geometry.id]) {
  78254. return;
  78255. }
  78256. if (geometry.doNotSerialize) {
  78257. return;
  78258. }
  78259. if (geometry instanceof BABYLON.BoxGeometry) {
  78260. serializationGeometries.boxes.push(geometry.serialize());
  78261. }
  78262. else if (geometry instanceof BABYLON.SphereGeometry) {
  78263. serializationGeometries.spheres.push(geometry.serialize());
  78264. }
  78265. else if (geometry instanceof BABYLON.CylinderGeometry) {
  78266. serializationGeometries.cylinders.push(geometry.serialize());
  78267. }
  78268. else if (geometry instanceof BABYLON.TorusGeometry) {
  78269. serializationGeometries.toruses.push(geometry.serialize());
  78270. }
  78271. else if (geometry instanceof BABYLON.GroundGeometry) {
  78272. serializationGeometries.grounds.push(geometry.serialize());
  78273. }
  78274. else if (geometry instanceof BABYLON.Plane) {
  78275. serializationGeometries.planes.push(geometry.serialize());
  78276. }
  78277. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  78278. serializationGeometries.torusKnots.push(geometry.serialize());
  78279. }
  78280. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  78281. throw new Error("Unknown primitive type");
  78282. }
  78283. else {
  78284. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  78285. }
  78286. serializedGeometries[geometry.id] = true;
  78287. };
  78288. var serializeMesh = function (mesh, serializationScene) {
  78289. var serializationObject = {};
  78290. // Geometry
  78291. var geometry = mesh._geometry;
  78292. if (geometry) {
  78293. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  78294. // 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
  78295. serializeGeometry(geometry, serializationScene.geometries);
  78296. }
  78297. }
  78298. // Custom
  78299. if (mesh.serialize) {
  78300. mesh.serialize(serializationObject);
  78301. }
  78302. return serializationObject;
  78303. };
  78304. var finalizeSingleMesh = function (mesh, serializationObject) {
  78305. //only works if the mesh is already loaded
  78306. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78307. //serialize material
  78308. if (mesh.material) {
  78309. if (mesh.material instanceof BABYLON.StandardMaterial) {
  78310. serializationObject.materials = serializationObject.materials || [];
  78311. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78312. serializationObject.materials.push(mesh.material.serialize());
  78313. }
  78314. }
  78315. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78316. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78317. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78318. serializationObject.multiMaterials.push(mesh.material.serialize());
  78319. }
  78320. }
  78321. }
  78322. //serialize geometry
  78323. var geometry = mesh._geometry;
  78324. if (geometry) {
  78325. if (!serializationObject.geometries) {
  78326. serializationObject.geometries = {};
  78327. serializationObject.geometries.boxes = [];
  78328. serializationObject.geometries.spheres = [];
  78329. serializationObject.geometries.cylinders = [];
  78330. serializationObject.geometries.toruses = [];
  78331. serializationObject.geometries.grounds = [];
  78332. serializationObject.geometries.planes = [];
  78333. serializationObject.geometries.torusKnots = [];
  78334. serializationObject.geometries.vertexData = [];
  78335. }
  78336. serializeGeometry(geometry, serializationObject.geometries);
  78337. }
  78338. // Skeletons
  78339. if (mesh.skeleton) {
  78340. serializationObject.skeletons = serializationObject.skeletons || [];
  78341. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78342. }
  78343. //serialize the actual mesh
  78344. serializationObject.meshes = serializationObject.meshes || [];
  78345. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78346. }
  78347. };
  78348. var SceneSerializer = /** @class */ (function () {
  78349. function SceneSerializer() {
  78350. }
  78351. SceneSerializer.ClearCache = function () {
  78352. serializedGeometries = [];
  78353. };
  78354. SceneSerializer.Serialize = function (scene) {
  78355. var serializationObject = {};
  78356. SceneSerializer.ClearCache();
  78357. // Scene
  78358. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78359. serializationObject.autoClear = scene.autoClear;
  78360. serializationObject.clearColor = scene.clearColor.asArray();
  78361. serializationObject.ambientColor = scene.ambientColor.asArray();
  78362. serializationObject.gravity = scene.gravity.asArray();
  78363. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78364. serializationObject.workerCollisions = scene.workerCollisions;
  78365. // Fog
  78366. if (scene.fogMode && scene.fogMode !== 0) {
  78367. serializationObject.fogMode = scene.fogMode;
  78368. serializationObject.fogColor = scene.fogColor.asArray();
  78369. serializationObject.fogStart = scene.fogStart;
  78370. serializationObject.fogEnd = scene.fogEnd;
  78371. serializationObject.fogDensity = scene.fogDensity;
  78372. }
  78373. //Physics
  78374. if (scene.isPhysicsEnabled()) {
  78375. var physicEngine = scene.getPhysicsEngine();
  78376. if (physicEngine) {
  78377. serializationObject.physicsEnabled = true;
  78378. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78379. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78380. }
  78381. }
  78382. // Metadata
  78383. if (scene.metadata) {
  78384. serializationObject.metadata = scene.metadata;
  78385. }
  78386. // Morph targets
  78387. serializationObject.morphTargetManagers = [];
  78388. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78389. var abstractMesh = _a[_i];
  78390. var manager = abstractMesh.morphTargetManager;
  78391. if (manager) {
  78392. serializationObject.morphTargetManagers.push(manager.serialize());
  78393. }
  78394. }
  78395. // Lights
  78396. serializationObject.lights = [];
  78397. var index;
  78398. var light;
  78399. for (index = 0; index < scene.lights.length; index++) {
  78400. light = scene.lights[index];
  78401. if (!light.doNotSerialize) {
  78402. serializationObject.lights.push(light.serialize());
  78403. }
  78404. }
  78405. // Cameras
  78406. serializationObject.cameras = [];
  78407. for (index = 0; index < scene.cameras.length; index++) {
  78408. var camera = scene.cameras[index];
  78409. if (!camera.doNotSerialize) {
  78410. serializationObject.cameras.push(camera.serialize());
  78411. }
  78412. }
  78413. if (scene.activeCamera) {
  78414. serializationObject.activeCameraID = scene.activeCamera.id;
  78415. }
  78416. // Animations
  78417. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78418. // Materials
  78419. serializationObject.materials = [];
  78420. serializationObject.multiMaterials = [];
  78421. var material;
  78422. for (index = 0; index < scene.materials.length; index++) {
  78423. material = scene.materials[index];
  78424. if (!material.doNotSerialize) {
  78425. serializationObject.materials.push(material.serialize());
  78426. }
  78427. }
  78428. // MultiMaterials
  78429. serializationObject.multiMaterials = [];
  78430. for (index = 0; index < scene.multiMaterials.length; index++) {
  78431. var multiMaterial = scene.multiMaterials[index];
  78432. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78433. }
  78434. // Environment texture
  78435. if (scene.environmentTexture) {
  78436. serializationObject.environmentTexture = scene.environmentTexture.name;
  78437. }
  78438. // Skeletons
  78439. serializationObject.skeletons = [];
  78440. for (index = 0; index < scene.skeletons.length; index++) {
  78441. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78442. }
  78443. // Transform nodes
  78444. serializationObject.transformNodes = [];
  78445. for (index = 0; index < scene.transformNodes.length; index++) {
  78446. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78447. }
  78448. // Geometries
  78449. serializationObject.geometries = {};
  78450. serializationObject.geometries.boxes = [];
  78451. serializationObject.geometries.spheres = [];
  78452. serializationObject.geometries.cylinders = [];
  78453. serializationObject.geometries.toruses = [];
  78454. serializationObject.geometries.grounds = [];
  78455. serializationObject.geometries.planes = [];
  78456. serializationObject.geometries.torusKnots = [];
  78457. serializationObject.geometries.vertexData = [];
  78458. serializedGeometries = [];
  78459. var geometries = scene.getGeometries();
  78460. for (index = 0; index < geometries.length; index++) {
  78461. var geometry = geometries[index];
  78462. if (geometry.isReady()) {
  78463. serializeGeometry(geometry, serializationObject.geometries);
  78464. }
  78465. }
  78466. // Meshes
  78467. serializationObject.meshes = [];
  78468. for (index = 0; index < scene.meshes.length; index++) {
  78469. var abstractMesh = scene.meshes[index];
  78470. if (abstractMesh instanceof BABYLON.Mesh) {
  78471. var mesh = abstractMesh;
  78472. if (!mesh.doNotSerialize) {
  78473. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78474. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78475. }
  78476. }
  78477. }
  78478. }
  78479. // Particles Systems
  78480. serializationObject.particleSystems = [];
  78481. for (index = 0; index < scene.particleSystems.length; index++) {
  78482. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78483. }
  78484. // Lens flares
  78485. serializationObject.lensFlareSystems = [];
  78486. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78487. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78488. }
  78489. // Shadows
  78490. serializationObject.shadowGenerators = [];
  78491. for (index = 0; index < scene.lights.length; index++) {
  78492. light = scene.lights[index];
  78493. var shadowGenerator = light.getShadowGenerator();
  78494. if (shadowGenerator) {
  78495. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78496. }
  78497. }
  78498. // Action Manager
  78499. if (scene.actionManager) {
  78500. serializationObject.actions = scene.actionManager.serialize("scene");
  78501. }
  78502. // Audio
  78503. serializationObject.sounds = [];
  78504. for (index = 0; index < scene.soundTracks.length; index++) {
  78505. var soundtrack = scene.soundTracks[index];
  78506. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78507. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78508. }
  78509. }
  78510. return serializationObject;
  78511. };
  78512. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78513. if (withParents === void 0) { withParents = false; }
  78514. if (withChildren === void 0) { withChildren = false; }
  78515. var serializationObject = {};
  78516. SceneSerializer.ClearCache();
  78517. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78518. if (withParents || withChildren) {
  78519. //deliberate for loop! not for each, appended should be processed as well.
  78520. for (var i = 0; i < toSerialize.length; ++i) {
  78521. if (withChildren) {
  78522. toSerialize[i].getDescendants().forEach(function (node) {
  78523. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78524. toSerialize.push(node);
  78525. }
  78526. });
  78527. }
  78528. //make sure the array doesn't contain the object already
  78529. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78530. toSerialize.push(toSerialize[i].parent);
  78531. }
  78532. }
  78533. }
  78534. toSerialize.forEach(function (mesh) {
  78535. finalizeSingleMesh(mesh, serializationObject);
  78536. });
  78537. return serializationObject;
  78538. };
  78539. return SceneSerializer;
  78540. }());
  78541. BABYLON.SceneSerializer = SceneSerializer;
  78542. })(BABYLON || (BABYLON = {}));
  78543. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78544. var BABYLON;
  78545. (function (BABYLON) {
  78546. var ReflectionProbe = /** @class */ (function () {
  78547. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78549. var _this = this;
  78550. this.name = name;
  78551. this._viewMatrix = BABYLON.Matrix.Identity();
  78552. this._target = BABYLON.Vector3.Zero();
  78553. this._add = BABYLON.Vector3.Zero();
  78554. this.invertYAxis = false;
  78555. this.position = BABYLON.Vector3.Zero();
  78556. this._scene = scene;
  78557. this._scene.reflectionProbes.push(this);
  78558. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78559. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78560. switch (faceIndex) {
  78561. case 0:
  78562. _this._add.copyFromFloats(1, 0, 0);
  78563. break;
  78564. case 1:
  78565. _this._add.copyFromFloats(-1, 0, 0);
  78566. break;
  78567. case 2:
  78568. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78569. break;
  78570. case 3:
  78571. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78572. break;
  78573. case 4:
  78574. _this._add.copyFromFloats(0, 0, 1);
  78575. break;
  78576. case 5:
  78577. _this._add.copyFromFloats(0, 0, -1);
  78578. break;
  78579. }
  78580. if (_this._attachedMesh) {
  78581. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78582. }
  78583. _this.position.addToRef(_this._add, _this._target);
  78584. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78585. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78586. scene._forcedViewPosition = _this.position;
  78587. });
  78588. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78589. scene._forcedViewPosition = null;
  78590. scene.updateTransformMatrix(true);
  78591. });
  78592. if (scene.activeCamera) {
  78593. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78594. }
  78595. }
  78596. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78597. get: function () {
  78598. return this._renderTargetTexture.samples;
  78599. },
  78600. set: function (value) {
  78601. this._renderTargetTexture.samples = value;
  78602. },
  78603. enumerable: true,
  78604. configurable: true
  78605. });
  78606. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78607. get: function () {
  78608. return this._renderTargetTexture.refreshRate;
  78609. },
  78610. set: function (value) {
  78611. this._renderTargetTexture.refreshRate = value;
  78612. },
  78613. enumerable: true,
  78614. configurable: true
  78615. });
  78616. ReflectionProbe.prototype.getScene = function () {
  78617. return this._scene;
  78618. };
  78619. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78620. get: function () {
  78621. return this._renderTargetTexture;
  78622. },
  78623. enumerable: true,
  78624. configurable: true
  78625. });
  78626. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78627. get: function () {
  78628. return this._renderTargetTexture.renderList;
  78629. },
  78630. enumerable: true,
  78631. configurable: true
  78632. });
  78633. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78634. this._attachedMesh = mesh;
  78635. };
  78636. /**
  78637. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78638. *
  78639. * @param renderingGroupId The rendering group id corresponding to its index
  78640. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78641. */
  78642. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78643. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78644. };
  78645. ReflectionProbe.prototype.dispose = function () {
  78646. var index = this._scene.reflectionProbes.indexOf(this);
  78647. if (index !== -1) {
  78648. // Remove from the scene if found
  78649. this._scene.reflectionProbes.splice(index, 1);
  78650. }
  78651. if (this._renderTargetTexture) {
  78652. this._renderTargetTexture.dispose();
  78653. this._renderTargetTexture = null;
  78654. }
  78655. };
  78656. return ReflectionProbe;
  78657. }());
  78658. BABYLON.ReflectionProbe = ReflectionProbe;
  78659. })(BABYLON || (BABYLON = {}));
  78660. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78661. var BABYLON;
  78662. (function (BABYLON) {
  78663. var Layer = /** @class */ (function () {
  78664. function Layer(name, imgUrl, scene, isBackground, color) {
  78665. this.name = name;
  78666. this.scale = new BABYLON.Vector2(1, 1);
  78667. this.offset = new BABYLON.Vector2(0, 0);
  78668. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78669. this.layerMask = 0x0FFFFFFF;
  78670. this._vertexBuffers = {};
  78671. // Events
  78672. /**
  78673. * An event triggered when the layer is disposed.
  78674. * @type {BABYLON.Observable}
  78675. */
  78676. this.onDisposeObservable = new BABYLON.Observable();
  78677. /**
  78678. * An event triggered before rendering the scene
  78679. * @type {BABYLON.Observable}
  78680. */
  78681. this.onBeforeRenderObservable = new BABYLON.Observable();
  78682. /**
  78683. * An event triggered after rendering the scene
  78684. * @type {BABYLON.Observable}
  78685. */
  78686. this.onAfterRenderObservable = new BABYLON.Observable();
  78687. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78688. this.isBackground = isBackground === undefined ? true : isBackground;
  78689. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78690. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78691. this._scene.layers.push(this);
  78692. var engine = this._scene.getEngine();
  78693. // VBO
  78694. var vertices = [];
  78695. vertices.push(1, 1);
  78696. vertices.push(-1, 1);
  78697. vertices.push(-1, -1);
  78698. vertices.push(1, -1);
  78699. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78701. this._createIndexBuffer();
  78702. // Effects
  78703. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78704. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78705. }
  78706. Object.defineProperty(Layer.prototype, "onDispose", {
  78707. set: function (callback) {
  78708. if (this._onDisposeObserver) {
  78709. this.onDisposeObservable.remove(this._onDisposeObserver);
  78710. }
  78711. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78712. },
  78713. enumerable: true,
  78714. configurable: true
  78715. });
  78716. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78717. set: function (callback) {
  78718. if (this._onBeforeRenderObserver) {
  78719. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78720. }
  78721. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78722. },
  78723. enumerable: true,
  78724. configurable: true
  78725. });
  78726. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78727. set: function (callback) {
  78728. if (this._onAfterRenderObserver) {
  78729. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78730. }
  78731. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78732. },
  78733. enumerable: true,
  78734. configurable: true
  78735. });
  78736. Layer.prototype._createIndexBuffer = function () {
  78737. var engine = this._scene.getEngine();
  78738. // Indices
  78739. var indices = [];
  78740. indices.push(0);
  78741. indices.push(1);
  78742. indices.push(2);
  78743. indices.push(0);
  78744. indices.push(2);
  78745. indices.push(3);
  78746. this._indexBuffer = engine.createIndexBuffer(indices);
  78747. };
  78748. Layer.prototype._rebuild = function () {
  78749. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78750. if (vb) {
  78751. vb._rebuild();
  78752. }
  78753. this._createIndexBuffer();
  78754. };
  78755. Layer.prototype.render = function () {
  78756. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78757. // Check
  78758. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78759. return;
  78760. var engine = this._scene.getEngine();
  78761. this.onBeforeRenderObservable.notifyObservers(this);
  78762. // Render
  78763. engine.enableEffect(currentEffect);
  78764. engine.setState(false);
  78765. // Texture
  78766. currentEffect.setTexture("textureSampler", this.texture);
  78767. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78768. // Color
  78769. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78770. // Scale / offset
  78771. currentEffect.setVector2("offset", this.offset);
  78772. currentEffect.setVector2("scale", this.scale);
  78773. // VBOs
  78774. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78775. // Draw order
  78776. if (!this.alphaTest) {
  78777. engine.setAlphaMode(this.alphaBlendingMode);
  78778. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78779. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78780. }
  78781. else {
  78782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78783. }
  78784. this.onAfterRenderObservable.notifyObservers(this);
  78785. };
  78786. Layer.prototype.dispose = function () {
  78787. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78788. if (vertexBuffer) {
  78789. vertexBuffer.dispose();
  78790. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78791. }
  78792. if (this._indexBuffer) {
  78793. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78794. this._indexBuffer = null;
  78795. }
  78796. if (this.texture) {
  78797. this.texture.dispose();
  78798. this.texture = null;
  78799. }
  78800. // Remove from scene
  78801. var index = this._scene.layers.indexOf(this);
  78802. this._scene.layers.splice(index, 1);
  78803. // Callback
  78804. this.onDisposeObservable.notifyObservers(this);
  78805. this.onDisposeObservable.clear();
  78806. this.onAfterRenderObservable.clear();
  78807. this.onBeforeRenderObservable.clear();
  78808. };
  78809. return Layer;
  78810. }());
  78811. BABYLON.Layer = Layer;
  78812. })(BABYLON || (BABYLON = {}));
  78813. //# sourceMappingURL=babylon.layer.js.map
  78814. var BABYLON;
  78815. (function (BABYLON) {
  78816. var TextureTools = /** @class */ (function () {
  78817. function TextureTools() {
  78818. }
  78819. /**
  78820. * Uses the GPU to create a copy texture rescaled at a given size
  78821. * @param texture Texture to copy from
  78822. * @param width Desired width
  78823. * @param height Desired height
  78824. * @return Generated texture
  78825. */
  78826. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78827. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78828. var scene = texture.getScene();
  78829. var engine = scene.getEngine();
  78830. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78831. rtt.wrapU = texture.wrapU;
  78832. rtt.wrapV = texture.wrapV;
  78833. rtt.uOffset = texture.uOffset;
  78834. rtt.vOffset = texture.vOffset;
  78835. rtt.uScale = texture.uScale;
  78836. rtt.vScale = texture.vScale;
  78837. rtt.uAng = texture.uAng;
  78838. rtt.vAng = texture.vAng;
  78839. rtt.wAng = texture.wAng;
  78840. rtt.coordinatesIndex = texture.coordinatesIndex;
  78841. rtt.level = texture.level;
  78842. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78843. rtt._texture.isReady = false;
  78844. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78845. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78846. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78847. passPostProcess.getEffect().executeWhenCompiled(function () {
  78848. passPostProcess.onApply = function (effect) {
  78849. effect.setTexture("textureSampler", texture);
  78850. };
  78851. var internalTexture = rtt.getInternalTexture();
  78852. if (internalTexture) {
  78853. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78854. engine.unBindFramebuffer(internalTexture);
  78855. rtt.disposeFramebufferObjects();
  78856. passPostProcess.dispose();
  78857. internalTexture.isReady = true;
  78858. }
  78859. });
  78860. return rtt;
  78861. };
  78862. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78863. if (!scene._environmentBRDFTexture) {
  78864. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78865. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78866. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78867. scene._environmentBRDFTexture = texture;
  78868. }
  78869. return scene._environmentBRDFTexture;
  78870. };
  78871. 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=";
  78872. return TextureTools;
  78873. }());
  78874. BABYLON.TextureTools = TextureTools;
  78875. })(BABYLON || (BABYLON = {}));
  78876. //# sourceMappingURL=babylon.textureTools.js.map
  78877. var BABYLON;
  78878. (function (BABYLON) {
  78879. var FramingBehavior = /** @class */ (function () {
  78880. function FramingBehavior() {
  78881. this._mode = FramingBehavior.FitFrustumSidesMode;
  78882. this._radiusScale = 1.0;
  78883. this._positionScale = 0.5;
  78884. this._defaultElevation = 0.3;
  78885. this._elevationReturnTime = 1500;
  78886. this._elevationReturnWaitTime = 1000;
  78887. this._zoomStopsAnimation = false;
  78888. this._framingTime = 1500;
  78889. this._isPointerDown = false;
  78890. this._lastInteractionTime = -Infinity;
  78891. // Framing control
  78892. this._animatables = new Array();
  78893. this._betaIsAnimating = false;
  78894. }
  78895. Object.defineProperty(FramingBehavior.prototype, "name", {
  78896. get: function () {
  78897. return "Framing";
  78898. },
  78899. enumerable: true,
  78900. configurable: true
  78901. });
  78902. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78903. /**
  78904. * Gets current mode used by the behavior.
  78905. */
  78906. get: function () {
  78907. return this._mode;
  78908. },
  78909. /**
  78910. * Sets the current mode used by the behavior
  78911. */
  78912. set: function (mode) {
  78913. this._mode = mode;
  78914. },
  78915. enumerable: true,
  78916. configurable: true
  78917. });
  78918. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78919. /**
  78920. * Gets the scale applied to the radius
  78921. */
  78922. get: function () {
  78923. return this._radiusScale;
  78924. },
  78925. /**
  78926. * Sets the scale applied to the radius (1 by default)
  78927. */
  78928. set: function (radius) {
  78929. this._radiusScale = radius;
  78930. },
  78931. enumerable: true,
  78932. configurable: true
  78933. });
  78934. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78935. /**
  78936. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78937. */
  78938. get: function () {
  78939. return this._positionScale;
  78940. },
  78941. /**
  78942. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78943. */
  78944. set: function (scale) {
  78945. this._positionScale = scale;
  78946. },
  78947. enumerable: true,
  78948. configurable: true
  78949. });
  78950. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78951. /**
  78952. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78953. * behaviour is triggered, in radians.
  78954. */
  78955. get: function () {
  78956. return this._defaultElevation;
  78957. },
  78958. /**
  78959. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78960. * behaviour is triggered, in radians.
  78961. */
  78962. set: function (elevation) {
  78963. this._defaultElevation = elevation;
  78964. },
  78965. enumerable: true,
  78966. configurable: true
  78967. });
  78968. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78969. /**
  78970. * Gets the time (in milliseconds) taken to return to the default beta position.
  78971. * Negative value indicates camera should not return to default.
  78972. */
  78973. get: function () {
  78974. return this._elevationReturnTime;
  78975. },
  78976. /**
  78977. * Sets the time (in milliseconds) taken to return to the default beta position.
  78978. * Negative value indicates camera should not return to default.
  78979. */
  78980. set: function (speed) {
  78981. this._elevationReturnTime = speed;
  78982. },
  78983. enumerable: true,
  78984. configurable: true
  78985. });
  78986. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78987. /**
  78988. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78989. */
  78990. get: function () {
  78991. return this._elevationReturnWaitTime;
  78992. },
  78993. /**
  78994. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78995. */
  78996. set: function (time) {
  78997. this._elevationReturnWaitTime = time;
  78998. },
  78999. enumerable: true,
  79000. configurable: true
  79001. });
  79002. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  79003. /**
  79004. * Gets the flag that indicates if user zooming should stop animation.
  79005. */
  79006. get: function () {
  79007. return this._zoomStopsAnimation;
  79008. },
  79009. /**
  79010. * Sets the flag that indicates if user zooming should stop animation.
  79011. */
  79012. set: function (flag) {
  79013. this._zoomStopsAnimation = flag;
  79014. },
  79015. enumerable: true,
  79016. configurable: true
  79017. });
  79018. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  79019. /**
  79020. * Gets the transition time when framing the mesh, in milliseconds
  79021. */
  79022. get: function () {
  79023. return this._framingTime;
  79024. },
  79025. /**
  79026. * Sets the transition time when framing the mesh, in milliseconds
  79027. */
  79028. set: function (time) {
  79029. this._framingTime = time;
  79030. },
  79031. enumerable: true,
  79032. configurable: true
  79033. });
  79034. FramingBehavior.prototype.init = function () {
  79035. // Do notihng
  79036. };
  79037. FramingBehavior.prototype.attach = function (camera) {
  79038. var _this = this;
  79039. this._attachedCamera = camera;
  79040. var scene = this._attachedCamera.getScene();
  79041. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  79042. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79043. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79044. _this._isPointerDown = true;
  79045. return;
  79046. }
  79047. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79048. _this._isPointerDown = false;
  79049. }
  79050. });
  79051. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79052. if (mesh) {
  79053. _this.zoomOnMesh(mesh);
  79054. }
  79055. });
  79056. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79057. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79058. _this._applyUserInteraction();
  79059. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  79060. // back to the default position after a given timeout
  79061. _this._maintainCameraAboveGround();
  79062. });
  79063. };
  79064. FramingBehavior.prototype.detach = function () {
  79065. if (!this._attachedCamera) {
  79066. return;
  79067. }
  79068. var scene = this._attachedCamera.getScene();
  79069. if (this._onPrePointerObservableObserver) {
  79070. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79071. }
  79072. if (this._onAfterCheckInputsObserver) {
  79073. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79074. }
  79075. if (this._onMeshTargetChangedObserver) {
  79076. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79077. }
  79078. this._attachedCamera = null;
  79079. };
  79080. /**
  79081. * Targets the given mesh and updates zoom level accordingly.
  79082. * @param mesh The mesh to target.
  79083. * @param radius Optional. If a cached radius position already exists, overrides default.
  79084. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79085. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79086. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79087. */
  79088. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  79089. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79090. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79091. mesh.computeWorldMatrix(true);
  79092. var boundingBox = mesh.getBoundingInfo().boundingBox;
  79093. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  79094. };
  79095. /**
  79096. * Targets the given mesh with its children and updates zoom level accordingly.
  79097. * @param mesh The mesh to target.
  79098. * @param radius Optional. If a cached radius position already exists, overrides default.
  79099. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79100. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79101. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79102. */
  79103. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  79104. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79105. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79106. mesh.computeWorldMatrix(true);
  79107. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  79108. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  79109. };
  79110. /**
  79111. * Targets the given meshes with their children and updates zoom level accordingly.
  79112. * @param meshes The mesh to target.
  79113. * @param radius Optional. If a cached radius position already exists, overrides default.
  79114. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79115. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79116. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79117. */
  79118. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  79119. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79120. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79121. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  79122. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  79123. for (var i = 0; i < meshes.length; i++) {
  79124. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  79125. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  79126. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  79127. }
  79128. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  79129. };
  79130. /**
  79131. * Targets the given mesh and updates zoom level accordingly.
  79132. * @param mesh The mesh to target.
  79133. * @param radius Optional. If a cached radius position already exists, overrides default.
  79134. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79135. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79136. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79137. */
  79138. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  79139. var _this = this;
  79140. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79141. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79142. var zoomTarget;
  79143. if (!this._attachedCamera) {
  79144. return;
  79145. }
  79146. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  79147. var bottom = minimumWorld.y;
  79148. var top = maximumWorld.y;
  79149. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  79150. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  79151. if (focusOnOriginXZ) {
  79152. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  79153. }
  79154. else {
  79155. var centerWorld = minimumWorld.add(radiusWorld);
  79156. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  79157. }
  79158. if (!this._vectorTransition) {
  79159. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  79160. }
  79161. this._betaIsAnimating = true;
  79162. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  79163. if (animatable) {
  79164. this._animatables.push(animatable);
  79165. }
  79166. // sets the radius and lower radius bounds
  79167. // Small delta ensures camera is not always at lower zoom limit.
  79168. var radius = 0;
  79169. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  79170. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79171. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  79172. radius = position;
  79173. }
  79174. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79175. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79176. if (this._attachedCamera.lowerRadiusLimit === null) {
  79177. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  79178. }
  79179. }
  79180. // Set sensibilities
  79181. var extend = maximumWorld.subtract(minimumWorld).length();
  79182. this._attachedCamera.panningSensibility = 5000 / extend;
  79183. this._attachedCamera.wheelPrecision = 100 / radius;
  79184. // transition to new radius
  79185. if (!this._radiusTransition) {
  79186. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79187. }
  79188. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  79189. if (onAnimationEnd) {
  79190. onAnimationEnd();
  79191. }
  79192. if (_this._attachedCamera) {
  79193. _this._attachedCamera.storeState();
  79194. }
  79195. });
  79196. if (animatable) {
  79197. this._animatables.push(animatable);
  79198. }
  79199. };
  79200. /**
  79201. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  79202. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  79203. * frustum width.
  79204. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  79205. * to fully enclose the mesh in the viewing frustum.
  79206. */
  79207. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  79208. var size = maximumWorld.subtract(minimumWorld);
  79209. var boxVectorGlobalDiagonal = size.length();
  79210. var frustumSlope = this._getFrustumSlope();
  79211. // Formula for setting distance
  79212. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  79213. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  79214. // Horizon distance
  79215. var radius = radiusWithoutFraming * this._radiusScale;
  79216. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  79217. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  79218. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  79219. var camera = this._attachedCamera;
  79220. if (!camera) {
  79221. return 0;
  79222. }
  79223. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79224. // Don't exceed the requested limit
  79225. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  79226. }
  79227. // Don't exceed the upper radius limit
  79228. if (camera.upperRadiusLimit) {
  79229. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  79230. }
  79231. return distance;
  79232. };
  79233. /**
  79234. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  79235. * is automatically returned to its default position (expected to be above ground plane).
  79236. */
  79237. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  79238. var _this = this;
  79239. if (this._elevationReturnTime < 0) {
  79240. return;
  79241. }
  79242. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  79243. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  79244. var limitBeta = Math.PI * 0.5;
  79245. // Bring the camera back up if below the ground plane
  79246. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  79247. this._betaIsAnimating = true;
  79248. //Transition to new position
  79249. this.stopAllAnimations();
  79250. if (!this._betaTransition) {
  79251. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79252. }
  79253. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  79254. _this._clearAnimationLocks();
  79255. _this.stopAllAnimations();
  79256. });
  79257. if (animatabe) {
  79258. this._animatables.push(animatabe);
  79259. }
  79260. }
  79261. };
  79262. /**
  79263. * Returns the frustum slope based on the canvas ratio and camera FOV
  79264. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  79265. */
  79266. FramingBehavior.prototype._getFrustumSlope = function () {
  79267. // Calculate the viewport ratio
  79268. // Aspect Ratio is Height/Width.
  79269. var camera = this._attachedCamera;
  79270. if (!camera) {
  79271. return BABYLON.Vector2.Zero();
  79272. }
  79273. var engine = camera.getScene().getEngine();
  79274. var aspectRatio = engine.getAspectRatio(camera);
  79275. // Camera FOV is the vertical field of view (top-bottom) in radians.
  79276. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  79277. var frustumSlopeY = Math.tan(camera.fov / 2);
  79278. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  79279. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  79280. // along the forward vector.
  79281. var frustumSlopeX = frustumSlopeY * aspectRatio;
  79282. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  79283. };
  79284. /**
  79285. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  79286. */
  79287. FramingBehavior.prototype._clearAnimationLocks = function () {
  79288. this._betaIsAnimating = false;
  79289. };
  79290. /**
  79291. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79292. */
  79293. FramingBehavior.prototype._applyUserInteraction = function () {
  79294. if (this.isUserIsMoving) {
  79295. this._lastInteractionTime = BABYLON.Tools.Now;
  79296. this.stopAllAnimations();
  79297. this._clearAnimationLocks();
  79298. }
  79299. };
  79300. /**
  79301. * Stops and removes all animations that have been applied to the camera
  79302. */
  79303. FramingBehavior.prototype.stopAllAnimations = function () {
  79304. if (this._attachedCamera) {
  79305. this._attachedCamera.animations = [];
  79306. }
  79307. while (this._animatables.length) {
  79308. if (this._animatables[0]) {
  79309. this._animatables[0].onAnimationEnd = null;
  79310. this._animatables[0].stop();
  79311. }
  79312. this._animatables.shift();
  79313. }
  79314. };
  79315. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79316. /**
  79317. * Gets a value indicating if the user is moving the camera
  79318. */
  79319. get: function () {
  79320. if (!this._attachedCamera) {
  79321. return false;
  79322. }
  79323. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79324. this._attachedCamera.inertialBetaOffset !== 0 ||
  79325. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79326. this._attachedCamera.inertialPanningX !== 0 ||
  79327. this._attachedCamera.inertialPanningY !== 0 ||
  79328. this._isPointerDown;
  79329. },
  79330. enumerable: true,
  79331. configurable: true
  79332. });
  79333. /**
  79334. * The easing function used by animations
  79335. */
  79336. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79337. /**
  79338. * The easing mode used by animations
  79339. */
  79340. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79341. // Statics
  79342. /**
  79343. * The camera can move all the way towards the mesh.
  79344. */
  79345. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79346. /**
  79347. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79348. */
  79349. FramingBehavior.FitFrustumSidesMode = 1;
  79350. return FramingBehavior;
  79351. }());
  79352. BABYLON.FramingBehavior = FramingBehavior;
  79353. })(BABYLON || (BABYLON = {}));
  79354. //# sourceMappingURL=babylon.framingBehavior.js.map
  79355. var BABYLON;
  79356. (function (BABYLON) {
  79357. /**
  79358. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79359. */
  79360. var BouncingBehavior = /** @class */ (function () {
  79361. function BouncingBehavior() {
  79362. /**
  79363. * The duration of the animation, in milliseconds
  79364. */
  79365. this.transitionDuration = 450;
  79366. /**
  79367. * Length of the distance animated by the transition when lower radius is reached
  79368. */
  79369. this.lowerRadiusTransitionRange = 2;
  79370. /**
  79371. * Length of the distance animated by the transition when upper radius is reached
  79372. */
  79373. this.upperRadiusTransitionRange = -2;
  79374. this._autoTransitionRange = false;
  79375. // Animations
  79376. this._radiusIsAnimating = false;
  79377. this._radiusBounceTransition = null;
  79378. this._animatables = new Array();
  79379. }
  79380. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79381. get: function () {
  79382. return "Bouncing";
  79383. },
  79384. enumerable: true,
  79385. configurable: true
  79386. });
  79387. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79388. /**
  79389. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79390. */
  79391. get: function () {
  79392. return this._autoTransitionRange;
  79393. },
  79394. /**
  79395. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79396. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79397. */
  79398. set: function (value) {
  79399. var _this = this;
  79400. if (this._autoTransitionRange === value) {
  79401. return;
  79402. }
  79403. this._autoTransitionRange = value;
  79404. var camera = this._attachedCamera;
  79405. if (!camera) {
  79406. return;
  79407. }
  79408. if (value) {
  79409. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79410. if (!mesh) {
  79411. return;
  79412. }
  79413. mesh.computeWorldMatrix(true);
  79414. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79415. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79416. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79417. });
  79418. }
  79419. else if (this._onMeshTargetChangedObserver) {
  79420. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79421. }
  79422. },
  79423. enumerable: true,
  79424. configurable: true
  79425. });
  79426. BouncingBehavior.prototype.init = function () {
  79427. // Do notihng
  79428. };
  79429. BouncingBehavior.prototype.attach = function (camera) {
  79430. var _this = this;
  79431. this._attachedCamera = camera;
  79432. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79433. if (!_this._attachedCamera) {
  79434. return;
  79435. }
  79436. // Add the bounce animation to the lower radius limit
  79437. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79438. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79439. }
  79440. // Add the bounce animation to the upper radius limit
  79441. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79442. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79443. }
  79444. });
  79445. };
  79446. BouncingBehavior.prototype.detach = function () {
  79447. if (!this._attachedCamera) {
  79448. return;
  79449. }
  79450. if (this._onAfterCheckInputsObserver) {
  79451. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79452. }
  79453. if (this._onMeshTargetChangedObserver) {
  79454. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79455. }
  79456. this._attachedCamera = null;
  79457. };
  79458. /**
  79459. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79460. * @param radiusLimit The limit to check against.
  79461. * @return Bool to indicate if at limit.
  79462. */
  79463. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79464. if (!this._attachedCamera) {
  79465. return false;
  79466. }
  79467. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79468. return true;
  79469. }
  79470. return false;
  79471. };
  79472. /**
  79473. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79474. * @param radiusDelta The delta by which to animate to. Can be negative.
  79475. */
  79476. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79477. var _this = this;
  79478. if (!this._attachedCamera) {
  79479. return;
  79480. }
  79481. if (!this._radiusBounceTransition) {
  79482. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79483. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79484. }
  79485. // Prevent zoom until bounce has completed
  79486. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79487. this._attachedCamera.wheelPrecision = Infinity;
  79488. this._attachedCamera.inertialRadiusOffset = 0;
  79489. // Animate to the radius limit
  79490. this.stopAllAnimations();
  79491. this._radiusIsAnimating = true;
  79492. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79493. if (animatable) {
  79494. this._animatables.push(animatable);
  79495. }
  79496. };
  79497. /**
  79498. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79499. */
  79500. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79501. this._radiusIsAnimating = false;
  79502. if (this._attachedCamera) {
  79503. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79504. }
  79505. };
  79506. /**
  79507. * Stops and removes all animations that have been applied to the camera
  79508. */
  79509. BouncingBehavior.prototype.stopAllAnimations = function () {
  79510. if (this._attachedCamera) {
  79511. this._attachedCamera.animations = [];
  79512. }
  79513. while (this._animatables.length) {
  79514. this._animatables[0].onAnimationEnd = null;
  79515. this._animatables[0].stop();
  79516. this._animatables.shift();
  79517. }
  79518. };
  79519. /**
  79520. * The easing function used by animations
  79521. */
  79522. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79523. /**
  79524. * The easing mode used by animations
  79525. */
  79526. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79527. return BouncingBehavior;
  79528. }());
  79529. BABYLON.BouncingBehavior = BouncingBehavior;
  79530. })(BABYLON || (BABYLON = {}));
  79531. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79532. var BABYLON;
  79533. (function (BABYLON) {
  79534. var AutoRotationBehavior = /** @class */ (function () {
  79535. function AutoRotationBehavior() {
  79536. this._zoomStopsAnimation = false;
  79537. this._idleRotationSpeed = 0.05;
  79538. this._idleRotationWaitTime = 2000;
  79539. this._idleRotationSpinupTime = 2000;
  79540. this._isPointerDown = false;
  79541. this._lastFrameTime = null;
  79542. this._lastInteractionTime = -Infinity;
  79543. this._cameraRotationSpeed = 0;
  79544. this._lastFrameRadius = 0;
  79545. }
  79546. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79547. get: function () {
  79548. return "AutoRotation";
  79549. },
  79550. enumerable: true,
  79551. configurable: true
  79552. });
  79553. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79554. /**
  79555. * Gets the flag that indicates if user zooming should stop animation.
  79556. */
  79557. get: function () {
  79558. return this._zoomStopsAnimation;
  79559. },
  79560. /**
  79561. * Sets the flag that indicates if user zooming should stop animation.
  79562. */
  79563. set: function (flag) {
  79564. this._zoomStopsAnimation = flag;
  79565. },
  79566. enumerable: true,
  79567. configurable: true
  79568. });
  79569. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79570. /**
  79571. * Gets the default speed at which the camera rotates around the model.
  79572. */
  79573. get: function () {
  79574. return this._idleRotationSpeed;
  79575. },
  79576. /**
  79577. * Sets the default speed at which the camera rotates around the model.
  79578. */
  79579. set: function (speed) {
  79580. this._idleRotationSpeed = speed;
  79581. },
  79582. enumerable: true,
  79583. configurable: true
  79584. });
  79585. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79586. /**
  79587. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79588. */
  79589. get: function () {
  79590. return this._idleRotationWaitTime;
  79591. },
  79592. /**
  79593. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79594. */
  79595. set: function (time) {
  79596. this._idleRotationWaitTime = time;
  79597. },
  79598. enumerable: true,
  79599. configurable: true
  79600. });
  79601. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79602. /**
  79603. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79604. */
  79605. get: function () {
  79606. return this._idleRotationSpinupTime;
  79607. },
  79608. /**
  79609. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79610. */
  79611. set: function (time) {
  79612. this._idleRotationSpinupTime = time;
  79613. },
  79614. enumerable: true,
  79615. configurable: true
  79616. });
  79617. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79618. /**
  79619. * Gets a value indicating if the camera is currently rotating because of this behavior
  79620. */
  79621. get: function () {
  79622. return Math.abs(this._cameraRotationSpeed) > 0;
  79623. },
  79624. enumerable: true,
  79625. configurable: true
  79626. });
  79627. AutoRotationBehavior.prototype.init = function () {
  79628. // Do notihng
  79629. };
  79630. AutoRotationBehavior.prototype.attach = function (camera) {
  79631. var _this = this;
  79632. this._attachedCamera = camera;
  79633. var scene = this._attachedCamera.getScene();
  79634. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79635. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79636. _this._isPointerDown = true;
  79637. return;
  79638. }
  79639. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79640. _this._isPointerDown = false;
  79641. }
  79642. });
  79643. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79644. var now = BABYLON.Tools.Now;
  79645. var dt = 0;
  79646. if (_this._lastFrameTime != null) {
  79647. dt = now - _this._lastFrameTime;
  79648. }
  79649. _this._lastFrameTime = now;
  79650. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79651. _this._applyUserInteraction();
  79652. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79653. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79654. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79655. // Step camera rotation by rotation speed
  79656. if (_this._attachedCamera) {
  79657. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79658. }
  79659. });
  79660. };
  79661. AutoRotationBehavior.prototype.detach = function () {
  79662. if (!this._attachedCamera) {
  79663. return;
  79664. }
  79665. var scene = this._attachedCamera.getScene();
  79666. if (this._onPrePointerObservableObserver) {
  79667. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79668. }
  79669. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79670. this._attachedCamera = null;
  79671. };
  79672. /**
  79673. * Returns true if user is scrolling.
  79674. * @return true if user is scrolling.
  79675. */
  79676. AutoRotationBehavior.prototype._userIsZooming = function () {
  79677. if (!this._attachedCamera) {
  79678. return false;
  79679. }
  79680. return this._attachedCamera.inertialRadiusOffset !== 0;
  79681. };
  79682. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79683. if (!this._attachedCamera) {
  79684. return false;
  79685. }
  79686. var zoomHasHitLimit = false;
  79687. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79688. zoomHasHitLimit = true;
  79689. }
  79690. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79691. this._lastFrameRadius = this._attachedCamera.radius;
  79692. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79693. };
  79694. /**
  79695. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79696. */
  79697. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79698. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79699. this._lastInteractionTime = BABYLON.Tools.Now;
  79700. }
  79701. };
  79702. // Tools
  79703. AutoRotationBehavior.prototype._userIsMoving = function () {
  79704. if (!this._attachedCamera) {
  79705. return false;
  79706. }
  79707. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79708. this._attachedCamera.inertialBetaOffset !== 0 ||
  79709. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79710. this._attachedCamera.inertialPanningX !== 0 ||
  79711. this._attachedCamera.inertialPanningY !== 0 ||
  79712. this._isPointerDown;
  79713. };
  79714. return AutoRotationBehavior;
  79715. }());
  79716. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79717. })(BABYLON || (BABYLON = {}));
  79718. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79719. var BABYLON;
  79720. (function (BABYLON) {
  79721. /**
  79722. * This class can be used to get instrumentation data from a Babylon engine
  79723. */
  79724. var EngineInstrumentation = /** @class */ (function () {
  79725. function EngineInstrumentation(engine) {
  79726. this.engine = engine;
  79727. this._captureGPUFrameTime = false;
  79728. this._gpuFrameTime = new BABYLON.PerfCounter();
  79729. this._captureShaderCompilationTime = false;
  79730. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79731. // Observers
  79732. this._onBeginFrameObserver = null;
  79733. this._onEndFrameObserver = null;
  79734. this._onBeforeShaderCompilationObserver = null;
  79735. this._onAfterShaderCompilationObserver = null;
  79736. }
  79737. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79738. // Properties
  79739. /**
  79740. * Gets the perf counter used for GPU frame time
  79741. */
  79742. get: function () {
  79743. return this._gpuFrameTime;
  79744. },
  79745. enumerable: true,
  79746. configurable: true
  79747. });
  79748. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79749. /**
  79750. * Gets the GPU frame time capture status
  79751. */
  79752. get: function () {
  79753. return this._captureGPUFrameTime;
  79754. },
  79755. /**
  79756. * Enable or disable the GPU frame time capture
  79757. */
  79758. set: function (value) {
  79759. var _this = this;
  79760. if (value === this._captureGPUFrameTime) {
  79761. return;
  79762. }
  79763. this._captureGPUFrameTime = value;
  79764. if (value) {
  79765. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79766. if (!_this._gpuFrameTimeToken) {
  79767. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79768. }
  79769. });
  79770. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79771. if (!_this._gpuFrameTimeToken) {
  79772. return;
  79773. }
  79774. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79775. if (time > -1) {
  79776. _this._gpuFrameTimeToken = null;
  79777. _this._gpuFrameTime.fetchNewFrame();
  79778. _this._gpuFrameTime.addCount(time, true);
  79779. }
  79780. });
  79781. }
  79782. else {
  79783. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79784. this._onBeginFrameObserver = null;
  79785. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79786. this._onEndFrameObserver = null;
  79787. }
  79788. },
  79789. enumerable: true,
  79790. configurable: true
  79791. });
  79792. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79793. /**
  79794. * Gets the perf counter used for shader compilation time
  79795. */
  79796. get: function () {
  79797. return this._shaderCompilationTime;
  79798. },
  79799. enumerable: true,
  79800. configurable: true
  79801. });
  79802. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79803. /**
  79804. * Gets the shader compilation time capture status
  79805. */
  79806. get: function () {
  79807. return this._captureShaderCompilationTime;
  79808. },
  79809. /**
  79810. * Enable or disable the shader compilation time capture
  79811. */
  79812. set: function (value) {
  79813. var _this = this;
  79814. if (value === this._captureShaderCompilationTime) {
  79815. return;
  79816. }
  79817. this._captureShaderCompilationTime = value;
  79818. if (value) {
  79819. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79820. _this._shaderCompilationTime.fetchNewFrame();
  79821. _this._shaderCompilationTime.beginMonitoring();
  79822. });
  79823. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79824. _this._shaderCompilationTime.endMonitoring();
  79825. });
  79826. }
  79827. else {
  79828. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79829. this._onBeforeShaderCompilationObserver = null;
  79830. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79831. this._onAfterShaderCompilationObserver = null;
  79832. }
  79833. },
  79834. enumerable: true,
  79835. configurable: true
  79836. });
  79837. EngineInstrumentation.prototype.dispose = function () {
  79838. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79839. this._onBeginFrameObserver = null;
  79840. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79841. this._onEndFrameObserver = null;
  79842. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79843. this._onBeforeShaderCompilationObserver = null;
  79844. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79845. this._onAfterShaderCompilationObserver = null;
  79846. this.engine = null;
  79847. };
  79848. return EngineInstrumentation;
  79849. }());
  79850. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79851. })(BABYLON || (BABYLON = {}));
  79852. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79853. var BABYLON;
  79854. (function (BABYLON) {
  79855. /**
  79856. * This class can be used to get instrumentation data from a Babylon engine
  79857. */
  79858. var SceneInstrumentation = /** @class */ (function () {
  79859. function SceneInstrumentation(scene) {
  79860. var _this = this;
  79861. this.scene = scene;
  79862. this._captureActiveMeshesEvaluationTime = false;
  79863. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79864. this._captureRenderTargetsRenderTime = false;
  79865. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79866. this._captureFrameTime = false;
  79867. this._frameTime = new BABYLON.PerfCounter();
  79868. this._captureRenderTime = false;
  79869. this._renderTime = new BABYLON.PerfCounter();
  79870. this._captureInterFrameTime = false;
  79871. this._interFrameTime = new BABYLON.PerfCounter();
  79872. this._captureParticlesRenderTime = false;
  79873. this._particlesRenderTime = new BABYLON.PerfCounter();
  79874. this._captureSpritesRenderTime = false;
  79875. this._spritesRenderTime = new BABYLON.PerfCounter();
  79876. this._capturePhysicsTime = false;
  79877. this._physicsTime = new BABYLON.PerfCounter();
  79878. this._captureAnimationsTime = false;
  79879. this._animationsTime = new BABYLON.PerfCounter();
  79880. // Observers
  79881. this._onBeforeActiveMeshesEvaluationObserver = null;
  79882. this._onAfterActiveMeshesEvaluationObserver = null;
  79883. this._onBeforeRenderTargetsRenderObserver = null;
  79884. this._onAfterRenderTargetsRenderObserver = null;
  79885. this._onAfterRenderObserver = null;
  79886. this._onBeforeDrawPhaseObserver = null;
  79887. this._onAfterDrawPhaseObserver = null;
  79888. this._onBeforeAnimationsObserver = null;
  79889. this._onBeforeParticlesRenderingObserver = null;
  79890. this._onAfterParticlesRenderingObserver = null;
  79891. this._onBeforeSpritesRenderingObserver = null;
  79892. this._onAfterSpritesRenderingObserver = null;
  79893. this._onBeforePhysicsObserver = null;
  79894. this._onAfterPhysicsObserver = null;
  79895. this._onAfterAnimationsObserver = null;
  79896. // Before render
  79897. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79898. if (_this._captureActiveMeshesEvaluationTime) {
  79899. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79900. }
  79901. if (_this._captureRenderTargetsRenderTime) {
  79902. _this._renderTargetsRenderTime.fetchNewFrame();
  79903. }
  79904. if (_this._captureFrameTime) {
  79905. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79906. _this._frameTime.beginMonitoring();
  79907. }
  79908. if (_this._captureInterFrameTime) {
  79909. _this._interFrameTime.endMonitoring();
  79910. }
  79911. if (_this._captureParticlesRenderTime) {
  79912. _this._particlesRenderTime.fetchNewFrame();
  79913. }
  79914. if (_this._captureSpritesRenderTime) {
  79915. _this._spritesRenderTime.fetchNewFrame();
  79916. }
  79917. if (_this._captureAnimationsTime) {
  79918. _this._animationsTime.beginMonitoring();
  79919. }
  79920. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79921. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79922. });
  79923. // After render
  79924. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79925. if (_this._captureFrameTime) {
  79926. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79927. _this._frameTime.endMonitoring();
  79928. }
  79929. if (_this._captureRenderTime) {
  79930. _this._renderTime.endMonitoring(false);
  79931. }
  79932. if (_this._captureInterFrameTime) {
  79933. _this._interFrameTime.beginMonitoring();
  79934. }
  79935. });
  79936. }
  79937. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79938. // Properties
  79939. /**
  79940. * Gets the perf counter used for active meshes evaluation time
  79941. */
  79942. get: function () {
  79943. return this._activeMeshesEvaluationTime;
  79944. },
  79945. enumerable: true,
  79946. configurable: true
  79947. });
  79948. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79949. /**
  79950. * Gets the active meshes evaluation time capture status
  79951. */
  79952. get: function () {
  79953. return this._captureActiveMeshesEvaluationTime;
  79954. },
  79955. /**
  79956. * Enable or disable the active meshes evaluation time capture
  79957. */
  79958. set: function (value) {
  79959. var _this = this;
  79960. if (value === this._captureActiveMeshesEvaluationTime) {
  79961. return;
  79962. }
  79963. this._captureActiveMeshesEvaluationTime = value;
  79964. if (value) {
  79965. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79966. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79967. _this._activeMeshesEvaluationTime.beginMonitoring();
  79968. });
  79969. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79970. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79971. _this._activeMeshesEvaluationTime.endMonitoring();
  79972. });
  79973. }
  79974. else {
  79975. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79976. this._onBeforeActiveMeshesEvaluationObserver = null;
  79977. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79978. this._onAfterActiveMeshesEvaluationObserver = null;
  79979. }
  79980. },
  79981. enumerable: true,
  79982. configurable: true
  79983. });
  79984. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79985. /**
  79986. * Gets the perf counter used for render targets render time
  79987. */
  79988. get: function () {
  79989. return this._renderTargetsRenderTime;
  79990. },
  79991. enumerable: true,
  79992. configurable: true
  79993. });
  79994. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79995. /**
  79996. * Gets the render targets render time capture status
  79997. */
  79998. get: function () {
  79999. return this._captureRenderTargetsRenderTime;
  80000. },
  80001. /**
  80002. * Enable or disable the render targets render time capture
  80003. */
  80004. set: function (value) {
  80005. var _this = this;
  80006. if (value === this._captureRenderTargetsRenderTime) {
  80007. return;
  80008. }
  80009. this._captureRenderTargetsRenderTime = value;
  80010. if (value) {
  80011. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  80012. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  80013. _this._renderTargetsRenderTime.beginMonitoring();
  80014. });
  80015. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  80016. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  80017. _this._renderTargetsRenderTime.endMonitoring(false);
  80018. });
  80019. }
  80020. else {
  80021. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80022. this._onBeforeRenderTargetsRenderObserver = null;
  80023. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80024. this._onAfterRenderTargetsRenderObserver = null;
  80025. }
  80026. },
  80027. enumerable: true,
  80028. configurable: true
  80029. });
  80030. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  80031. /**
  80032. * Gets the perf counter used for particles render time
  80033. */
  80034. get: function () {
  80035. return this._particlesRenderTime;
  80036. },
  80037. enumerable: true,
  80038. configurable: true
  80039. });
  80040. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  80041. /**
  80042. * Gets the particles render time capture status
  80043. */
  80044. get: function () {
  80045. return this._captureParticlesRenderTime;
  80046. },
  80047. /**
  80048. * Enable or disable the particles render time capture
  80049. */
  80050. set: function (value) {
  80051. var _this = this;
  80052. if (value === this._captureParticlesRenderTime) {
  80053. return;
  80054. }
  80055. this._captureParticlesRenderTime = value;
  80056. if (value) {
  80057. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  80058. BABYLON.Tools.StartPerformanceCounter("Particles");
  80059. _this._particlesRenderTime.beginMonitoring();
  80060. });
  80061. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  80062. BABYLON.Tools.EndPerformanceCounter("Particles");
  80063. _this._particlesRenderTime.endMonitoring(false);
  80064. });
  80065. }
  80066. else {
  80067. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80068. this._onBeforeParticlesRenderingObserver = null;
  80069. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80070. this._onAfterParticlesRenderingObserver = null;
  80071. }
  80072. },
  80073. enumerable: true,
  80074. configurable: true
  80075. });
  80076. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  80077. /**
  80078. * Gets the perf counter used for sprites render time
  80079. */
  80080. get: function () {
  80081. return this._spritesRenderTime;
  80082. },
  80083. enumerable: true,
  80084. configurable: true
  80085. });
  80086. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  80087. /**
  80088. * Gets the sprites render time capture status
  80089. */
  80090. get: function () {
  80091. return this._captureSpritesRenderTime;
  80092. },
  80093. /**
  80094. * Enable or disable the sprites render time capture
  80095. */
  80096. set: function (value) {
  80097. var _this = this;
  80098. if (value === this._captureSpritesRenderTime) {
  80099. return;
  80100. }
  80101. this._captureSpritesRenderTime = value;
  80102. if (value) {
  80103. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  80104. BABYLON.Tools.StartPerformanceCounter("Sprites");
  80105. _this._spritesRenderTime.beginMonitoring();
  80106. });
  80107. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  80108. BABYLON.Tools.EndPerformanceCounter("Sprites");
  80109. _this._spritesRenderTime.endMonitoring(false);
  80110. });
  80111. }
  80112. else {
  80113. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80114. this._onBeforeSpritesRenderingObserver = null;
  80115. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80116. this._onAfterSpritesRenderingObserver = null;
  80117. }
  80118. },
  80119. enumerable: true,
  80120. configurable: true
  80121. });
  80122. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  80123. /**
  80124. * Gets the perf counter used for physics time
  80125. */
  80126. get: function () {
  80127. return this._physicsTime;
  80128. },
  80129. enumerable: true,
  80130. configurable: true
  80131. });
  80132. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  80133. /**
  80134. * Gets the physics time capture status
  80135. */
  80136. get: function () {
  80137. return this._capturePhysicsTime;
  80138. },
  80139. /**
  80140. * Enable or disable the physics time capture
  80141. */
  80142. set: function (value) {
  80143. var _this = this;
  80144. if (value === this._capturePhysicsTime) {
  80145. return;
  80146. }
  80147. this._capturePhysicsTime = value;
  80148. if (value) {
  80149. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  80150. BABYLON.Tools.StartPerformanceCounter("Physics");
  80151. _this._physicsTime.beginMonitoring();
  80152. });
  80153. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  80154. BABYLON.Tools.EndPerformanceCounter("Physics");
  80155. _this._physicsTime.endMonitoring();
  80156. });
  80157. }
  80158. else {
  80159. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80160. this._onBeforePhysicsObserver = null;
  80161. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80162. this._onAfterPhysicsObserver = null;
  80163. }
  80164. },
  80165. enumerable: true,
  80166. configurable: true
  80167. });
  80168. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  80169. /**
  80170. * Gets the perf counter used for animations time
  80171. */
  80172. get: function () {
  80173. return this._animationsTime;
  80174. },
  80175. enumerable: true,
  80176. configurable: true
  80177. });
  80178. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  80179. /**
  80180. * Gets the animations time capture status
  80181. */
  80182. get: function () {
  80183. return this._captureAnimationsTime;
  80184. },
  80185. /**
  80186. * Enable or disable the animations time capture
  80187. */
  80188. set: function (value) {
  80189. var _this = this;
  80190. if (value === this._captureAnimationsTime) {
  80191. return;
  80192. }
  80193. this._captureAnimationsTime = value;
  80194. if (value) {
  80195. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  80196. _this._animationsTime.endMonitoring();
  80197. });
  80198. }
  80199. else {
  80200. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80201. this._onAfterAnimationsObserver = null;
  80202. }
  80203. },
  80204. enumerable: true,
  80205. configurable: true
  80206. });
  80207. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  80208. /**
  80209. * Gets the perf counter used for frame time capture
  80210. */
  80211. get: function () {
  80212. return this._frameTime;
  80213. },
  80214. enumerable: true,
  80215. configurable: true
  80216. });
  80217. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  80218. /**
  80219. * Gets the frame time capture status
  80220. */
  80221. get: function () {
  80222. return this._captureFrameTime;
  80223. },
  80224. /**
  80225. * Enable or disable the frame time capture
  80226. */
  80227. set: function (value) {
  80228. this._captureFrameTime = value;
  80229. },
  80230. enumerable: true,
  80231. configurable: true
  80232. });
  80233. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  80234. /**
  80235. * Gets the perf counter used for inter-frames time capture
  80236. */
  80237. get: function () {
  80238. return this._interFrameTime;
  80239. },
  80240. enumerable: true,
  80241. configurable: true
  80242. });
  80243. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  80244. /**
  80245. * Gets the inter-frames time capture status
  80246. */
  80247. get: function () {
  80248. return this._captureInterFrameTime;
  80249. },
  80250. /**
  80251. * Enable or disable the inter-frames time capture
  80252. */
  80253. set: function (value) {
  80254. this._captureInterFrameTime = value;
  80255. },
  80256. enumerable: true,
  80257. configurable: true
  80258. });
  80259. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  80260. /**
  80261. * Gets the perf counter used for render time capture
  80262. */
  80263. get: function () {
  80264. return this._renderTime;
  80265. },
  80266. enumerable: true,
  80267. configurable: true
  80268. });
  80269. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  80270. /**
  80271. * Gets the render time capture status
  80272. */
  80273. get: function () {
  80274. return this._captureRenderTime;
  80275. },
  80276. /**
  80277. * Enable or disable the render time capture
  80278. */
  80279. set: function (value) {
  80280. var _this = this;
  80281. if (value === this._captureRenderTime) {
  80282. return;
  80283. }
  80284. this._captureRenderTime = value;
  80285. if (value) {
  80286. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80287. _this._renderTime.beginMonitoring();
  80288. BABYLON.Tools.StartPerformanceCounter("Main render");
  80289. });
  80290. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80291. _this._renderTime.endMonitoring(false);
  80292. BABYLON.Tools.EndPerformanceCounter("Main render");
  80293. });
  80294. }
  80295. else {
  80296. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80297. this._onBeforeDrawPhaseObserver = null;
  80298. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80299. this._onAfterDrawPhaseObserver = null;
  80300. }
  80301. },
  80302. enumerable: true,
  80303. configurable: true
  80304. });
  80305. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80306. /**
  80307. * Gets the perf counter used for draw calls
  80308. */
  80309. get: function () {
  80310. return this.scene.getEngine()._drawCalls;
  80311. },
  80312. enumerable: true,
  80313. configurable: true
  80314. });
  80315. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80316. /**
  80317. * Gets the perf counter used for texture collisions
  80318. */
  80319. get: function () {
  80320. return this.scene.getEngine()._textureCollisions;
  80321. },
  80322. enumerable: true,
  80323. configurable: true
  80324. });
  80325. SceneInstrumentation.prototype.dispose = function () {
  80326. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80327. this._onAfterRenderObserver = null;
  80328. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80329. this._onBeforeActiveMeshesEvaluationObserver = null;
  80330. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80331. this._onAfterActiveMeshesEvaluationObserver = null;
  80332. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80333. this._onBeforeRenderTargetsRenderObserver = null;
  80334. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80335. this._onAfterRenderTargetsRenderObserver = null;
  80336. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80337. this._onBeforeAnimationsObserver = null;
  80338. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80339. this._onBeforeParticlesRenderingObserver = null;
  80340. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80341. this._onAfterParticlesRenderingObserver = null;
  80342. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80343. this._onBeforeSpritesRenderingObserver = null;
  80344. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80345. this._onAfterSpritesRenderingObserver = null;
  80346. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80347. this._onBeforeDrawPhaseObserver = null;
  80348. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80349. this._onAfterDrawPhaseObserver = null;
  80350. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80351. this._onBeforePhysicsObserver = null;
  80352. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80353. this._onAfterPhysicsObserver = null;
  80354. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80355. this._onAfterAnimationsObserver = null;
  80356. this.scene = null;
  80357. };
  80358. return SceneInstrumentation;
  80359. }());
  80360. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80361. })(BABYLON || (BABYLON = {}));
  80362. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80363. var BABYLON;
  80364. (function (BABYLON) {
  80365. var _TimeToken = /** @class */ (function () {
  80366. function _TimeToken() {
  80367. this._timeElapsedQueryEnded = false;
  80368. }
  80369. return _TimeToken;
  80370. }());
  80371. BABYLON._TimeToken = _TimeToken;
  80372. })(BABYLON || (BABYLON = {}));
  80373. //# sourceMappingURL=babylon.timeToken.js.map
  80374. var BABYLON;
  80375. (function (BABYLON) {
  80376. /**
  80377. * Background material defines definition.
  80378. */
  80379. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80380. __extends(BackgroundMaterialDefines, _super);
  80381. /**
  80382. * Constructor of the defines.
  80383. */
  80384. function BackgroundMaterialDefines() {
  80385. var _this = _super.call(this) || this;
  80386. /**
  80387. * True if the diffuse texture is in use.
  80388. */
  80389. _this.DIFFUSE = false;
  80390. /**
  80391. * The direct UV channel to use.
  80392. */
  80393. _this.DIFFUSEDIRECTUV = 0;
  80394. /**
  80395. * True if the diffuse texture is in gamma space.
  80396. */
  80397. _this.GAMMADIFFUSE = false;
  80398. /**
  80399. * True if the diffuse texture has opacity in the alpha channel.
  80400. */
  80401. _this.DIFFUSEHASALPHA = false;
  80402. /**
  80403. * True if you want the material to fade to transparent at grazing angle.
  80404. */
  80405. _this.OPACITYFRESNEL = false;
  80406. /**
  80407. * True if an extra blur needs to be added in the reflection.
  80408. */
  80409. _this.REFLECTIONBLUR = false;
  80410. /**
  80411. * True if you want the material to fade to reflection at grazing angle.
  80412. */
  80413. _this.REFLECTIONFRESNEL = false;
  80414. /**
  80415. * True if you want the material to falloff as far as you move away from the scene center.
  80416. */
  80417. _this.REFLECTIONFALLOFF = false;
  80418. /**
  80419. * False if the current Webgl implementation does not support the texture lod extension.
  80420. */
  80421. _this.TEXTURELODSUPPORT = false;
  80422. /**
  80423. * True to ensure the data are premultiplied.
  80424. */
  80425. _this.PREMULTIPLYALPHA = false;
  80426. /**
  80427. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80428. */
  80429. _this.USERGBCOLOR = false;
  80430. /**
  80431. * True to add noise in order to reduce the banding effect.
  80432. */
  80433. _this.NOISE = false;
  80434. // Image Processing Configuration.
  80435. _this.IMAGEPROCESSING = false;
  80436. _this.VIGNETTE = false;
  80437. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80438. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80439. _this.TONEMAPPING = false;
  80440. _this.CONTRAST = false;
  80441. _this.COLORCURVES = false;
  80442. _this.COLORGRADING = false;
  80443. _this.COLORGRADING3D = false;
  80444. _this.SAMPLER3DGREENDEPTH = false;
  80445. _this.SAMPLER3DBGRMAP = false;
  80446. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80447. _this.EXPOSURE = false;
  80448. // Reflection.
  80449. _this.REFLECTION = false;
  80450. _this.REFLECTIONMAP_3D = false;
  80451. _this.REFLECTIONMAP_SPHERICAL = false;
  80452. _this.REFLECTIONMAP_PLANAR = false;
  80453. _this.REFLECTIONMAP_CUBIC = false;
  80454. _this.REFLECTIONMAP_PROJECTION = false;
  80455. _this.REFLECTIONMAP_SKYBOX = false;
  80456. _this.REFLECTIONMAP_EXPLICIT = false;
  80457. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80458. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80459. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80460. _this.INVERTCUBICMAP = false;
  80461. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80462. _this.LODINREFLECTIONALPHA = false;
  80463. _this.GAMMAREFLECTION = false;
  80464. // Default BJS.
  80465. _this.MAINUV1 = false;
  80466. _this.MAINUV2 = false;
  80467. _this.UV1 = false;
  80468. _this.UV2 = false;
  80469. _this.CLIPPLANE = false;
  80470. _this.POINTSIZE = false;
  80471. _this.FOG = false;
  80472. _this.NORMAL = false;
  80473. _this.NUM_BONE_INFLUENCERS = 0;
  80474. _this.BonesPerMesh = 0;
  80475. _this.INSTANCES = false;
  80476. _this.SHADOWFLOAT = false;
  80477. _this.rebuild();
  80478. return _this;
  80479. }
  80480. return BackgroundMaterialDefines;
  80481. }(BABYLON.MaterialDefines));
  80482. /**
  80483. * Background material used to create an efficient environement around your scene.
  80484. */
  80485. var BackgroundMaterial = /** @class */ (function (_super) {
  80486. __extends(BackgroundMaterial, _super);
  80487. /**
  80488. * constructor
  80489. * @param name The name of the material
  80490. * @param scene The scene to add the material to
  80491. */
  80492. function BackgroundMaterial(name, scene) {
  80493. var _this = _super.call(this, name, scene) || this;
  80494. _this.primaryColor = BABYLON.Color3.White();
  80495. _this.primaryLevel = 1;
  80496. _this.secondaryColor = BABYLON.Color3.Gray();
  80497. _this.secondaryLevel = 1;
  80498. _this.tertiaryColor = BABYLON.Color3.Black();
  80499. _this.tertiaryLevel = 1;
  80500. _this.reflectionTexture = null;
  80501. _this.reflectionBlur = 0;
  80502. _this.diffuseTexture = null;
  80503. /**
  80504. * Specify the list of lights casting shadow on the material.
  80505. * All scene shadow lights will be included if null.
  80506. */
  80507. _this._shadowLights = null;
  80508. _this.shadowLights = null;
  80509. _this.shadowBlurScale = 1;
  80510. _this.shadowLevel = 0;
  80511. _this.sceneCenter = BABYLON.Vector3.Zero();
  80512. _this.opacityFresnel = true;
  80513. _this.reflectionFresnel = false;
  80514. _this.reflectionFalloffDistance = 0.0;
  80515. _this.reflectionAmount = 1.0;
  80516. _this.reflectionReflectance0 = 0.05;
  80517. _this.reflectionReflectance90 = 0.5;
  80518. _this.useRGBColor = true;
  80519. _this.enableNoise = false;
  80520. /**
  80521. * Number of Simultaneous lights allowed on the material.
  80522. */
  80523. _this._maxSimultaneousLights = 4;
  80524. _this.maxSimultaneousLights = 4;
  80525. /**
  80526. * Keep track of the image processing observer to allow dispose and replace.
  80527. */
  80528. _this._imageProcessingObserver = null;
  80529. // Temp values kept as cache in the material.
  80530. _this._renderTargets = new BABYLON.SmartArray(16);
  80531. _this._reflectionControls = BABYLON.Vector4.Zero();
  80532. // Setup the default processing configuration to the scene.
  80533. _this._attachImageProcessingConfiguration(null);
  80534. _this.getRenderTargetTextures = function () {
  80535. _this._renderTargets.reset();
  80536. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80537. _this._renderTargets.push(_this._diffuseTexture);
  80538. }
  80539. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80540. _this._renderTargets.push(_this._reflectionTexture);
  80541. }
  80542. return _this._renderTargets;
  80543. };
  80544. return _this;
  80545. }
  80546. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80547. /**
  80548. * Sets the reflection reflectance fresnel values according to the default standard
  80549. * empirically know to work well :-)
  80550. */
  80551. set: function (value) {
  80552. var reflectionWeight = value;
  80553. if (reflectionWeight < 0.5) {
  80554. reflectionWeight = reflectionWeight * 2.0;
  80555. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80556. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80557. }
  80558. else {
  80559. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80560. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80561. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80562. }
  80563. },
  80564. enumerable: true,
  80565. configurable: true
  80566. });
  80567. /**
  80568. * Attaches a new image processing configuration to the PBR Material.
  80569. * @param configuration (if null the scene configuration will be use)
  80570. */
  80571. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80572. var _this = this;
  80573. if (configuration === this._imageProcessingConfiguration) {
  80574. return;
  80575. }
  80576. // Detaches observer.
  80577. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80578. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80579. }
  80580. // Pick the scene configuration if needed.
  80581. if (!configuration) {
  80582. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80583. }
  80584. else {
  80585. this._imageProcessingConfiguration = configuration;
  80586. }
  80587. // Attaches observer.
  80588. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80589. _this._markAllSubMeshesAsImageProcessingDirty();
  80590. });
  80591. };
  80592. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80593. /**
  80594. * Gets the image processing configuration used either in this material.
  80595. */
  80596. get: function () {
  80597. return this._imageProcessingConfiguration;
  80598. },
  80599. /**
  80600. * Sets the Default image processing configuration used either in the this material.
  80601. *
  80602. * If sets to null, the scene one is in use.
  80603. */
  80604. set: function (value) {
  80605. this._attachImageProcessingConfiguration(value);
  80606. // Ensure the effect will be rebuilt.
  80607. this._markAllSubMeshesAsTexturesDirty();
  80608. },
  80609. enumerable: true,
  80610. configurable: true
  80611. });
  80612. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80613. /**
  80614. * Gets wether the color curves effect is enabled.
  80615. */
  80616. get: function () {
  80617. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80618. },
  80619. /**
  80620. * Sets wether the color curves effect is enabled.
  80621. */
  80622. set: function (value) {
  80623. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80624. },
  80625. enumerable: true,
  80626. configurable: true
  80627. });
  80628. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80629. /**
  80630. * Gets wether the color grading effect is enabled.
  80631. */
  80632. get: function () {
  80633. return this.imageProcessingConfiguration.colorGradingEnabled;
  80634. },
  80635. /**
  80636. * Gets wether the color grading effect is enabled.
  80637. */
  80638. set: function (value) {
  80639. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80640. },
  80641. enumerable: true,
  80642. configurable: true
  80643. });
  80644. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80645. /**
  80646. * Gets wether tonemapping is enabled or not.
  80647. */
  80648. get: function () {
  80649. return this._imageProcessingConfiguration.toneMappingEnabled;
  80650. },
  80651. /**
  80652. * Sets wether tonemapping is enabled or not
  80653. */
  80654. set: function (value) {
  80655. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. ;
  80661. ;
  80662. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80663. /**
  80664. * The camera exposure used on this material.
  80665. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80666. * This corresponds to a photographic exposure.
  80667. */
  80668. get: function () {
  80669. return this._imageProcessingConfiguration.exposure;
  80670. },
  80671. /**
  80672. * The camera exposure used on this material.
  80673. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80674. * This corresponds to a photographic exposure.
  80675. */
  80676. set: function (value) {
  80677. this._imageProcessingConfiguration.exposure = value;
  80678. },
  80679. enumerable: true,
  80680. configurable: true
  80681. });
  80682. ;
  80683. ;
  80684. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80685. /**
  80686. * Gets The camera contrast used on this material.
  80687. */
  80688. get: function () {
  80689. return this._imageProcessingConfiguration.contrast;
  80690. },
  80691. /**
  80692. * Sets The camera contrast used on this material.
  80693. */
  80694. set: function (value) {
  80695. this._imageProcessingConfiguration.contrast = value;
  80696. },
  80697. enumerable: true,
  80698. configurable: true
  80699. });
  80700. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80701. /**
  80702. * Gets the Color Grading 2D Lookup Texture.
  80703. */
  80704. get: function () {
  80705. return this._imageProcessingConfiguration.colorGradingTexture;
  80706. },
  80707. /**
  80708. * Sets the Color Grading 2D Lookup Texture.
  80709. */
  80710. set: function (value) {
  80711. this.imageProcessingConfiguration.colorGradingTexture = value;
  80712. },
  80713. enumerable: true,
  80714. configurable: true
  80715. });
  80716. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80717. /**
  80718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80720. * 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;
  80721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80722. */
  80723. get: function () {
  80724. return this.imageProcessingConfiguration.colorCurves;
  80725. },
  80726. /**
  80727. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80728. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80729. * 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;
  80730. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80731. */
  80732. set: function (value) {
  80733. this.imageProcessingConfiguration.colorCurves = value;
  80734. },
  80735. enumerable: true,
  80736. configurable: true
  80737. });
  80738. /**
  80739. * The entire material has been created in order to prevent overdraw.
  80740. * @returns false
  80741. */
  80742. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80743. return true;
  80744. };
  80745. /**
  80746. * The entire material has been created in order to prevent overdraw.
  80747. * @returns true if blending is enable
  80748. */
  80749. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80750. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80751. };
  80752. /**
  80753. * Checks wether the material is ready to be rendered for a given mesh.
  80754. * @param mesh The mesh to render
  80755. * @param subMesh The submesh to check against
  80756. * @param useInstances Specify wether or not the material is used with instances
  80757. */
  80758. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80759. var _this = this;
  80760. if (useInstances === void 0) { useInstances = false; }
  80761. if (subMesh.effect && this.isFrozen) {
  80762. if (this._wasPreviouslyReady) {
  80763. return true;
  80764. }
  80765. }
  80766. if (!subMesh._materialDefines) {
  80767. subMesh._materialDefines = new BackgroundMaterialDefines();
  80768. }
  80769. var scene = this.getScene();
  80770. var defines = subMesh._materialDefines;
  80771. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80772. if (defines._renderId === scene.getRenderId()) {
  80773. return true;
  80774. }
  80775. }
  80776. var engine = scene.getEngine();
  80777. // Lights
  80778. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80779. defines._needNormals = true;
  80780. // Textures
  80781. if (defines._areTexturesDirty) {
  80782. defines._needUVs = false;
  80783. if (scene.texturesEnabled) {
  80784. if (scene.getEngine().getCaps().textureLOD) {
  80785. defines.TEXTURELODSUPPORT = true;
  80786. }
  80787. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80788. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80789. return false;
  80790. }
  80791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80792. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80793. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80794. defines.OPACITYFRESNEL = this._opacityFresnel;
  80795. }
  80796. else {
  80797. defines.DIFFUSE = false;
  80798. defines.DIFFUSEHASALPHA = false;
  80799. defines.GAMMADIFFUSE = false;
  80800. defines.OPACITYFRESNEL = false;
  80801. }
  80802. var reflectionTexture = this._reflectionTexture;
  80803. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80804. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80805. return false;
  80806. }
  80807. defines.REFLECTION = true;
  80808. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80809. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80810. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80811. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80812. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80813. defines.INVERTCUBICMAP = true;
  80814. }
  80815. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80816. switch (reflectionTexture.coordinatesMode) {
  80817. case BABYLON.Texture.CUBIC_MODE:
  80818. case BABYLON.Texture.INVCUBIC_MODE:
  80819. defines.REFLECTIONMAP_CUBIC = true;
  80820. break;
  80821. case BABYLON.Texture.EXPLICIT_MODE:
  80822. defines.REFLECTIONMAP_EXPLICIT = true;
  80823. break;
  80824. case BABYLON.Texture.PLANAR_MODE:
  80825. defines.REFLECTIONMAP_PLANAR = true;
  80826. break;
  80827. case BABYLON.Texture.PROJECTION_MODE:
  80828. defines.REFLECTIONMAP_PROJECTION = true;
  80829. break;
  80830. case BABYLON.Texture.SKYBOX_MODE:
  80831. defines.REFLECTIONMAP_SKYBOX = true;
  80832. break;
  80833. case BABYLON.Texture.SPHERICAL_MODE:
  80834. defines.REFLECTIONMAP_SPHERICAL = true;
  80835. break;
  80836. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80837. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80838. break;
  80839. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80840. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80841. break;
  80842. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80843. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80844. break;
  80845. }
  80846. if (this.reflectionFresnel) {
  80847. defines.REFLECTIONFRESNEL = true;
  80848. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80849. this._reflectionControls.x = this.reflectionAmount;
  80850. this._reflectionControls.y = this.reflectionReflectance0;
  80851. this._reflectionControls.z = this.reflectionReflectance90;
  80852. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80853. }
  80854. else {
  80855. defines.REFLECTIONFRESNEL = false;
  80856. defines.REFLECTIONFALLOFF = false;
  80857. }
  80858. }
  80859. else {
  80860. defines.REFLECTION = false;
  80861. defines.REFLECTIONFALLOFF = false;
  80862. defines.REFLECTIONBLUR = false;
  80863. defines.REFLECTIONMAP_3D = false;
  80864. defines.REFLECTIONMAP_SPHERICAL = false;
  80865. defines.REFLECTIONMAP_PLANAR = false;
  80866. defines.REFLECTIONMAP_CUBIC = false;
  80867. defines.REFLECTIONMAP_PROJECTION = false;
  80868. defines.REFLECTIONMAP_SKYBOX = false;
  80869. defines.REFLECTIONMAP_EXPLICIT = false;
  80870. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80871. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80872. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80873. defines.INVERTCUBICMAP = false;
  80874. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80875. defines.LODINREFLECTIONALPHA = false;
  80876. defines.GAMMAREFLECTION = false;
  80877. }
  80878. }
  80879. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80880. defines.USERGBCOLOR = this._useRGBColor;
  80881. defines.NOISE = this._enableNoise;
  80882. }
  80883. if (defines._areImageProcessingDirty) {
  80884. if (!this._imageProcessingConfiguration.isReady()) {
  80885. return false;
  80886. }
  80887. this._imageProcessingConfiguration.prepareDefines(defines);
  80888. }
  80889. // Misc.
  80890. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80891. // Values that need to be evaluated on every frame
  80892. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  80893. // Attribs
  80894. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80895. if (mesh) {
  80896. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80897. mesh.createNormals(true);
  80898. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80899. }
  80900. }
  80901. }
  80902. // Get correct effect
  80903. if (defines.isDirty) {
  80904. defines.markAsProcessed();
  80905. scene.resetCachedMaterial();
  80906. // Fallbacks
  80907. var fallbacks = new BABYLON.EffectFallbacks();
  80908. if (defines.FOG) {
  80909. fallbacks.addFallback(0, "FOG");
  80910. }
  80911. if (defines.POINTSIZE) {
  80912. fallbacks.addFallback(1, "POINTSIZE");
  80913. }
  80914. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80915. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80916. fallbacks.addCPUSkinningFallback(0, mesh);
  80917. }
  80918. //Attributes
  80919. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80920. if (defines.NORMAL) {
  80921. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80922. }
  80923. if (defines.UV1) {
  80924. attribs.push(BABYLON.VertexBuffer.UVKind);
  80925. }
  80926. if (defines.UV2) {
  80927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80928. }
  80929. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80930. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80931. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80932. "vFogInfos", "vFogColor", "pointSize",
  80933. "vClipPlane", "mBones",
  80934. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80935. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80936. "shadowLevel", "alpha",
  80937. "vBackgroundCenter", "vReflectionControl",
  80938. "vDiffuseInfos", "diffuseMatrix",
  80939. ];
  80940. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80941. var uniformBuffers = ["Material", "Scene"];
  80942. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80943. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80944. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80945. uniformsNames: uniforms,
  80946. uniformBuffersNames: uniformBuffers,
  80947. samplers: samplers,
  80948. defines: defines,
  80949. maxSimultaneousLights: this._maxSimultaneousLights
  80950. });
  80951. var onCompiled = function (effect) {
  80952. if (_this.onCompiled) {
  80953. _this.onCompiled(effect);
  80954. }
  80955. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80956. };
  80957. var join = defines.toString();
  80958. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80959. attributes: attribs,
  80960. uniformsNames: uniforms,
  80961. uniformBuffersNames: uniformBuffers,
  80962. samplers: samplers,
  80963. defines: join,
  80964. fallbacks: fallbacks,
  80965. onCompiled: onCompiled,
  80966. onError: this.onError,
  80967. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80968. }, engine), defines);
  80969. this.buildUniformLayout();
  80970. }
  80971. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80972. return false;
  80973. }
  80974. defines._renderId = scene.getRenderId();
  80975. this._wasPreviouslyReady = true;
  80976. return true;
  80977. };
  80978. /**
  80979. * Build the uniform buffer used in the material.
  80980. */
  80981. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80982. // Order is important !
  80983. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80984. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80985. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80986. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80987. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80988. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80989. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80990. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80991. this._uniformBuffer.addUniform("pointSize", 1);
  80992. this._uniformBuffer.addUniform("shadowLevel", 1);
  80993. this._uniformBuffer.addUniform("alpha", 1);
  80994. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80995. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80996. this._uniformBuffer.create();
  80997. };
  80998. /**
  80999. * Unbind the material.
  81000. */
  81001. BackgroundMaterial.prototype.unbind = function () {
  81002. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  81003. this._uniformBuffer.setTexture("diffuseSampler", null);
  81004. }
  81005. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  81006. this._uniformBuffer.setTexture("reflectionSampler", null);
  81007. }
  81008. _super.prototype.unbind.call(this);
  81009. };
  81010. /**
  81011. * Bind only the world matrix to the material.
  81012. * @param world The world matrix to bind.
  81013. */
  81014. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  81015. this._activeEffect.setMatrix("world", world);
  81016. };
  81017. /**
  81018. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  81019. * @param world The world matrix to bind.
  81020. * @param subMesh The submesh to bind for.
  81021. */
  81022. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81023. var scene = this.getScene();
  81024. var defines = subMesh._materialDefines;
  81025. if (!defines) {
  81026. return;
  81027. }
  81028. var effect = subMesh.effect;
  81029. if (!effect) {
  81030. return;
  81031. }
  81032. this._activeEffect = effect;
  81033. // Matrices
  81034. this.bindOnlyWorldMatrix(world);
  81035. // Bones
  81036. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  81037. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  81038. if (mustRebind) {
  81039. this._uniformBuffer.bindToEffect(effect, "Material");
  81040. this.bindViewProjection(effect);
  81041. var reflectionTexture = this._reflectionTexture;
  81042. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  81043. // Texture uniforms
  81044. if (scene.texturesEnabled) {
  81045. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  81046. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  81047. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  81048. }
  81049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  81050. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  81051. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  81052. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  81053. }
  81054. }
  81055. if (this.shadowLevel > 0) {
  81056. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  81057. }
  81058. this._uniformBuffer.updateFloat("alpha", this.alpha);
  81059. // Point size
  81060. if (this.pointsCloud) {
  81061. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  81062. }
  81063. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  81064. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  81065. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  81066. }
  81067. // Textures
  81068. if (scene.texturesEnabled) {
  81069. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  81070. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  81071. }
  81072. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  81073. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  81074. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  81075. }
  81076. else if (!defines.REFLECTIONBLUR) {
  81077. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  81078. }
  81079. else {
  81080. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  81081. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  81082. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  81083. }
  81084. if (defines.REFLECTIONFRESNEL) {
  81085. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  81086. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  81087. }
  81088. }
  81089. }
  81090. // Clip plane
  81091. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  81092. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  81093. }
  81094. if (mustRebind || !this.isFrozen) {
  81095. if (scene.lightsEnabled) {
  81096. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  81097. }
  81098. // View
  81099. this.bindView(effect);
  81100. // Fog
  81101. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81102. // image processing
  81103. this._imageProcessingConfiguration.bind(this._activeEffect);
  81104. }
  81105. this._uniformBuffer.update();
  81106. this._afterBind(mesh);
  81107. };
  81108. /**
  81109. * Dispose the material.
  81110. * @forceDisposeEffect Force disposal of the associated effect.
  81111. * @forceDisposeTextures Force disposal of the associated textures.
  81112. */
  81113. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  81114. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  81115. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  81116. if (forceDisposeTextures) {
  81117. if (this.diffuseTexture) {
  81118. this.diffuseTexture.dispose();
  81119. }
  81120. if (this.reflectionTexture) {
  81121. this.reflectionTexture.dispose();
  81122. }
  81123. }
  81124. this._renderTargets.dispose();
  81125. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81126. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81127. }
  81128. _super.prototype.dispose.call(this, forceDisposeEffect);
  81129. };
  81130. /**
  81131. * Clones the material.
  81132. * @name The cloned name.
  81133. * @returns The cloned material.
  81134. */
  81135. BackgroundMaterial.prototype.clone = function (name) {
  81136. var _this = this;
  81137. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  81138. };
  81139. /**
  81140. * Serializes the current material to its JSON representation.
  81141. * @returns The JSON representation.
  81142. */
  81143. BackgroundMaterial.prototype.serialize = function () {
  81144. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81145. serializationObject.customType = "BABYLON.BackgroundMaterial";
  81146. return serializationObject;
  81147. };
  81148. /**
  81149. * Gets the class name of the material
  81150. * @returns "BackgroundMaterial"
  81151. */
  81152. BackgroundMaterial.prototype.getClassName = function () {
  81153. return "BackgroundMaterial";
  81154. };
  81155. /**
  81156. * Parse a JSON input to create back a background material.
  81157. * @param source
  81158. * @param scene
  81159. * @param rootUrl
  81160. * @returns the instantiated BackgroundMaterial.
  81161. */
  81162. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  81163. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  81164. };
  81165. /**
  81166. * Standard reflectance value at parallel view angle.
  81167. */
  81168. BackgroundMaterial.standardReflectance0 = 0.05;
  81169. /**
  81170. * Standard reflectance value at grazing angle.
  81171. */
  81172. BackgroundMaterial.standardReflectance90 = 0.5;
  81173. __decorate([
  81174. BABYLON.serializeAsColor3()
  81175. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  81176. __decorate([
  81177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81178. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  81179. __decorate([
  81180. BABYLON.serialize()
  81181. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  81182. __decorate([
  81183. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81184. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  81185. __decorate([
  81186. BABYLON.serializeAsColor3()
  81187. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  81188. __decorate([
  81189. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81190. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  81191. __decorate([
  81192. BABYLON.serialize()
  81193. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  81194. __decorate([
  81195. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81196. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  81197. __decorate([
  81198. BABYLON.serializeAsColor3()
  81199. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  81200. __decorate([
  81201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81202. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  81203. __decorate([
  81204. BABYLON.serialize()
  81205. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  81206. __decorate([
  81207. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81208. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  81209. __decorate([
  81210. BABYLON.serializeAsTexture()
  81211. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  81212. __decorate([
  81213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81214. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  81215. __decorate([
  81216. BABYLON.serialize()
  81217. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  81218. __decorate([
  81219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81220. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  81221. __decorate([
  81222. BABYLON.serializeAsTexture()
  81223. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  81224. __decorate([
  81225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81226. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  81227. __decorate([
  81228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81229. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  81230. __decorate([
  81231. BABYLON.serialize()
  81232. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  81233. __decorate([
  81234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81235. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  81236. __decorate([
  81237. BABYLON.serialize()
  81238. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  81239. __decorate([
  81240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81241. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  81242. __decorate([
  81243. BABYLON.serializeAsVector3()
  81244. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  81245. __decorate([
  81246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81247. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  81248. __decorate([
  81249. BABYLON.serialize()
  81250. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  81251. __decorate([
  81252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81253. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  81254. __decorate([
  81255. BABYLON.serialize()
  81256. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  81257. __decorate([
  81258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81259. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  81260. __decorate([
  81261. BABYLON.serialize()
  81262. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  81263. __decorate([
  81264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81265. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  81266. __decorate([
  81267. BABYLON.serialize()
  81268. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  81269. __decorate([
  81270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81271. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  81272. __decorate([
  81273. BABYLON.serialize()
  81274. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  81275. __decorate([
  81276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81277. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  81278. __decorate([
  81279. BABYLON.serialize()
  81280. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  81281. __decorate([
  81282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81283. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81284. __decorate([
  81285. BABYLON.serialize()
  81286. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81287. __decorate([
  81288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81289. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81290. __decorate([
  81291. BABYLON.serialize()
  81292. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81293. __decorate([
  81294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81295. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81296. __decorate([
  81297. BABYLON.serialize()
  81298. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81299. __decorate([
  81300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81301. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81302. __decorate([
  81303. BABYLON.serializeAsImageProcessingConfiguration()
  81304. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81305. return BackgroundMaterial;
  81306. }(BABYLON.PushMaterial));
  81307. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81308. })(BABYLON || (BABYLON = {}));
  81309. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81310. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81311. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81312. s = arguments[i];
  81313. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81314. t[p] = s[p];
  81315. }
  81316. return t;
  81317. };
  81318. var BABYLON;
  81319. (function (BABYLON) {
  81320. /**
  81321. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81322. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81323. * It also helps with the default setup of your imageProcessing configuration.
  81324. */
  81325. var EnvironmentHelper = /** @class */ (function () {
  81326. /**
  81327. * constructor
  81328. * @param options
  81329. * @param scene The scene to add the material to
  81330. */
  81331. function EnvironmentHelper(options, scene) {
  81332. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81333. this._scene = scene;
  81334. this._setupBackground();
  81335. this._setupImageProcessing();
  81336. }
  81337. /**
  81338. * Creates the default options for the helper.
  81339. */
  81340. EnvironmentHelper._getDefaultOptions = function () {
  81341. return {
  81342. createGround: true,
  81343. groundSize: 15,
  81344. groundTexture: this._groundTextureCDNUrl,
  81345. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81346. groundOpacity: 0.9,
  81347. enableGroundShadow: true,
  81348. groundShadowLevel: 0.5,
  81349. enableGroundMirror: false,
  81350. groundMirrorSizeRatio: 0.3,
  81351. groundMirrorBlurKernel: 64,
  81352. groundMirrorAmount: 1,
  81353. groundMirrorFresnelWeight: 1,
  81354. groundMirrorFallOffDistance: 0,
  81355. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81356. groundYBias: 0.00001,
  81357. createSkybox: true,
  81358. skyboxSize: 20,
  81359. skyboxTexture: this._skyboxTextureCDNUrl,
  81360. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81361. backgroundYRotation: 0,
  81362. sizeAuto: true,
  81363. rootPosition: BABYLON.Vector3.Zero(),
  81364. setupImageProcessing: true,
  81365. environmentTexture: this._environmentTextureCDNUrl,
  81366. cameraExposure: 0.8,
  81367. cameraContrast: 1.2,
  81368. toneMappingEnabled: true,
  81369. };
  81370. };
  81371. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81372. /**
  81373. * Gets the root mesh created by the helper.
  81374. */
  81375. get: function () {
  81376. return this._rootMesh;
  81377. },
  81378. enumerable: true,
  81379. configurable: true
  81380. });
  81381. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81382. /**
  81383. * Gets the skybox created by the helper.
  81384. */
  81385. get: function () {
  81386. return this._skybox;
  81387. },
  81388. enumerable: true,
  81389. configurable: true
  81390. });
  81391. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81392. /**
  81393. * Gets the skybox texture created by the helper.
  81394. */
  81395. get: function () {
  81396. return this._skyboxTexture;
  81397. },
  81398. enumerable: true,
  81399. configurable: true
  81400. });
  81401. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81402. /**
  81403. * Gets the skybox material created by the helper.
  81404. */
  81405. get: function () {
  81406. return this._skyboxMaterial;
  81407. },
  81408. enumerable: true,
  81409. configurable: true
  81410. });
  81411. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81412. /**
  81413. * Gets the ground mesh created by the helper.
  81414. */
  81415. get: function () {
  81416. return this._ground;
  81417. },
  81418. enumerable: true,
  81419. configurable: true
  81420. });
  81421. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81422. /**
  81423. * Gets the ground texture created by the helper.
  81424. */
  81425. get: function () {
  81426. return this._groundTexture;
  81427. },
  81428. enumerable: true,
  81429. configurable: true
  81430. });
  81431. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81432. /**
  81433. * Gets the ground mirror created by the helper.
  81434. */
  81435. get: function () {
  81436. return this._groundMirror;
  81437. },
  81438. enumerable: true,
  81439. configurable: true
  81440. });
  81441. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81442. /**
  81443. * Gets the ground mirror render list to helps pushing the meshes
  81444. * you wish in the ground reflection.
  81445. */
  81446. get: function () {
  81447. if (this._groundMirror) {
  81448. return this._groundMirror.renderList;
  81449. }
  81450. return null;
  81451. },
  81452. enumerable: true,
  81453. configurable: true
  81454. });
  81455. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81456. /**
  81457. * Gets the ground material created by the helper.
  81458. */
  81459. get: function () {
  81460. return this._groundMaterial;
  81461. },
  81462. enumerable: true,
  81463. configurable: true
  81464. });
  81465. /**
  81466. * Updates the background according to the new options
  81467. * @param options
  81468. */
  81469. EnvironmentHelper.prototype.updateOptions = function (options) {
  81470. var newOptions = __assign({}, this._options, options);
  81471. if (this._ground && !newOptions.createGround) {
  81472. this._ground.dispose();
  81473. this._ground = null;
  81474. }
  81475. if (this._groundMaterial && !newOptions.createGround) {
  81476. this._groundMaterial.dispose();
  81477. this._groundMaterial = null;
  81478. }
  81479. if (this._groundTexture) {
  81480. if (this._options.groundTexture != newOptions.groundTexture) {
  81481. this._groundTexture.dispose();
  81482. this._groundTexture = null;
  81483. }
  81484. }
  81485. if (this._skybox && !newOptions.createSkybox) {
  81486. this._skybox.dispose();
  81487. this._skybox = null;
  81488. }
  81489. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81490. this._skyboxMaterial.dispose();
  81491. this._skyboxMaterial = null;
  81492. }
  81493. if (this._skyboxTexture) {
  81494. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81495. this._skyboxTexture.dispose();
  81496. this._skyboxTexture = null;
  81497. }
  81498. }
  81499. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81500. this._groundMirror.dispose();
  81501. this._groundMirror = null;
  81502. }
  81503. if (this._scene.environmentTexture) {
  81504. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81505. this._scene.environmentTexture.dispose();
  81506. }
  81507. }
  81508. this._options = newOptions;
  81509. this._setupBackground();
  81510. this._setupImageProcessing();
  81511. };
  81512. /**
  81513. * Sets the primary color of all the available elements.
  81514. * @param color
  81515. */
  81516. EnvironmentHelper.prototype.setMainColor = function (color) {
  81517. if (this.groundMaterial) {
  81518. this.groundMaterial.primaryColor = color;
  81519. }
  81520. if (this.skyboxMaterial) {
  81521. this.skyboxMaterial.primaryColor = color;
  81522. }
  81523. if (this.groundMirror) {
  81524. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81525. }
  81526. };
  81527. /**
  81528. * Setup the image processing according to the specified options.
  81529. */
  81530. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81531. if (this._options.setupImageProcessing) {
  81532. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81533. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81534. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81535. this._setupEnvironmentTexture();
  81536. }
  81537. };
  81538. /**
  81539. * Setup the environment texture according to the specified options.
  81540. */
  81541. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81542. if (this._scene.environmentTexture) {
  81543. return;
  81544. }
  81545. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81546. this._scene.environmentTexture = this._options.environmentTexture;
  81547. return;
  81548. }
  81549. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81550. this._scene.environmentTexture = environmentTexture;
  81551. };
  81552. /**
  81553. * Setup the background according to the specified options.
  81554. */
  81555. EnvironmentHelper.prototype._setupBackground = function () {
  81556. if (!this._rootMesh) {
  81557. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81558. }
  81559. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81560. var sceneSize = this._getSceneSize();
  81561. if (this._options.createGround) {
  81562. this._setupGround(sceneSize);
  81563. this._setupGroundMaterial();
  81564. this._setupGroundDiffuseTexture();
  81565. if (this._options.enableGroundMirror) {
  81566. this._setupGroundMirrorTexture(sceneSize);
  81567. }
  81568. this._setupMirrorInGroundMaterial();
  81569. }
  81570. if (this._options.createSkybox) {
  81571. this._setupSkybox(sceneSize);
  81572. this._setupSkyboxMaterial();
  81573. this._setupSkyboxReflectionTexture();
  81574. }
  81575. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81576. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81577. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81578. };
  81579. /**
  81580. * Get the scene sizes according to the setup.
  81581. */
  81582. EnvironmentHelper.prototype._getSceneSize = function () {
  81583. var groundSize = this._options.groundSize;
  81584. var skyboxSize = this._options.skyboxSize;
  81585. var rootPosition = this._options.rootPosition;
  81586. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81587. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81588. }
  81589. var sceneExtends = this._scene.getWorldExtends();
  81590. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81591. if (this._options.sizeAuto) {
  81592. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81593. this._scene.activeCamera.upperRadiusLimit) {
  81594. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81595. skyboxSize = groundSize;
  81596. }
  81597. var sceneDiagonalLenght = sceneDiagonal.length();
  81598. if (sceneDiagonalLenght > groundSize) {
  81599. groundSize = sceneDiagonalLenght * 2;
  81600. skyboxSize = groundSize;
  81601. }
  81602. // 10 % bigger.
  81603. groundSize *= 1.1;
  81604. skyboxSize *= 1.5;
  81605. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81606. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81607. }
  81608. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81609. };
  81610. /**
  81611. * Setup the ground according to the specified options.
  81612. */
  81613. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81614. var _this = this;
  81615. if (!this._ground) {
  81616. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81617. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81618. this._ground.parent = this._rootMesh;
  81619. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81620. }
  81621. this._ground.receiveShadows = this._options.enableGroundShadow;
  81622. };
  81623. /**
  81624. * Setup the ground material according to the specified options.
  81625. */
  81626. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81627. if (!this._groundMaterial) {
  81628. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81629. }
  81630. this._groundMaterial.alpha = this._options.groundOpacity;
  81631. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81632. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81633. this._groundMaterial.primaryLevel = 1;
  81634. this._groundMaterial.primaryColor = this._options.groundColor;
  81635. this._groundMaterial.secondaryLevel = 0;
  81636. this._groundMaterial.tertiaryLevel = 0;
  81637. this._groundMaterial.useRGBColor = false;
  81638. this._groundMaterial.enableNoise = true;
  81639. if (this._ground) {
  81640. this._ground.material = this._groundMaterial;
  81641. }
  81642. };
  81643. /**
  81644. * Setup the ground diffuse texture according to the specified options.
  81645. */
  81646. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81647. if (!this._groundMaterial) {
  81648. return;
  81649. }
  81650. if (this._groundTexture) {
  81651. return;
  81652. }
  81653. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81654. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81655. return;
  81656. }
  81657. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81658. diffuseTexture.gammaSpace = false;
  81659. diffuseTexture.hasAlpha = true;
  81660. this._groundMaterial.diffuseTexture = diffuseTexture;
  81661. };
  81662. /**
  81663. * Setup the ground mirror texture according to the specified options.
  81664. */
  81665. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81666. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81667. if (!this._groundMirror) {
  81668. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81669. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81670. this._groundMirror.anisotropicFilteringLevel = 1;
  81671. this._groundMirror.wrapU = wrapping;
  81672. this._groundMirror.wrapV = wrapping;
  81673. this._groundMirror.gammaSpace = false;
  81674. if (this._groundMirror.renderList) {
  81675. for (var i = 0; i < this._scene.meshes.length; i++) {
  81676. var mesh = this._scene.meshes[i];
  81677. if (mesh !== this._ground &&
  81678. mesh !== this._skybox &&
  81679. mesh !== this._rootMesh) {
  81680. this._groundMirror.renderList.push(mesh);
  81681. }
  81682. }
  81683. }
  81684. }
  81685. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81686. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81687. };
  81688. /**
  81689. * Setup the ground to receive the mirror texture.
  81690. */
  81691. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81692. if (this._groundMaterial) {
  81693. this._groundMaterial.reflectionTexture = this._groundMirror;
  81694. this._groundMaterial.reflectionFresnel = true;
  81695. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81696. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81697. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81698. }
  81699. };
  81700. /**
  81701. * Setup the skybox according to the specified options.
  81702. */
  81703. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81704. var _this = this;
  81705. if (!this._skybox) {
  81706. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81707. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81708. }
  81709. this._skybox.parent = this._rootMesh;
  81710. };
  81711. /**
  81712. * Setup the skybox material according to the specified options.
  81713. */
  81714. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81715. if (!this._skybox) {
  81716. return;
  81717. }
  81718. if (!this._skyboxMaterial) {
  81719. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81720. }
  81721. this._skyboxMaterial.useRGBColor = false;
  81722. this._skyboxMaterial.primaryLevel = 1;
  81723. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81724. this._skyboxMaterial.secondaryLevel = 0;
  81725. this._skyboxMaterial.tertiaryLevel = 0;
  81726. this._skyboxMaterial.enableNoise = true;
  81727. this._skybox.material = this._skyboxMaterial;
  81728. };
  81729. /**
  81730. * Setup the skybox reflection texture according to the specified options.
  81731. */
  81732. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81733. if (!this._skyboxMaterial) {
  81734. return;
  81735. }
  81736. if (this._skyboxTexture) {
  81737. return;
  81738. }
  81739. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81740. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81741. return;
  81742. }
  81743. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81744. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81745. this._skyboxTexture.gammaSpace = false;
  81746. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81747. };
  81748. /**
  81749. * Dispose all the elements created by the Helper.
  81750. */
  81751. EnvironmentHelper.prototype.dispose = function () {
  81752. if (this._groundMaterial) {
  81753. this._groundMaterial.dispose(true, true);
  81754. }
  81755. if (this._skyboxMaterial) {
  81756. this._skyboxMaterial.dispose(true, true);
  81757. }
  81758. this._rootMesh.dispose(false);
  81759. };
  81760. /**
  81761. * Default ground texture URL.
  81762. */
  81763. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81764. /**
  81765. * Default skybox texture URL.
  81766. */
  81767. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81768. /**
  81769. * Default environment texture URL.
  81770. */
  81771. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81772. return EnvironmentHelper;
  81773. }());
  81774. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81775. })(BABYLON || (BABYLON = {}));
  81776. //# sourceMappingURL=babylon.environmentHelper.js.map
  81777. 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}"};
  81778. 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};"};
  81779. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81780. var BABYLON;
  81781. (function (BABYLON) {
  81782. var GridMaterialDefines = /** @class */ (function (_super) {
  81783. __extends(GridMaterialDefines, _super);
  81784. function GridMaterialDefines() {
  81785. var _this = _super.call(this) || this;
  81786. _this.TRANSPARENT = false;
  81787. _this.FOG = false;
  81788. _this.PREMULTIPLYALPHA = false;
  81789. _this.rebuild();
  81790. return _this;
  81791. }
  81792. return GridMaterialDefines;
  81793. }(BABYLON.MaterialDefines));
  81794. /**
  81795. * The grid materials allows you to wrap any shape with a grid.
  81796. * Colors are customizable.
  81797. */
  81798. var GridMaterial = /** @class */ (function (_super) {
  81799. __extends(GridMaterial, _super);
  81800. /**
  81801. * constructor
  81802. * @param name The name given to the material in order to identify it afterwards.
  81803. * @param scene The scene the material is used in.
  81804. */
  81805. function GridMaterial(name, scene) {
  81806. var _this = _super.call(this, name, scene) || this;
  81807. /**
  81808. * Main color of the grid (e.g. between lines)
  81809. */
  81810. _this.mainColor = BABYLON.Color3.Black();
  81811. /**
  81812. * Color of the grid lines.
  81813. */
  81814. _this.lineColor = BABYLON.Color3.Teal();
  81815. /**
  81816. * The scale of the grid compared to unit.
  81817. */
  81818. _this.gridRatio = 1.0;
  81819. /**
  81820. * Allows setting an offset for the grid lines.
  81821. */
  81822. _this.gridOffset = BABYLON.Vector3.Zero();
  81823. /**
  81824. * The frequency of thicker lines.
  81825. */
  81826. _this.majorUnitFrequency = 10;
  81827. /**
  81828. * The visibility of minor units in the grid.
  81829. */
  81830. _this.minorUnitVisibility = 0.33;
  81831. /**
  81832. * The grid opacity outside of the lines.
  81833. */
  81834. _this.opacity = 1.0;
  81835. /**
  81836. * Determine RBG output is premultiplied by alpha value.
  81837. */
  81838. _this.preMultiplyAlpha = false;
  81839. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81840. return _this;
  81841. }
  81842. /**
  81843. * Returns wehter or not the grid requires alpha blending.
  81844. */
  81845. GridMaterial.prototype.needAlphaBlending = function () {
  81846. return this.opacity < 1.0;
  81847. };
  81848. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81849. return this.needAlphaBlending();
  81850. };
  81851. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81852. if (this.isFrozen) {
  81853. if (this._wasPreviouslyReady && subMesh.effect) {
  81854. return true;
  81855. }
  81856. }
  81857. if (!subMesh._materialDefines) {
  81858. subMesh._materialDefines = new GridMaterialDefines();
  81859. }
  81860. var defines = subMesh._materialDefines;
  81861. var scene = this.getScene();
  81862. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81863. if (this._renderId === scene.getRenderId()) {
  81864. return true;
  81865. }
  81866. }
  81867. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81868. defines.TRANSPARENT = !defines.TRANSPARENT;
  81869. defines.markAsUnprocessed();
  81870. }
  81871. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81872. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81873. defines.markAsUnprocessed();
  81874. }
  81875. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81876. // Get correct effect
  81877. if (defines.isDirty) {
  81878. defines.markAsProcessed();
  81879. scene.resetCachedMaterial();
  81880. // Attributes
  81881. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81882. // Defines
  81883. var join = defines.toString();
  81884. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81885. }
  81886. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81887. return false;
  81888. }
  81889. this._renderId = scene.getRenderId();
  81890. this._wasPreviouslyReady = true;
  81891. return true;
  81892. };
  81893. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81894. var scene = this.getScene();
  81895. var defines = subMesh._materialDefines;
  81896. if (!defines) {
  81897. return;
  81898. }
  81899. var effect = subMesh.effect;
  81900. if (!effect) {
  81901. return;
  81902. }
  81903. this._activeEffect = effect;
  81904. // Matrices
  81905. this.bindOnlyWorldMatrix(world);
  81906. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81907. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81908. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81909. // Uniforms
  81910. if (this._mustRebind(scene, effect)) {
  81911. this._activeEffect.setColor3("mainColor", this.mainColor);
  81912. this._activeEffect.setColor3("lineColor", this.lineColor);
  81913. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81914. this._gridControl.x = this.gridRatio;
  81915. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81916. this._gridControl.z = this.minorUnitVisibility;
  81917. this._gridControl.w = this.opacity;
  81918. this._activeEffect.setVector4("gridControl", this._gridControl);
  81919. }
  81920. // Fog
  81921. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81922. this._afterBind(mesh, this._activeEffect);
  81923. };
  81924. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81925. _super.prototype.dispose.call(this, forceDisposeEffect);
  81926. };
  81927. GridMaterial.prototype.clone = function (name) {
  81928. var _this = this;
  81929. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81930. };
  81931. GridMaterial.prototype.serialize = function () {
  81932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81933. serializationObject.customType = "BABYLON.GridMaterial";
  81934. return serializationObject;
  81935. };
  81936. GridMaterial.prototype.getClassName = function () {
  81937. return "GridMaterial";
  81938. };
  81939. GridMaterial.Parse = function (source, scene, rootUrl) {
  81940. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81941. };
  81942. __decorate([
  81943. BABYLON.serializeAsColor3()
  81944. ], GridMaterial.prototype, "mainColor", void 0);
  81945. __decorate([
  81946. BABYLON.serializeAsColor3()
  81947. ], GridMaterial.prototype, "lineColor", void 0);
  81948. __decorate([
  81949. BABYLON.serialize()
  81950. ], GridMaterial.prototype, "gridRatio", void 0);
  81951. __decorate([
  81952. BABYLON.serializeAsColor3()
  81953. ], GridMaterial.prototype, "gridOffset", void 0);
  81954. __decorate([
  81955. BABYLON.serialize()
  81956. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81957. __decorate([
  81958. BABYLON.serialize()
  81959. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81960. __decorate([
  81961. BABYLON.serialize()
  81962. ], GridMaterial.prototype, "opacity", void 0);
  81963. __decorate([
  81964. BABYLON.serialize()
  81965. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81966. return GridMaterial;
  81967. }(BABYLON.PushMaterial));
  81968. BABYLON.GridMaterial = GridMaterial;
  81969. })(BABYLON || (BABYLON = {}));
  81970. //# sourceMappingURL=babylon.gridmaterial.js.map
  81971. 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}";
  81972. 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}";
  81973. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81974. var BABYLON;
  81975. (function (BABYLON) {
  81976. var GLTFLoaderCoordinateSystemMode;
  81977. (function (GLTFLoaderCoordinateSystemMode) {
  81978. /**
  81979. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81980. */
  81981. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81982. /**
  81983. * Sets the useRightHandedSystem flag on the scene.
  81984. */
  81985. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81986. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81987. var GLTFLoaderAnimationStartMode;
  81988. (function (GLTFLoaderAnimationStartMode) {
  81989. /**
  81990. * No animation will start.
  81991. */
  81992. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81993. /**
  81994. * The first animation will start.
  81995. */
  81996. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81997. /**
  81998. * All animations will start.
  81999. */
  82000. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  82001. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  82002. var GLTFFileLoader = /** @class */ (function () {
  82003. function GLTFFileLoader() {
  82004. // #region Common options
  82005. /**
  82006. * Raised when the asset has been parsed.
  82007. * The data.json property stores the glTF JSON.
  82008. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  82009. */
  82010. this.onParsedObservable = new BABYLON.Observable();
  82011. // #endregion
  82012. // #region V2 options
  82013. /**
  82014. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  82015. */
  82016. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  82017. /**
  82018. * The animation start mode (NONE, FIRST, ALL).
  82019. */
  82020. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  82021. /**
  82022. * Set to true to compile materials before raising the success callback.
  82023. */
  82024. this.compileMaterials = false;
  82025. /**
  82026. * Set to true to also compile materials with clip planes.
  82027. */
  82028. this.useClipPlane = false;
  82029. /**
  82030. * Set to true to compile shadow generators before raising the success callback.
  82031. */
  82032. this.compileShadowGenerators = false;
  82033. /**
  82034. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  82035. */
  82036. this.onMeshLoadedObservable = new BABYLON.Observable();
  82037. /**
  82038. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  82039. */
  82040. this.onTextureLoadedObservable = new BABYLON.Observable();
  82041. /**
  82042. * Raised when the loader creates a material after parsing the glTF properties of the material.
  82043. */
  82044. this.onMaterialLoadedObservable = new BABYLON.Observable();
  82045. /**
  82046. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  82047. * For assets with LODs, raised when all of the LODs are complete.
  82048. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  82049. */
  82050. this.onCompleteObservable = new BABYLON.Observable();
  82051. /**
  82052. * Raised when the loader is disposed.
  82053. */
  82054. this.onDisposeObservable = new BABYLON.Observable();
  82055. // #endregion
  82056. this._loader = null;
  82057. this.name = "gltf";
  82058. this.extensions = {
  82059. ".gltf": { isBinary: false },
  82060. ".glb": { isBinary: true }
  82061. };
  82062. }
  82063. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  82064. set: function (callback) {
  82065. if (this._onParsedObserver) {
  82066. this.onParsedObservable.remove(this._onParsedObserver);
  82067. }
  82068. this._onParsedObserver = this.onParsedObservable.add(callback);
  82069. },
  82070. enumerable: true,
  82071. configurable: true
  82072. });
  82073. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  82074. set: function (callback) {
  82075. if (this._onMeshLoadedObserver) {
  82076. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  82077. }
  82078. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  82079. },
  82080. enumerable: true,
  82081. configurable: true
  82082. });
  82083. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  82084. set: function (callback) {
  82085. if (this._onTextureLoadedObserver) {
  82086. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  82087. }
  82088. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  82094. set: function (callback) {
  82095. if (this._onMaterialLoadedObserver) {
  82096. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  82097. }
  82098. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  82099. },
  82100. enumerable: true,
  82101. configurable: true
  82102. });
  82103. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  82104. set: function (callback) {
  82105. if (this._onCompleteObserver) {
  82106. this.onCompleteObservable.remove(this._onCompleteObserver);
  82107. }
  82108. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  82109. },
  82110. enumerable: true,
  82111. configurable: true
  82112. });
  82113. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  82114. set: function (callback) {
  82115. if (this._onDisposeObserver) {
  82116. this.onDisposeObservable.remove(this._onDisposeObserver);
  82117. }
  82118. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82119. },
  82120. enumerable: true,
  82121. configurable: true
  82122. });
  82123. /**
  82124. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  82125. */
  82126. GLTFFileLoader.prototype.dispose = function () {
  82127. if (this._loader) {
  82128. this._loader.dispose();
  82129. this._loader = null;
  82130. }
  82131. this.onParsedObservable.clear();
  82132. this.onMeshLoadedObservable.clear();
  82133. this.onTextureLoadedObservable.clear();
  82134. this.onMaterialLoadedObservable.clear();
  82135. this.onCompleteObservable.clear();
  82136. this.onDisposeObservable.notifyObservers(this);
  82137. this.onDisposeObservable.clear();
  82138. };
  82139. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82140. try {
  82141. var loaderData = this._parse(data);
  82142. this._loader = this._getLoader(loaderData);
  82143. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82144. }
  82145. catch (e) {
  82146. if (onError) {
  82147. onError(e.message, e);
  82148. }
  82149. else {
  82150. BABYLON.Tools.Error(e.message);
  82151. }
  82152. }
  82153. };
  82154. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82155. try {
  82156. var loaderData = this._parse(data);
  82157. this._loader = this._getLoader(loaderData);
  82158. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82159. }
  82160. catch (e) {
  82161. if (onError) {
  82162. onError(e.message, e);
  82163. }
  82164. else {
  82165. BABYLON.Tools.Error(e.message);
  82166. }
  82167. }
  82168. };
  82169. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82170. try {
  82171. var loaderData = this._parse(data);
  82172. this._loader = this._getLoader(loaderData);
  82173. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  82174. var container = new BABYLON.AssetContainer(scene);
  82175. Array.prototype.push.apply(container.meshes, meshes);
  82176. Array.prototype.push.apply(container.particleSystems, particleSystems);
  82177. Array.prototype.push.apply(container.skeletons, skeletons);
  82178. container.removeAllFromScene();
  82179. onSuccess(container);
  82180. }, onProgress, onError);
  82181. }
  82182. catch (e) {
  82183. if (onError) {
  82184. onError(e.message, e);
  82185. }
  82186. else {
  82187. BABYLON.Tools.Error(e.message);
  82188. }
  82189. }
  82190. };
  82191. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  82192. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  82193. };
  82194. GLTFFileLoader.prototype.createPlugin = function () {
  82195. return new GLTFFileLoader();
  82196. };
  82197. GLTFFileLoader.prototype._parse = function (data) {
  82198. var parsedData;
  82199. if (data instanceof ArrayBuffer) {
  82200. parsedData = GLTFFileLoader._parseBinary(data);
  82201. }
  82202. else {
  82203. parsedData = {
  82204. json: JSON.parse(data),
  82205. bin: null
  82206. };
  82207. }
  82208. this.onParsedObservable.notifyObservers(parsedData);
  82209. return parsedData;
  82210. };
  82211. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  82212. var _this = this;
  82213. var loaderVersion = { major: 2, minor: 0 };
  82214. var asset = loaderData.json.asset || {};
  82215. var version = GLTFFileLoader._parseVersion(asset.version);
  82216. if (!version) {
  82217. throw new Error("Invalid version: " + asset.version);
  82218. }
  82219. if (asset.minVersion !== undefined) {
  82220. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82221. if (!minVersion) {
  82222. throw new Error("Invalid minimum version: " + asset.minVersion);
  82223. }
  82224. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  82225. throw new Error("Incompatible minimum version: " + asset.minVersion);
  82226. }
  82227. }
  82228. var createLoaders = {
  82229. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  82230. 2: GLTFFileLoader.CreateGLTFLoaderV2
  82231. };
  82232. var createLoader = createLoaders[version.major];
  82233. if (!createLoader) {
  82234. throw new Error("Unsupported version: " + asset.version);
  82235. }
  82236. var loader = createLoader();
  82237. loader.coordinateSystemMode = this.coordinateSystemMode;
  82238. loader.animationStartMode = this.animationStartMode;
  82239. loader.compileMaterials = this.compileMaterials;
  82240. loader.useClipPlane = this.useClipPlane;
  82241. loader.compileShadowGenerators = this.compileShadowGenerators;
  82242. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  82243. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  82244. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  82245. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  82246. return loader;
  82247. };
  82248. GLTFFileLoader._parseBinary = function (data) {
  82249. var Binary = {
  82250. Magic: 0x46546C67
  82251. };
  82252. var binaryReader = new BinaryReader(data);
  82253. var magic = binaryReader.readUint32();
  82254. if (magic !== Binary.Magic) {
  82255. throw new Error("Unexpected magic: " + magic);
  82256. }
  82257. var version = binaryReader.readUint32();
  82258. switch (version) {
  82259. case 1: return GLTFFileLoader._parseV1(binaryReader);
  82260. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82261. }
  82262. throw new Error("Unsupported version: " + version);
  82263. };
  82264. GLTFFileLoader._parseV1 = function (binaryReader) {
  82265. var ContentFormat = {
  82266. JSON: 0
  82267. };
  82268. var length = binaryReader.readUint32();
  82269. if (length != binaryReader.getLength()) {
  82270. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82271. }
  82272. var contentLength = binaryReader.readUint32();
  82273. var contentFormat = binaryReader.readUint32();
  82274. var content;
  82275. switch (contentFormat) {
  82276. case ContentFormat.JSON: {
  82277. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  82278. break;
  82279. }
  82280. default: {
  82281. throw new Error("Unexpected content format: " + contentFormat);
  82282. }
  82283. }
  82284. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  82285. var body = binaryReader.readUint8Array(bytesRemaining);
  82286. return {
  82287. json: content,
  82288. bin: body
  82289. };
  82290. };
  82291. GLTFFileLoader._parseV2 = function (binaryReader) {
  82292. var ChunkFormat = {
  82293. JSON: 0x4E4F534A,
  82294. BIN: 0x004E4942
  82295. };
  82296. var length = binaryReader.readUint32();
  82297. if (length !== binaryReader.getLength()) {
  82298. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82299. }
  82300. // JSON chunk
  82301. var chunkLength = binaryReader.readUint32();
  82302. var chunkFormat = binaryReader.readUint32();
  82303. if (chunkFormat !== ChunkFormat.JSON) {
  82304. throw new Error("First chunk format is not JSON");
  82305. }
  82306. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  82307. // Look for BIN chunk
  82308. var bin = null;
  82309. while (binaryReader.getPosition() < binaryReader.getLength()) {
  82310. var chunkLength_1 = binaryReader.readUint32();
  82311. var chunkFormat_1 = binaryReader.readUint32();
  82312. switch (chunkFormat_1) {
  82313. case ChunkFormat.JSON: {
  82314. throw new Error("Unexpected JSON chunk");
  82315. }
  82316. case ChunkFormat.BIN: {
  82317. bin = binaryReader.readUint8Array(chunkLength_1);
  82318. break;
  82319. }
  82320. default: {
  82321. // ignore unrecognized chunkFormat
  82322. binaryReader.skipBytes(chunkLength_1);
  82323. break;
  82324. }
  82325. }
  82326. }
  82327. return {
  82328. json: json,
  82329. bin: bin
  82330. };
  82331. };
  82332. GLTFFileLoader._parseVersion = function (version) {
  82333. if (version === "1.0" || version === "1.0.1") {
  82334. return {
  82335. major: 1,
  82336. minor: 0
  82337. };
  82338. }
  82339. var match = (version + "").match(/^(\d+)\.(\d+)/);
  82340. if (!match) {
  82341. return null;
  82342. }
  82343. return {
  82344. major: parseInt(match[1]),
  82345. minor: parseInt(match[2])
  82346. };
  82347. };
  82348. GLTFFileLoader._compareVersion = function (a, b) {
  82349. if (a.major > b.major)
  82350. return 1;
  82351. if (a.major < b.major)
  82352. return -1;
  82353. if (a.minor > b.minor)
  82354. return 1;
  82355. if (a.minor < b.minor)
  82356. return -1;
  82357. return 0;
  82358. };
  82359. GLTFFileLoader._decodeBufferToText = function (buffer) {
  82360. var result = "";
  82361. var length = buffer.byteLength;
  82362. for (var i = 0; i < length; i++) {
  82363. result += String.fromCharCode(buffer[i]);
  82364. }
  82365. return result;
  82366. };
  82367. // #endregion
  82368. // #region V1 options
  82369. GLTFFileLoader.IncrementalLoading = true;
  82370. GLTFFileLoader.HomogeneousCoordinates = false;
  82371. return GLTFFileLoader;
  82372. }());
  82373. BABYLON.GLTFFileLoader = GLTFFileLoader;
  82374. var BinaryReader = /** @class */ (function () {
  82375. function BinaryReader(arrayBuffer) {
  82376. this._arrayBuffer = arrayBuffer;
  82377. this._dataView = new DataView(arrayBuffer);
  82378. this._byteOffset = 0;
  82379. }
  82380. BinaryReader.prototype.getPosition = function () {
  82381. return this._byteOffset;
  82382. };
  82383. BinaryReader.prototype.getLength = function () {
  82384. return this._arrayBuffer.byteLength;
  82385. };
  82386. BinaryReader.prototype.readUint32 = function () {
  82387. var value = this._dataView.getUint32(this._byteOffset, true);
  82388. this._byteOffset += 4;
  82389. return value;
  82390. };
  82391. BinaryReader.prototype.readUint8Array = function (length) {
  82392. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  82393. this._byteOffset += length;
  82394. return value;
  82395. };
  82396. BinaryReader.prototype.skipBytes = function (length) {
  82397. this._byteOffset += length;
  82398. };
  82399. return BinaryReader;
  82400. }());
  82401. if (BABYLON.SceneLoader) {
  82402. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  82403. }
  82404. })(BABYLON || (BABYLON = {}));
  82405. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  82406. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82407. var BABYLON;
  82408. (function (BABYLON) {
  82409. var GLTF1;
  82410. (function (GLTF1) {
  82411. /**
  82412. * Enums
  82413. */
  82414. var EComponentType;
  82415. (function (EComponentType) {
  82416. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82417. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82418. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82419. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82420. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82421. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  82422. var EShaderType;
  82423. (function (EShaderType) {
  82424. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  82425. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  82426. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  82427. var EParameterType;
  82428. (function (EParameterType) {
  82429. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  82430. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82431. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  82432. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82433. EParameterType[EParameterType["INT"] = 5124] = "INT";
  82434. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82435. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  82436. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  82437. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  82438. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  82439. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  82440. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  82441. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  82442. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  82443. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  82444. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  82445. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  82446. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  82447. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  82448. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  82449. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  82450. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  82451. var ETextureWrapMode;
  82452. (function (ETextureWrapMode) {
  82453. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82454. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82455. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82456. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  82457. var ETextureFilterType;
  82458. (function (ETextureFilterType) {
  82459. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  82460. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  82461. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82462. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82463. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82464. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82465. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  82466. var ETextureFormat;
  82467. (function (ETextureFormat) {
  82468. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  82469. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  82470. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  82471. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  82472. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  82473. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  82474. var ECullingType;
  82475. (function (ECullingType) {
  82476. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  82477. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  82478. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  82479. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  82480. var EBlendingFunction;
  82481. (function (EBlendingFunction) {
  82482. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  82483. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  82484. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  82485. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  82486. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  82487. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  82488. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82489. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82490. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  82491. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  82492. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  82493. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  82494. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  82495. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  82496. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  82497. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  82498. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82499. })(BABYLON || (BABYLON = {}));
  82500. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82501. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82502. var BABYLON;
  82503. (function (BABYLON) {
  82504. var GLTF1;
  82505. (function (GLTF1) {
  82506. /**
  82507. * Tokenizer. Used for shaders compatibility
  82508. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  82509. */
  82510. var ETokenType;
  82511. (function (ETokenType) {
  82512. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  82513. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  82514. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  82515. })(ETokenType || (ETokenType = {}));
  82516. var Tokenizer = /** @class */ (function () {
  82517. function Tokenizer(toParse) {
  82518. this._pos = 0;
  82519. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  82520. this._toParse = toParse;
  82521. this._maxPos = toParse.length;
  82522. }
  82523. Tokenizer.prototype.getNextToken = function () {
  82524. if (this.isEnd())
  82525. return ETokenType.END_OF_INPUT;
  82526. this.currentString = this.read();
  82527. this.currentToken = ETokenType.UNKNOWN;
  82528. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  82529. this.currentToken = ETokenType.IDENTIFIER;
  82530. this.currentIdentifier = this.currentString;
  82531. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  82532. this.currentIdentifier += this.currentString;
  82533. this.forward();
  82534. }
  82535. }
  82536. return this.currentToken;
  82537. };
  82538. Tokenizer.prototype.peek = function () {
  82539. return this._toParse[this._pos];
  82540. };
  82541. Tokenizer.prototype.read = function () {
  82542. return this._toParse[this._pos++];
  82543. };
  82544. Tokenizer.prototype.forward = function () {
  82545. this._pos++;
  82546. };
  82547. Tokenizer.prototype.isEnd = function () {
  82548. return this._pos >= this._maxPos;
  82549. };
  82550. return Tokenizer;
  82551. }());
  82552. /**
  82553. * Values
  82554. */
  82555. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82556. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82557. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82558. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82559. /**
  82560. * Parse
  82561. */
  82562. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82563. for (var buf in parsedBuffers) {
  82564. var parsedBuffer = parsedBuffers[buf];
  82565. gltfRuntime.buffers[buf] = parsedBuffer;
  82566. gltfRuntime.buffersCount++;
  82567. }
  82568. };
  82569. var parseShaders = function (parsedShaders, gltfRuntime) {
  82570. for (var sha in parsedShaders) {
  82571. var parsedShader = parsedShaders[sha];
  82572. gltfRuntime.shaders[sha] = parsedShader;
  82573. gltfRuntime.shaderscount++;
  82574. }
  82575. };
  82576. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82577. for (var object in parsedObjects) {
  82578. var parsedObject = parsedObjects[object];
  82579. gltfRuntime[runtimeProperty][object] = parsedObject;
  82580. }
  82581. };
  82582. /**
  82583. * Utils
  82584. */
  82585. var normalizeUVs = function (buffer) {
  82586. if (!buffer) {
  82587. return;
  82588. }
  82589. for (var i = 0; i < buffer.length / 2; i++) {
  82590. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82591. }
  82592. };
  82593. var getAttribute = function (attributeParameter) {
  82594. if (attributeParameter.semantic === "NORMAL") {
  82595. return "normal";
  82596. }
  82597. else if (attributeParameter.semantic === "POSITION") {
  82598. return "position";
  82599. }
  82600. else if (attributeParameter.semantic === "JOINT") {
  82601. return "matricesIndices";
  82602. }
  82603. else if (attributeParameter.semantic === "WEIGHT") {
  82604. return "matricesWeights";
  82605. }
  82606. else if (attributeParameter.semantic === "COLOR") {
  82607. return "color";
  82608. }
  82609. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82610. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82611. return "uv" + (channel === 0 ? "" : channel + 1);
  82612. }
  82613. return null;
  82614. };
  82615. /**
  82616. * Loads and creates animations
  82617. */
  82618. var loadAnimations = function (gltfRuntime) {
  82619. for (var anim in gltfRuntime.animations) {
  82620. var animation = gltfRuntime.animations[anim];
  82621. if (!animation.channels || !animation.samplers) {
  82622. continue;
  82623. }
  82624. var lastAnimation = null;
  82625. for (var i = 0; i < animation.channels.length; i++) {
  82626. // Get parameters and load buffers
  82627. var channel = animation.channels[i];
  82628. var sampler = animation.samplers[channel.sampler];
  82629. if (!sampler) {
  82630. continue;
  82631. }
  82632. var inputData = null;
  82633. var outputData = null;
  82634. if (animation.parameters) {
  82635. inputData = animation.parameters[sampler.input];
  82636. outputData = animation.parameters[sampler.output];
  82637. }
  82638. else {
  82639. inputData = sampler.input;
  82640. outputData = sampler.output;
  82641. }
  82642. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82643. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82644. var targetID = channel.target.id;
  82645. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82646. if (targetNode === null) {
  82647. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82648. }
  82649. if (targetNode === null) {
  82650. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82651. continue;
  82652. }
  82653. var isBone = targetNode instanceof BABYLON.Bone;
  82654. // Get target path (position, rotation or scaling)
  82655. var targetPath = channel.target.path;
  82656. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82657. if (targetPathIndex !== -1) {
  82658. targetPath = babylonAnimationPaths[targetPathIndex];
  82659. }
  82660. // Determine animation type
  82661. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82662. if (!isBone) {
  82663. if (targetPath === "rotationQuaternion") {
  82664. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82665. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82666. }
  82667. else {
  82668. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82669. }
  82670. }
  82671. // Create animation and key frames
  82672. var babylonAnimation = null;
  82673. var keys = [];
  82674. var arrayOffset = 0;
  82675. var modifyKey = false;
  82676. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82677. babylonAnimation = lastAnimation;
  82678. modifyKey = true;
  82679. }
  82680. if (!modifyKey) {
  82681. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82682. }
  82683. // For each frame
  82684. for (var j = 0; j < bufferInput.length; j++) {
  82685. var value = null;
  82686. if (targetPath === "rotationQuaternion") {
  82687. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82688. arrayOffset += 4;
  82689. }
  82690. else {
  82691. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82692. arrayOffset += 3;
  82693. }
  82694. if (isBone) {
  82695. var bone = targetNode;
  82696. var translation = BABYLON.Vector3.Zero();
  82697. var rotationQuaternion = new BABYLON.Quaternion();
  82698. var scaling = BABYLON.Vector3.Zero();
  82699. // Warning on decompose
  82700. var mat = bone.getBaseMatrix();
  82701. if (modifyKey && lastAnimation) {
  82702. mat = lastAnimation.getKeys()[j].value;
  82703. }
  82704. mat.decompose(scaling, rotationQuaternion, translation);
  82705. if (targetPath === "position") {
  82706. translation = value;
  82707. }
  82708. else if (targetPath === "rotationQuaternion") {
  82709. rotationQuaternion = value;
  82710. }
  82711. else {
  82712. scaling = value;
  82713. }
  82714. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82715. }
  82716. if (!modifyKey) {
  82717. keys.push({
  82718. frame: bufferInput[j],
  82719. value: value
  82720. });
  82721. }
  82722. else if (lastAnimation) {
  82723. lastAnimation.getKeys()[j].value = value;
  82724. }
  82725. }
  82726. // Finish
  82727. if (!modifyKey && babylonAnimation) {
  82728. babylonAnimation.setKeys(keys);
  82729. targetNode.animations.push(babylonAnimation);
  82730. }
  82731. lastAnimation = babylonAnimation;
  82732. gltfRuntime.scene.stopAnimation(targetNode);
  82733. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82734. }
  82735. }
  82736. };
  82737. /**
  82738. * Returns the bones transformation matrix
  82739. */
  82740. var configureBoneTransformation = function (node) {
  82741. var mat = null;
  82742. if (node.translation || node.rotation || node.scale) {
  82743. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82744. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82745. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82746. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82747. }
  82748. else {
  82749. mat = BABYLON.Matrix.FromArray(node.matrix);
  82750. }
  82751. return mat;
  82752. };
  82753. /**
  82754. * Returns the parent bone
  82755. */
  82756. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82757. // Try to find
  82758. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82759. if (newSkeleton.bones[i].name === jointName) {
  82760. return newSkeleton.bones[i];
  82761. }
  82762. }
  82763. // Not found, search in gltf nodes
  82764. var nodes = gltfRuntime.nodes;
  82765. for (var nde in nodes) {
  82766. var node = nodes[nde];
  82767. if (!node.jointName) {
  82768. continue;
  82769. }
  82770. var children = node.children;
  82771. for (var i = 0; i < children.length; i++) {
  82772. var child = gltfRuntime.nodes[children[i]];
  82773. if (!child.jointName) {
  82774. continue;
  82775. }
  82776. if (child.jointName === jointName) {
  82777. var mat = configureBoneTransformation(node);
  82778. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82779. bone.id = nde;
  82780. return bone;
  82781. }
  82782. }
  82783. }
  82784. return null;
  82785. };
  82786. /**
  82787. * Returns the appropriate root node
  82788. */
  82789. var getNodeToRoot = function (nodesToRoot, id) {
  82790. for (var i = 0; i < nodesToRoot.length; i++) {
  82791. var nodeToRoot = nodesToRoot[i];
  82792. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82793. var child = nodeToRoot.node.children[j];
  82794. if (child === id) {
  82795. return nodeToRoot.bone;
  82796. }
  82797. }
  82798. }
  82799. return null;
  82800. };
  82801. /**
  82802. * Returns the node with the joint name
  82803. */
  82804. var getJointNode = function (gltfRuntime, jointName) {
  82805. var nodes = gltfRuntime.nodes;
  82806. var node = nodes[jointName];
  82807. if (node) {
  82808. return {
  82809. node: node,
  82810. id: jointName
  82811. };
  82812. }
  82813. for (var nde in nodes) {
  82814. node = nodes[nde];
  82815. if (node.jointName === jointName) {
  82816. return {
  82817. node: node,
  82818. id: nde
  82819. };
  82820. }
  82821. }
  82822. return null;
  82823. };
  82824. /**
  82825. * Checks if a nodes is in joints
  82826. */
  82827. var nodeIsInJoints = function (skins, id) {
  82828. for (var i = 0; i < skins.jointNames.length; i++) {
  82829. if (skins.jointNames[i] === id) {
  82830. return true;
  82831. }
  82832. }
  82833. return false;
  82834. };
  82835. /**
  82836. * Fills the nodes to root for bones and builds hierarchy
  82837. */
  82838. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82839. // Creates nodes for root
  82840. for (var nde in gltfRuntime.nodes) {
  82841. var node = gltfRuntime.nodes[nde];
  82842. var id = nde;
  82843. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82844. continue;
  82845. }
  82846. // Create node to root bone
  82847. var mat = configureBoneTransformation(node);
  82848. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82849. bone.id = id;
  82850. nodesToRoot.push({ bone: bone, node: node, id: id });
  82851. }
  82852. // Parenting
  82853. for (var i = 0; i < nodesToRoot.length; i++) {
  82854. var nodeToRoot = nodesToRoot[i];
  82855. var children = nodeToRoot.node.children;
  82856. for (var j = 0; j < children.length; j++) {
  82857. var child = null;
  82858. for (var k = 0; k < nodesToRoot.length; k++) {
  82859. if (nodesToRoot[k].id === children[j]) {
  82860. child = nodesToRoot[k];
  82861. break;
  82862. }
  82863. }
  82864. if (child) {
  82865. child.bone._parent = nodeToRoot.bone;
  82866. nodeToRoot.bone.children.push(child.bone);
  82867. }
  82868. }
  82869. }
  82870. };
  82871. /**
  82872. * Imports a skeleton
  82873. */
  82874. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82875. if (!newSkeleton) {
  82876. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82877. }
  82878. if (!skins.babylonSkeleton) {
  82879. return newSkeleton;
  82880. }
  82881. // Find the root bones
  82882. var nodesToRoot = [];
  82883. var nodesToRootToAdd = [];
  82884. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82885. newSkeleton.bones = [];
  82886. // Joints
  82887. for (var i = 0; i < skins.jointNames.length; i++) {
  82888. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82889. if (!jointNode) {
  82890. continue;
  82891. }
  82892. var node = jointNode.node;
  82893. if (!node) {
  82894. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82895. continue;
  82896. }
  82897. var id = jointNode.id;
  82898. // Optimize, if the bone already exists...
  82899. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82900. if (existingBone) {
  82901. newSkeleton.bones.push(existingBone);
  82902. continue;
  82903. }
  82904. // Search for parent bone
  82905. var foundBone = false;
  82906. var parentBone = null;
  82907. for (var j = 0; j < i; j++) {
  82908. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82909. if (!jointNode_1) {
  82910. continue;
  82911. }
  82912. var joint = jointNode_1.node;
  82913. if (!joint) {
  82914. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82915. continue;
  82916. }
  82917. var children = joint.children;
  82918. if (!children) {
  82919. continue;
  82920. }
  82921. foundBone = false;
  82922. for (var k = 0; k < children.length; k++) {
  82923. if (children[k] === id) {
  82924. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82925. foundBone = true;
  82926. break;
  82927. }
  82928. }
  82929. if (foundBone) {
  82930. break;
  82931. }
  82932. }
  82933. // Create bone
  82934. var mat = configureBoneTransformation(node);
  82935. if (!parentBone && nodesToRoot.length > 0) {
  82936. parentBone = getNodeToRoot(nodesToRoot, id);
  82937. if (parentBone) {
  82938. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82939. nodesToRootToAdd.push(parentBone);
  82940. }
  82941. }
  82942. }
  82943. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82944. bone.id = id;
  82945. }
  82946. // Polish
  82947. var bones = newSkeleton.bones;
  82948. newSkeleton.bones = [];
  82949. for (var i = 0; i < skins.jointNames.length; i++) {
  82950. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82951. if (!jointNode) {
  82952. continue;
  82953. }
  82954. for (var j = 0; j < bones.length; j++) {
  82955. if (bones[j].id === jointNode.id) {
  82956. newSkeleton.bones.push(bones[j]);
  82957. break;
  82958. }
  82959. }
  82960. }
  82961. newSkeleton.prepare();
  82962. // Finish
  82963. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82964. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82965. }
  82966. return newSkeleton;
  82967. };
  82968. /**
  82969. * Imports a mesh and its geometries
  82970. */
  82971. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82972. if (!newMesh) {
  82973. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82974. newMesh.id = id;
  82975. }
  82976. if (!node.babylonNode) {
  82977. return newMesh;
  82978. }
  82979. var subMaterials = [];
  82980. var vertexData = new BABYLON.VertexData();
  82981. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82982. var verticesStarts = new Array();
  82983. var verticesCounts = new Array();
  82984. var indexStarts = new Array();
  82985. var indexCounts = new Array();
  82986. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82987. var meshID = meshes[meshIndex];
  82988. var mesh = gltfRuntime.meshes[meshID];
  82989. if (!mesh) {
  82990. continue;
  82991. }
  82992. // Positions, normals and UVs
  82993. for (var i = 0; i < mesh.primitives.length; i++) {
  82994. // Temporary vertex data
  82995. var tempVertexData = new BABYLON.VertexData();
  82996. var primitive = mesh.primitives[i];
  82997. if (primitive.mode !== 4) {
  82998. // continue;
  82999. }
  83000. var attributes = primitive.attributes;
  83001. var accessor = null;
  83002. var buffer = null;
  83003. // Set positions, normal and uvs
  83004. for (var semantic in attributes) {
  83005. // Link accessor and buffer view
  83006. accessor = gltfRuntime.accessors[attributes[semantic]];
  83007. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  83008. if (semantic === "NORMAL") {
  83009. tempVertexData.normals = new Float32Array(buffer.length);
  83010. tempVertexData.normals.set(buffer);
  83011. }
  83012. else if (semantic === "POSITION") {
  83013. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  83014. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  83015. for (var j = 0; j < buffer.length; j += 4) {
  83016. tempVertexData.positions[j] = buffer[j];
  83017. tempVertexData.positions[j + 1] = buffer[j + 1];
  83018. tempVertexData.positions[j + 2] = buffer[j + 2];
  83019. }
  83020. }
  83021. else {
  83022. tempVertexData.positions = new Float32Array(buffer.length);
  83023. tempVertexData.positions.set(buffer);
  83024. }
  83025. verticesCounts.push(tempVertexData.positions.length);
  83026. }
  83027. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  83028. var channel = Number(semantic.split("_")[1]);
  83029. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  83030. var uvs = new Float32Array(buffer.length);
  83031. uvs.set(buffer);
  83032. normalizeUVs(uvs);
  83033. tempVertexData.set(uvs, uvKind);
  83034. }
  83035. else if (semantic === "JOINT") {
  83036. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  83037. tempVertexData.matricesIndices.set(buffer);
  83038. }
  83039. else if (semantic === "WEIGHT") {
  83040. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  83041. tempVertexData.matricesWeights.set(buffer);
  83042. }
  83043. else if (semantic === "COLOR") {
  83044. tempVertexData.colors = new Float32Array(buffer.length);
  83045. tempVertexData.colors.set(buffer);
  83046. }
  83047. }
  83048. // Indices
  83049. accessor = gltfRuntime.accessors[primitive.indices];
  83050. if (accessor) {
  83051. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  83052. tempVertexData.indices = new Int32Array(buffer.length);
  83053. tempVertexData.indices.set(buffer);
  83054. indexCounts.push(tempVertexData.indices.length);
  83055. }
  83056. else {
  83057. // Set indices on the fly
  83058. var indices = [];
  83059. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  83060. indices.push(j);
  83061. }
  83062. tempVertexData.indices = new Int32Array(indices);
  83063. indexCounts.push(tempVertexData.indices.length);
  83064. }
  83065. vertexData.merge(tempVertexData);
  83066. // Sub material
  83067. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  83068. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  83069. // Update vertices start and index start
  83070. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  83071. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  83072. }
  83073. }
  83074. var material;
  83075. if (subMaterials.length > 1) {
  83076. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  83077. material.subMaterials = subMaterials;
  83078. }
  83079. else {
  83080. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  83081. }
  83082. if (subMaterials.length === 1) {
  83083. material = subMaterials[0];
  83084. }
  83085. if (!newMesh.material) {
  83086. newMesh.material = material;
  83087. }
  83088. // Apply geometry
  83089. geometry.setAllVerticesData(vertexData, false);
  83090. newMesh.computeWorldMatrix(true);
  83091. // Apply submeshes
  83092. newMesh.subMeshes = [];
  83093. var index = 0;
  83094. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  83095. var meshID = meshes[meshIndex];
  83096. var mesh = gltfRuntime.meshes[meshID];
  83097. if (!mesh) {
  83098. continue;
  83099. }
  83100. for (var i = 0; i < mesh.primitives.length; i++) {
  83101. if (mesh.primitives[i].mode !== 4) {
  83102. //continue;
  83103. }
  83104. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  83105. index++;
  83106. }
  83107. }
  83108. // Finish
  83109. return newMesh;
  83110. };
  83111. /**
  83112. * Configure node transformation from position, rotation and scaling
  83113. */
  83114. var configureNode = function (newNode, position, rotation, scaling) {
  83115. if (newNode.position) {
  83116. newNode.position = position;
  83117. }
  83118. if (newNode.rotationQuaternion || newNode.rotation) {
  83119. newNode.rotationQuaternion = rotation;
  83120. }
  83121. if (newNode.scaling) {
  83122. newNode.scaling = scaling;
  83123. }
  83124. };
  83125. /**
  83126. * Configures node from transformation matrix
  83127. */
  83128. var configureNodeFromMatrix = function (newNode, node, parent) {
  83129. if (node.matrix) {
  83130. var position = new BABYLON.Vector3(0, 0, 0);
  83131. var rotation = new BABYLON.Quaternion();
  83132. var scaling = new BABYLON.Vector3(0, 0, 0);
  83133. var mat = BABYLON.Matrix.FromArray(node.matrix);
  83134. mat.decompose(scaling, rotation, position);
  83135. configureNode(newNode, position, rotation, scaling);
  83136. }
  83137. else if (node.translation && node.rotation && node.scale) {
  83138. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  83139. }
  83140. newNode.computeWorldMatrix(true);
  83141. };
  83142. /**
  83143. * Imports a node
  83144. */
  83145. var importNode = function (gltfRuntime, node, id, parent) {
  83146. var lastNode = null;
  83147. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  83148. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  83149. return null;
  83150. }
  83151. }
  83152. // Meshes
  83153. if (node.skin) {
  83154. if (node.meshes) {
  83155. var skin = gltfRuntime.skins[node.skin];
  83156. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  83157. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  83158. if (newMesh.skeleton === null) {
  83159. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  83160. if (!skin.babylonSkeleton) {
  83161. skin.babylonSkeleton = newMesh.skeleton;
  83162. }
  83163. }
  83164. lastNode = newMesh;
  83165. }
  83166. }
  83167. else if (node.meshes) {
  83168. /**
  83169. * Improve meshes property
  83170. */
  83171. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  83172. lastNode = newMesh;
  83173. }
  83174. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83175. var light = gltfRuntime.lights[node.light];
  83176. if (light) {
  83177. if (light.type === "ambient") {
  83178. var ambienLight = light[light.type];
  83179. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83180. hemiLight.name = node.name || "";
  83181. if (ambienLight.color) {
  83182. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  83183. }
  83184. lastNode = hemiLight;
  83185. }
  83186. else if (light.type === "directional") {
  83187. var directionalLight = light[light.type];
  83188. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83189. dirLight.name = node.name || "";
  83190. if (directionalLight.color) {
  83191. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  83192. }
  83193. lastNode = dirLight;
  83194. }
  83195. else if (light.type === "point") {
  83196. var pointLight = light[light.type];
  83197. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83198. ptLight.name = node.name || "";
  83199. if (pointLight.color) {
  83200. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  83201. }
  83202. lastNode = ptLight;
  83203. }
  83204. else if (light.type === "spot") {
  83205. var spotLight = light[light.type];
  83206. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  83207. spLight.name = node.name || "";
  83208. if (spotLight.color) {
  83209. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  83210. }
  83211. if (spotLight.fallOfAngle) {
  83212. spLight.angle = spotLight.fallOfAngle;
  83213. }
  83214. if (spotLight.fallOffExponent) {
  83215. spLight.exponent = spotLight.fallOffExponent;
  83216. }
  83217. lastNode = spLight;
  83218. }
  83219. }
  83220. }
  83221. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83222. var camera = gltfRuntime.cameras[node.camera];
  83223. if (camera) {
  83224. if (camera.type === "orthographic") {
  83225. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83226. orthoCamera.name = node.name || "";
  83227. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  83228. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83229. lastNode = orthoCamera;
  83230. }
  83231. else if (camera.type === "perspective") {
  83232. var perspectiveCamera = camera[camera.type];
  83233. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83234. persCamera.name = node.name || "";
  83235. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83236. if (!perspectiveCamera.aspectRatio) {
  83237. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  83238. }
  83239. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  83240. persCamera.maxZ = perspectiveCamera.zfar;
  83241. persCamera.minZ = perspectiveCamera.znear;
  83242. }
  83243. lastNode = persCamera;
  83244. }
  83245. }
  83246. }
  83247. // Empty node
  83248. if (!node.jointName) {
  83249. if (node.babylonNode) {
  83250. return node.babylonNode;
  83251. }
  83252. else if (lastNode === null) {
  83253. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  83254. node.babylonNode = dummy;
  83255. lastNode = dummy;
  83256. }
  83257. }
  83258. if (lastNode !== null) {
  83259. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  83260. configureNodeFromMatrix(lastNode, node, parent);
  83261. }
  83262. else {
  83263. var translation = node.translation || [0, 0, 0];
  83264. var rotation = node.rotation || [0, 0, 0, 1];
  83265. var scale = node.scale || [1, 1, 1];
  83266. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  83267. }
  83268. lastNode.updateCache(true);
  83269. node.babylonNode = lastNode;
  83270. }
  83271. return lastNode;
  83272. };
  83273. /**
  83274. * Traverses nodes and creates them
  83275. */
  83276. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  83277. if (meshIncluded === void 0) { meshIncluded = false; }
  83278. var node = gltfRuntime.nodes[id];
  83279. var newNode = null;
  83280. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  83281. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  83282. meshIncluded = true;
  83283. }
  83284. else {
  83285. meshIncluded = false;
  83286. }
  83287. }
  83288. else {
  83289. meshIncluded = true;
  83290. }
  83291. if (!node.jointName && meshIncluded) {
  83292. newNode = importNode(gltfRuntime, node, id, parent);
  83293. if (newNode !== null) {
  83294. newNode.id = id;
  83295. newNode.parent = parent;
  83296. }
  83297. }
  83298. if (node.children) {
  83299. for (var i = 0; i < node.children.length; i++) {
  83300. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  83301. }
  83302. }
  83303. };
  83304. /**
  83305. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  83306. */
  83307. var postLoad = function (gltfRuntime) {
  83308. // Nodes
  83309. var currentScene = gltfRuntime.currentScene;
  83310. if (currentScene) {
  83311. for (var i = 0; i < currentScene.nodes.length; i++) {
  83312. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83313. }
  83314. }
  83315. else {
  83316. for (var thing in gltfRuntime.scenes) {
  83317. currentScene = gltfRuntime.scenes[thing];
  83318. for (var i = 0; i < currentScene.nodes.length; i++) {
  83319. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83320. }
  83321. }
  83322. }
  83323. // Set animations
  83324. loadAnimations(gltfRuntime);
  83325. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  83326. var skeleton = gltfRuntime.scene.skeletons[i];
  83327. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  83328. }
  83329. };
  83330. /**
  83331. * onBind shaderrs callback to set uniforms and matrices
  83332. */
  83333. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  83334. var materialValues = material.values || technique.parameters;
  83335. for (var unif in unTreatedUniforms) {
  83336. var uniform = unTreatedUniforms[unif];
  83337. var type = uniform.type;
  83338. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  83339. if (uniform.semantic && !uniform.source && !uniform.node) {
  83340. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  83341. }
  83342. else if (uniform.semantic && (uniform.source || uniform.node)) {
  83343. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  83344. if (source === null) {
  83345. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  83346. }
  83347. if (source === null) {
  83348. continue;
  83349. }
  83350. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  83351. }
  83352. }
  83353. else {
  83354. var value = materialValues[technique.uniforms[unif]];
  83355. if (!value) {
  83356. continue;
  83357. }
  83358. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83359. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  83360. if (texture === null || texture === undefined) {
  83361. continue;
  83362. }
  83363. shaderMaterial.getEffect().setTexture(unif, texture);
  83364. }
  83365. else {
  83366. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  83367. }
  83368. }
  83369. }
  83370. onSuccess(shaderMaterial);
  83371. };
  83372. /**
  83373. * Prepare uniforms to send the only one time
  83374. * Loads the appropriate textures
  83375. */
  83376. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  83377. var materialValues = material.values || technique.parameters;
  83378. var techniqueUniforms = technique.uniforms;
  83379. /**
  83380. * Prepare values here (not matrices)
  83381. */
  83382. for (var unif in unTreatedUniforms) {
  83383. var uniform = unTreatedUniforms[unif];
  83384. var type = uniform.type;
  83385. var value = materialValues[techniqueUniforms[unif]];
  83386. if (value === undefined) {
  83387. // In case the value is the same for all materials
  83388. value = uniform.value;
  83389. }
  83390. if (!value) {
  83391. continue;
  83392. }
  83393. var onLoadTexture = function (uniformName) {
  83394. return function (texture) {
  83395. if (uniform.value && uniformName) {
  83396. // Static uniform
  83397. shaderMaterial.setTexture(uniformName, texture);
  83398. delete unTreatedUniforms[uniformName];
  83399. }
  83400. };
  83401. };
  83402. // Texture (sampler2D)
  83403. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83404. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  83405. }
  83406. else {
  83407. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  83408. // Static uniform
  83409. delete unTreatedUniforms[unif];
  83410. }
  83411. }
  83412. }
  83413. };
  83414. /**
  83415. * Shader compilation failed
  83416. */
  83417. var onShaderCompileError = function (program, shaderMaterial, onError) {
  83418. return function (effect, error) {
  83419. shaderMaterial.dispose(true);
  83420. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  83421. };
  83422. };
  83423. /**
  83424. * Shader compilation success
  83425. */
  83426. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  83427. return function (_) {
  83428. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  83429. shaderMaterial.onBind = function (mesh) {
  83430. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  83431. };
  83432. };
  83433. };
  83434. /**
  83435. * Returns the appropriate uniform if already handled by babylon
  83436. */
  83437. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  83438. for (var unif in technique.uniforms) {
  83439. var uniform = technique.uniforms[unif];
  83440. var uniformParameter = technique.parameters[uniform];
  83441. if (tokenizer.currentIdentifier === unif) {
  83442. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  83443. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83444. if (transformIndex !== -1) {
  83445. delete unTreatedUniforms[unif];
  83446. return babylonTransforms[transformIndex];
  83447. }
  83448. }
  83449. }
  83450. }
  83451. return tokenizer.currentIdentifier;
  83452. };
  83453. /**
  83454. * All shaders loaded. Create materials one by one
  83455. */
  83456. var importMaterials = function (gltfRuntime) {
  83457. // Create materials
  83458. for (var mat in gltfRuntime.materials) {
  83459. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  83460. }
  83461. };
  83462. /**
  83463. * Implementation of the base glTF spec
  83464. */
  83465. var GLTFLoaderBase = /** @class */ (function () {
  83466. function GLTFLoaderBase() {
  83467. }
  83468. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  83469. var gltfRuntime = {
  83470. extensions: {},
  83471. accessors: {},
  83472. buffers: {},
  83473. bufferViews: {},
  83474. meshes: {},
  83475. lights: {},
  83476. cameras: {},
  83477. nodes: {},
  83478. images: {},
  83479. textures: {},
  83480. shaders: {},
  83481. programs: {},
  83482. samplers: {},
  83483. techniques: {},
  83484. materials: {},
  83485. animations: {},
  83486. skins: {},
  83487. extensionsUsed: [],
  83488. scenes: {},
  83489. buffersCount: 0,
  83490. shaderscount: 0,
  83491. scene: scene,
  83492. rootUrl: rootUrl,
  83493. loadedBufferCount: 0,
  83494. loadedBufferViews: {},
  83495. loadedShaderCount: 0,
  83496. importOnlyMeshes: false,
  83497. dummyNodes: []
  83498. };
  83499. // Parse
  83500. if (parsedData.extensions) {
  83501. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  83502. }
  83503. if (parsedData.extensionsUsed) {
  83504. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  83505. }
  83506. if (parsedData.buffers) {
  83507. parseBuffers(parsedData.buffers, gltfRuntime);
  83508. }
  83509. if (parsedData.bufferViews) {
  83510. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  83511. }
  83512. if (parsedData.accessors) {
  83513. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  83514. }
  83515. if (parsedData.meshes) {
  83516. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  83517. }
  83518. if (parsedData.lights) {
  83519. parseObject(parsedData.lights, "lights", gltfRuntime);
  83520. }
  83521. if (parsedData.cameras) {
  83522. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  83523. }
  83524. if (parsedData.nodes) {
  83525. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  83526. }
  83527. if (parsedData.images) {
  83528. parseObject(parsedData.images, "images", gltfRuntime);
  83529. }
  83530. if (parsedData.textures) {
  83531. parseObject(parsedData.textures, "textures", gltfRuntime);
  83532. }
  83533. if (parsedData.shaders) {
  83534. parseShaders(parsedData.shaders, gltfRuntime);
  83535. }
  83536. if (parsedData.programs) {
  83537. parseObject(parsedData.programs, "programs", gltfRuntime);
  83538. }
  83539. if (parsedData.samplers) {
  83540. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83541. }
  83542. if (parsedData.techniques) {
  83543. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83544. }
  83545. if (parsedData.materials) {
  83546. parseObject(parsedData.materials, "materials", gltfRuntime);
  83547. }
  83548. if (parsedData.animations) {
  83549. parseObject(parsedData.animations, "animations", gltfRuntime);
  83550. }
  83551. if (parsedData.skins) {
  83552. parseObject(parsedData.skins, "skins", gltfRuntime);
  83553. }
  83554. if (parsedData.scenes) {
  83555. gltfRuntime.scenes = parsedData.scenes;
  83556. }
  83557. if (parsedData.scene && parsedData.scenes) {
  83558. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83559. }
  83560. return gltfRuntime;
  83561. };
  83562. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83563. var buffer = gltfRuntime.buffers[id];
  83564. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83565. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83566. }
  83567. else {
  83568. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83569. if (request) {
  83570. onError(request.status + " " + request.statusText);
  83571. }
  83572. });
  83573. }
  83574. };
  83575. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83576. var texture = gltfRuntime.textures[id];
  83577. if (!texture || !texture.source) {
  83578. onError("");
  83579. return;
  83580. }
  83581. if (texture.babylonTexture) {
  83582. onSuccess(null);
  83583. return;
  83584. }
  83585. var source = gltfRuntime.images[texture.source];
  83586. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83587. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83588. }
  83589. else {
  83590. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83591. if (request) {
  83592. onError(request.status + " " + request.statusText);
  83593. }
  83594. });
  83595. }
  83596. };
  83597. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83598. var texture = gltfRuntime.textures[id];
  83599. if (texture.babylonTexture) {
  83600. onSuccess(texture.babylonTexture);
  83601. return;
  83602. }
  83603. var sampler = gltfRuntime.samplers[texture.sampler];
  83604. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83605. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83606. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83607. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83608. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83609. var blob = new Blob([buffer]);
  83610. var blobURL = URL.createObjectURL(blob);
  83611. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83612. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83613. if (sampler.wrapS !== undefined) {
  83614. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83615. }
  83616. if (sampler.wrapT !== undefined) {
  83617. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83618. }
  83619. newTexture.name = id;
  83620. texture.babylonTexture = newTexture;
  83621. onSuccess(newTexture);
  83622. };
  83623. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83624. var shader = gltfRuntime.shaders[id];
  83625. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83626. var shaderString = atob(shader.uri.split(",")[1]);
  83627. onSuccess(shaderString);
  83628. }
  83629. else {
  83630. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83631. if (request) {
  83632. onError(request.status + " " + request.statusText);
  83633. }
  83634. });
  83635. }
  83636. };
  83637. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83638. var material = gltfRuntime.materials[id];
  83639. if (!material.technique) {
  83640. if (onError) {
  83641. onError("No technique found.");
  83642. }
  83643. return;
  83644. }
  83645. var technique = gltfRuntime.techniques[material.technique];
  83646. if (!technique) {
  83647. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83648. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83649. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83650. onSuccess(defaultMaterial);
  83651. return;
  83652. }
  83653. var program = gltfRuntime.programs[technique.program];
  83654. var states = technique.states;
  83655. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83656. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83657. var newVertexShader = "";
  83658. var newPixelShader = "";
  83659. var vertexTokenizer = new Tokenizer(vertexShader);
  83660. var pixelTokenizer = new Tokenizer(pixelShader);
  83661. var unTreatedUniforms = {};
  83662. var uniforms = [];
  83663. var attributes = [];
  83664. var samplers = [];
  83665. // Fill uniform, sampler2D and attributes
  83666. for (var unif in technique.uniforms) {
  83667. var uniform = technique.uniforms[unif];
  83668. var uniformParameter = technique.parameters[uniform];
  83669. unTreatedUniforms[unif] = uniformParameter;
  83670. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83671. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83672. if (transformIndex !== -1) {
  83673. uniforms.push(babylonTransforms[transformIndex]);
  83674. delete unTreatedUniforms[unif];
  83675. }
  83676. else {
  83677. uniforms.push(unif);
  83678. }
  83679. }
  83680. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83681. samplers.push(unif);
  83682. }
  83683. else {
  83684. uniforms.push(unif);
  83685. }
  83686. }
  83687. for (var attr in technique.attributes) {
  83688. var attribute = technique.attributes[attr];
  83689. var attributeParameter = technique.parameters[attribute];
  83690. if (attributeParameter.semantic) {
  83691. attributes.push(getAttribute(attributeParameter));
  83692. }
  83693. }
  83694. // Configure vertex shader
  83695. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83696. var tokenType = vertexTokenizer.currentToken;
  83697. if (tokenType !== ETokenType.IDENTIFIER) {
  83698. newVertexShader += vertexTokenizer.currentString;
  83699. continue;
  83700. }
  83701. var foundAttribute = false;
  83702. for (var attr in technique.attributes) {
  83703. var attribute = technique.attributes[attr];
  83704. var attributeParameter = technique.parameters[attribute];
  83705. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83706. newVertexShader += getAttribute(attributeParameter);
  83707. foundAttribute = true;
  83708. break;
  83709. }
  83710. }
  83711. if (foundAttribute) {
  83712. continue;
  83713. }
  83714. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83715. }
  83716. // Configure pixel shader
  83717. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83718. var tokenType = pixelTokenizer.currentToken;
  83719. if (tokenType !== ETokenType.IDENTIFIER) {
  83720. newPixelShader += pixelTokenizer.currentString;
  83721. continue;
  83722. }
  83723. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83724. }
  83725. // Create shader material
  83726. var shaderPath = {
  83727. vertex: program.vertexShader + id,
  83728. fragment: program.fragmentShader + id
  83729. };
  83730. var options = {
  83731. attributes: attributes,
  83732. uniforms: uniforms,
  83733. samplers: samplers,
  83734. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83735. };
  83736. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83737. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83738. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83739. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83740. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83741. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83742. if (states && states.functions) {
  83743. var functions = states.functions;
  83744. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83745. shaderMaterial.backFaceCulling = false;
  83746. }
  83747. var blendFunc = functions.blendFuncSeparate;
  83748. if (blendFunc) {
  83749. 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) {
  83750. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83751. }
  83752. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83753. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83754. }
  83755. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83756. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83757. }
  83758. 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) {
  83759. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83760. }
  83761. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83762. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83763. }
  83764. 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) {
  83765. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83766. }
  83767. }
  83768. }
  83769. };
  83770. return GLTFLoaderBase;
  83771. }());
  83772. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83773. /**
  83774. * glTF V1 Loader
  83775. */
  83776. var GLTFLoader = /** @class */ (function () {
  83777. function GLTFLoader() {
  83778. // #region Stubs for IGLTFLoader interface
  83779. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83780. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83781. this.compileMaterials = false;
  83782. this.useClipPlane = false;
  83783. this.compileShadowGenerators = false;
  83784. this.onDisposeObservable = new BABYLON.Observable();
  83785. this.onMeshLoadedObservable = new BABYLON.Observable();
  83786. this.onTextureLoadedObservable = new BABYLON.Observable();
  83787. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83788. this.onCompleteObservable = new BABYLON.Observable();
  83789. }
  83790. GLTFLoader.RegisterExtension = function (extension) {
  83791. if (GLTFLoader.Extensions[extension.name]) {
  83792. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83793. return;
  83794. }
  83795. GLTFLoader.Extensions[extension.name] = extension;
  83796. };
  83797. GLTFLoader.prototype.dispose = function () { };
  83798. // #endregion
  83799. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83800. var _this = this;
  83801. scene.useRightHandedSystem = true;
  83802. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83803. gltfRuntime.importOnlyMeshes = true;
  83804. if (meshesNames === "") {
  83805. gltfRuntime.importMeshesNames = [];
  83806. }
  83807. else if (typeof meshesNames === "string") {
  83808. gltfRuntime.importMeshesNames = [meshesNames];
  83809. }
  83810. else if (meshesNames && !(meshesNames instanceof Array)) {
  83811. gltfRuntime.importMeshesNames = [meshesNames];
  83812. }
  83813. else {
  83814. gltfRuntime.importMeshesNames = [];
  83815. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83816. }
  83817. // Create nodes
  83818. _this._createNodes(gltfRuntime);
  83819. var meshes = new Array();
  83820. var skeletons = new Array();
  83821. // Fill arrays of meshes and skeletons
  83822. for (var nde in gltfRuntime.nodes) {
  83823. var node = gltfRuntime.nodes[nde];
  83824. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83825. meshes.push(node.babylonNode);
  83826. }
  83827. }
  83828. for (var skl in gltfRuntime.skins) {
  83829. var skin = gltfRuntime.skins[skl];
  83830. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83831. skeletons.push(skin.babylonSkeleton);
  83832. }
  83833. }
  83834. // Load buffers, shaders, materials, etc.
  83835. _this._loadBuffersAsync(gltfRuntime, function () {
  83836. _this._loadShadersAsync(gltfRuntime, function () {
  83837. importMaterials(gltfRuntime);
  83838. postLoad(gltfRuntime);
  83839. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83840. onSuccess(meshes, [], skeletons);
  83841. }
  83842. });
  83843. }, onProgress);
  83844. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83845. onSuccess(meshes, [], skeletons);
  83846. }
  83847. }, onError);
  83848. return true;
  83849. };
  83850. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83851. var _this = this;
  83852. scene.useRightHandedSystem = true;
  83853. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83854. // Load runtime extensios
  83855. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83856. // Create nodes
  83857. _this._createNodes(gltfRuntime);
  83858. // Load buffers, shaders, materials, etc.
  83859. _this._loadBuffersAsync(gltfRuntime, function () {
  83860. _this._loadShadersAsync(gltfRuntime, function () {
  83861. importMaterials(gltfRuntime);
  83862. postLoad(gltfRuntime);
  83863. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83864. onSuccess();
  83865. }
  83866. });
  83867. });
  83868. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83869. onSuccess();
  83870. }
  83871. }, onError);
  83872. }, onError);
  83873. };
  83874. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83875. var hasShaders = false;
  83876. var processShader = function (sha, shader) {
  83877. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83878. gltfRuntime.loadedShaderCount++;
  83879. if (shaderString) {
  83880. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83881. }
  83882. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83883. onload();
  83884. }
  83885. }, function () {
  83886. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83887. });
  83888. };
  83889. for (var sha in gltfRuntime.shaders) {
  83890. hasShaders = true;
  83891. var shader = gltfRuntime.shaders[sha];
  83892. if (shader) {
  83893. processShader.bind(this, sha, shader)();
  83894. }
  83895. else {
  83896. BABYLON.Tools.Error("No shader named: " + sha);
  83897. }
  83898. }
  83899. if (!hasShaders) {
  83900. onload();
  83901. }
  83902. };
  83903. ;
  83904. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83905. var hasBuffers = false;
  83906. var processBuffer = function (buf, buffer) {
  83907. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83908. gltfRuntime.loadedBufferCount++;
  83909. if (bufferView) {
  83910. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83911. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83912. }
  83913. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83914. }
  83915. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83916. onLoad();
  83917. }
  83918. }, function () {
  83919. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83920. });
  83921. };
  83922. for (var buf in gltfRuntime.buffers) {
  83923. hasBuffers = true;
  83924. var buffer = gltfRuntime.buffers[buf];
  83925. if (buffer) {
  83926. processBuffer.bind(this, buf, buffer)();
  83927. }
  83928. else {
  83929. BABYLON.Tools.Error("No buffer named: " + buf);
  83930. }
  83931. }
  83932. if (!hasBuffers) {
  83933. onLoad();
  83934. }
  83935. };
  83936. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83937. var currentScene = gltfRuntime.currentScene;
  83938. if (currentScene) {
  83939. // Only one scene even if multiple scenes are defined
  83940. for (var i = 0; i < currentScene.nodes.length; i++) {
  83941. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83942. }
  83943. }
  83944. else {
  83945. // Load all scenes
  83946. for (var thing in gltfRuntime.scenes) {
  83947. currentScene = gltfRuntime.scenes[thing];
  83948. for (var i = 0; i < currentScene.nodes.length; i++) {
  83949. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83950. }
  83951. }
  83952. }
  83953. };
  83954. GLTFLoader.Extensions = {};
  83955. return GLTFLoader;
  83956. }());
  83957. GLTF1.GLTFLoader = GLTFLoader;
  83958. ;
  83959. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83960. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83961. })(BABYLON || (BABYLON = {}));
  83962. //# sourceMappingURL=babylon.glTFLoader.js.map
  83963. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83964. var BABYLON;
  83965. (function (BABYLON) {
  83966. var GLTF1;
  83967. (function (GLTF1) {
  83968. /**
  83969. * Utils functions for GLTF
  83970. */
  83971. var GLTFUtils = /** @class */ (function () {
  83972. function GLTFUtils() {
  83973. }
  83974. /**
  83975. * Sets the given "parameter" matrix
  83976. * @param scene: the {BABYLON.Scene} object
  83977. * @param source: the source node where to pick the matrix
  83978. * @param parameter: the GLTF technique parameter
  83979. * @param uniformName: the name of the shader's uniform
  83980. * @param shaderMaterial: the shader material
  83981. */
  83982. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83983. var mat = null;
  83984. if (parameter.semantic === "MODEL") {
  83985. mat = source.getWorldMatrix();
  83986. }
  83987. else if (parameter.semantic === "PROJECTION") {
  83988. mat = scene.getProjectionMatrix();
  83989. }
  83990. else if (parameter.semantic === "VIEW") {
  83991. mat = scene.getViewMatrix();
  83992. }
  83993. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83994. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83995. }
  83996. else if (parameter.semantic === "MODELVIEW") {
  83997. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83998. }
  83999. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  84000. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  84001. }
  84002. else if (parameter.semantic === "MODELINVERSE") {
  84003. mat = source.getWorldMatrix().invert();
  84004. }
  84005. else if (parameter.semantic === "VIEWINVERSE") {
  84006. mat = scene.getViewMatrix().invert();
  84007. }
  84008. else if (parameter.semantic === "PROJECTIONINVERSE") {
  84009. mat = scene.getProjectionMatrix().invert();
  84010. }
  84011. else if (parameter.semantic === "MODELVIEWINVERSE") {
  84012. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  84013. }
  84014. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  84015. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  84016. }
  84017. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  84018. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  84019. }
  84020. else {
  84021. debugger;
  84022. }
  84023. if (mat) {
  84024. switch (parameter.type) {
  84025. case GLTF1.EParameterType.FLOAT_MAT2:
  84026. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  84027. break;
  84028. case GLTF1.EParameterType.FLOAT_MAT3:
  84029. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  84030. break;
  84031. case GLTF1.EParameterType.FLOAT_MAT4:
  84032. shaderMaterial.setMatrix(uniformName, mat);
  84033. break;
  84034. default: break;
  84035. }
  84036. }
  84037. };
  84038. /**
  84039. * Sets the given "parameter" matrix
  84040. * @param shaderMaterial: the shader material
  84041. * @param uniform: the name of the shader's uniform
  84042. * @param value: the value of the uniform
  84043. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  84044. */
  84045. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  84046. switch (type) {
  84047. case GLTF1.EParameterType.FLOAT:
  84048. shaderMaterial.setFloat(uniform, value);
  84049. return true;
  84050. case GLTF1.EParameterType.FLOAT_VEC2:
  84051. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  84052. return true;
  84053. case GLTF1.EParameterType.FLOAT_VEC3:
  84054. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  84055. return true;
  84056. case GLTF1.EParameterType.FLOAT_VEC4:
  84057. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  84058. return true;
  84059. default: return false;
  84060. }
  84061. };
  84062. /**
  84063. * If the uri is a base64 string
  84064. * @param uri: the uri to test
  84065. */
  84066. GLTFUtils.IsBase64 = function (uri) {
  84067. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  84068. };
  84069. /**
  84070. * Decode the base64 uri
  84071. * @param uri: the uri to decode
  84072. */
  84073. GLTFUtils.DecodeBase64 = function (uri) {
  84074. var decodedString = atob(uri.split(",")[1]);
  84075. var bufferLength = decodedString.length;
  84076. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  84077. for (var i = 0; i < bufferLength; i++) {
  84078. bufferView[i] = decodedString.charCodeAt(i);
  84079. }
  84080. return bufferView.buffer;
  84081. };
  84082. /**
  84083. * Returns the wrap mode of the texture
  84084. * @param mode: the mode value
  84085. */
  84086. GLTFUtils.GetWrapMode = function (mode) {
  84087. switch (mode) {
  84088. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  84089. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  84090. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  84091. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  84092. }
  84093. };
  84094. /**
  84095. * Returns the byte stride giving an accessor
  84096. * @param accessor: the GLTF accessor objet
  84097. */
  84098. GLTFUtils.GetByteStrideFromType = function (accessor) {
  84099. // Needs this function since "byteStride" isn't requiered in glTF format
  84100. var type = accessor.type;
  84101. switch (type) {
  84102. case "VEC2": return 2;
  84103. case "VEC3": return 3;
  84104. case "VEC4": return 4;
  84105. case "MAT2": return 4;
  84106. case "MAT3": return 9;
  84107. case "MAT4": return 16;
  84108. default: return 1;
  84109. }
  84110. };
  84111. /**
  84112. * Returns the texture filter mode giving a mode value
  84113. * @param mode: the filter mode value
  84114. */
  84115. GLTFUtils.GetTextureFilterMode = function (mode) {
  84116. switch (mode) {
  84117. case GLTF1.ETextureFilterType.LINEAR:
  84118. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  84119. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  84120. case GLTF1.ETextureFilterType.NEAREST:
  84121. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  84122. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  84123. }
  84124. };
  84125. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  84126. var byteOffset = bufferView.byteOffset + byteOffset;
  84127. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  84128. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  84129. throw new Error("Buffer access is out of range");
  84130. }
  84131. var buffer = loadedBufferView.buffer;
  84132. byteOffset += loadedBufferView.byteOffset;
  84133. switch (componentType) {
  84134. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  84135. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  84136. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  84137. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  84138. default: return new Float32Array(buffer, byteOffset, byteLength);
  84139. }
  84140. };
  84141. /**
  84142. * Returns a buffer from its accessor
  84143. * @param gltfRuntime: the GLTF runtime
  84144. * @param accessor: the GLTF accessor
  84145. */
  84146. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  84147. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  84148. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  84149. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  84150. };
  84151. /**
  84152. * Decodes a buffer view into a string
  84153. * @param view: the buffer view
  84154. */
  84155. GLTFUtils.DecodeBufferToText = function (view) {
  84156. var result = "";
  84157. var length = view.byteLength;
  84158. for (var i = 0; i < length; ++i) {
  84159. result += String.fromCharCode(view[i]);
  84160. }
  84161. return result;
  84162. };
  84163. /**
  84164. * Returns the default material of gltf. Related to
  84165. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  84166. * @param scene: the Babylon.js scene
  84167. */
  84168. GLTFUtils.GetDefaultMaterial = function (scene) {
  84169. if (!GLTFUtils._DefaultMaterial) {
  84170. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  84171. "precision highp float;",
  84172. "",
  84173. "uniform mat4 worldView;",
  84174. "uniform mat4 projection;",
  84175. "",
  84176. "attribute vec3 position;",
  84177. "",
  84178. "void main(void)",
  84179. "{",
  84180. " gl_Position = projection * worldView * vec4(position, 1.0);",
  84181. "}"
  84182. ].join("\n");
  84183. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  84184. "precision highp float;",
  84185. "",
  84186. "uniform vec4 u_emission;",
  84187. "",
  84188. "void main(void)",
  84189. "{",
  84190. " gl_FragColor = u_emission;",
  84191. "}"
  84192. ].join("\n");
  84193. var shaderPath = {
  84194. vertex: "GLTFDefaultMaterial",
  84195. fragment: "GLTFDefaultMaterial"
  84196. };
  84197. var options = {
  84198. attributes: ["position"],
  84199. uniforms: ["worldView", "projection", "u_emission"],
  84200. samplers: new Array(),
  84201. needAlphaBlending: false
  84202. };
  84203. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  84204. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  84205. }
  84206. return GLTFUtils._DefaultMaterial;
  84207. };
  84208. // The GLTF default material
  84209. GLTFUtils._DefaultMaterial = null;
  84210. return GLTFUtils;
  84211. }());
  84212. GLTF1.GLTFUtils = GLTFUtils;
  84213. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84214. })(BABYLON || (BABYLON = {}));
  84215. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84216. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84217. var BABYLON;
  84218. (function (BABYLON) {
  84219. var GLTF1;
  84220. (function (GLTF1) {
  84221. var GLTFLoaderExtension = /** @class */ (function () {
  84222. function GLTFLoaderExtension(name) {
  84223. this._name = name;
  84224. }
  84225. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  84226. get: function () {
  84227. return this._name;
  84228. },
  84229. enumerable: true,
  84230. configurable: true
  84231. });
  84232. /**
  84233. * Defines an override for loading the runtime
  84234. * Return true to stop further extensions from loading the runtime
  84235. */
  84236. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84237. return false;
  84238. };
  84239. /**
  84240. * Defines an onverride for creating gltf runtime
  84241. * Return true to stop further extensions from creating the runtime
  84242. */
  84243. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84244. return false;
  84245. };
  84246. /**
  84247. * Defines an override for loading buffers
  84248. * Return true to stop further extensions from loading this buffer
  84249. */
  84250. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84251. return false;
  84252. };
  84253. /**
  84254. * Defines an override for loading texture buffers
  84255. * Return true to stop further extensions from loading this texture data
  84256. */
  84257. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84258. return false;
  84259. };
  84260. /**
  84261. * Defines an override for creating textures
  84262. * Return true to stop further extensions from loading this texture
  84263. */
  84264. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84265. return false;
  84266. };
  84267. /**
  84268. * Defines an override for loading shader strings
  84269. * Return true to stop further extensions from loading this shader data
  84270. */
  84271. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84272. return false;
  84273. };
  84274. /**
  84275. * Defines an override for loading materials
  84276. * Return true to stop further extensions from loading this material
  84277. */
  84278. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84279. return false;
  84280. };
  84281. // ---------
  84282. // Utilities
  84283. // ---------
  84284. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84285. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84286. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  84287. }, function () {
  84288. setTimeout(function () {
  84289. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84290. });
  84291. });
  84292. };
  84293. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84294. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84295. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  84296. }, function () {
  84297. setTimeout(function () {
  84298. onSuccess();
  84299. });
  84300. });
  84301. };
  84302. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84303. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84304. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84305. }, function () {
  84306. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84307. });
  84308. };
  84309. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  84310. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  84311. };
  84312. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84313. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84314. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84315. }, function () {
  84316. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84317. });
  84318. };
  84319. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84320. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84321. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84322. }, function () {
  84323. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84324. });
  84325. };
  84326. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84327. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84328. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84329. }, function () {
  84330. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84331. });
  84332. };
  84333. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84334. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84335. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84336. }, function () {
  84337. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84338. });
  84339. };
  84340. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  84341. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  84342. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  84343. if (func(loaderExtension)) {
  84344. return;
  84345. }
  84346. }
  84347. defaultFunc();
  84348. };
  84349. return GLTFLoaderExtension;
  84350. }());
  84351. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  84352. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84353. })(BABYLON || (BABYLON = {}));
  84354. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84355. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84356. var BABYLON;
  84357. (function (BABYLON) {
  84358. var GLTF1;
  84359. (function (GLTF1) {
  84360. var BinaryExtensionBufferName = "binary_glTF";
  84361. ;
  84362. ;
  84363. var GLTFBinaryExtension = /** @class */ (function (_super) {
  84364. __extends(GLTFBinaryExtension, _super);
  84365. function GLTFBinaryExtension() {
  84366. return _super.call(this, "KHR_binary_glTF") || this;
  84367. }
  84368. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84369. var extensionsUsed = data.json.extensionsUsed;
  84370. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  84371. return false;
  84372. }
  84373. this._bin = data.bin;
  84374. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84375. return true;
  84376. };
  84377. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84378. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  84379. return false;
  84380. }
  84381. if (id !== BinaryExtensionBufferName) {
  84382. return false;
  84383. }
  84384. onSuccess(this._bin);
  84385. return true;
  84386. };
  84387. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84388. var texture = gltfRuntime.textures[id];
  84389. var source = gltfRuntime.images[texture.source];
  84390. if (!source.extensions || !(this.name in source.extensions)) {
  84391. return false;
  84392. }
  84393. var sourceExt = source.extensions[this.name];
  84394. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  84395. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84396. onSuccess(buffer);
  84397. return true;
  84398. };
  84399. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84400. var shader = gltfRuntime.shaders[id];
  84401. if (!shader.extensions || !(this.name in shader.extensions)) {
  84402. return false;
  84403. }
  84404. var binaryExtensionShader = shader.extensions[this.name];
  84405. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  84406. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84407. setTimeout(function () {
  84408. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  84409. onSuccess(shaderString);
  84410. });
  84411. return true;
  84412. };
  84413. return GLTFBinaryExtension;
  84414. }(GLTF1.GLTFLoaderExtension));
  84415. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  84416. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  84417. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84418. })(BABYLON || (BABYLON = {}));
  84419. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  84420. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84421. var BABYLON;
  84422. (function (BABYLON) {
  84423. var GLTF1;
  84424. (function (GLTF1) {
  84425. ;
  84426. ;
  84427. ;
  84428. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  84429. __extends(GLTFMaterialsCommonExtension, _super);
  84430. function GLTFMaterialsCommonExtension() {
  84431. return _super.call(this, "KHR_materials_common") || this;
  84432. }
  84433. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84434. if (!gltfRuntime.extensions)
  84435. return false;
  84436. var extension = gltfRuntime.extensions[this.name];
  84437. if (!extension)
  84438. return false;
  84439. // Create lights
  84440. var lights = extension.lights;
  84441. if (lights) {
  84442. for (var thing in lights) {
  84443. var light = lights[thing];
  84444. switch (light.type) {
  84445. case "ambient":
  84446. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  84447. var ambient = light.ambient;
  84448. if (ambient) {
  84449. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  84450. }
  84451. break;
  84452. case "point":
  84453. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  84454. var point = light.point;
  84455. if (point) {
  84456. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  84457. }
  84458. break;
  84459. case "directional":
  84460. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  84461. var directional = light.directional;
  84462. if (directional) {
  84463. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  84464. }
  84465. break;
  84466. case "spot":
  84467. var spot = light.spot;
  84468. if (spot) {
  84469. 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);
  84470. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  84471. }
  84472. break;
  84473. default:
  84474. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  84475. break;
  84476. }
  84477. }
  84478. }
  84479. return false;
  84480. };
  84481. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84482. var material = gltfRuntime.materials[id];
  84483. if (!material || !material.extensions)
  84484. return false;
  84485. var extension = material.extensions[this.name];
  84486. if (!extension)
  84487. return false;
  84488. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  84489. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  84490. if (extension.technique === "CONSTANT") {
  84491. standardMaterial.disableLighting = true;
  84492. }
  84493. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  84494. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  84495. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  84496. // Ambient
  84497. if (typeof extension.values.ambient === "string") {
  84498. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  84499. }
  84500. else {
  84501. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  84502. }
  84503. // Diffuse
  84504. if (typeof extension.values.diffuse === "string") {
  84505. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  84506. }
  84507. else {
  84508. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  84509. }
  84510. // Emission
  84511. if (typeof extension.values.emission === "string") {
  84512. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  84513. }
  84514. else {
  84515. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  84516. }
  84517. // Specular
  84518. if (typeof extension.values.specular === "string") {
  84519. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  84520. }
  84521. else {
  84522. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  84523. }
  84524. return true;
  84525. };
  84526. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  84527. // Create buffer from texture url
  84528. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  84529. // Create texture from buffer
  84530. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  84531. }, onError);
  84532. };
  84533. return GLTFMaterialsCommonExtension;
  84534. }(GLTF1.GLTFLoaderExtension));
  84535. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84536. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84537. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84538. })(BABYLON || (BABYLON = {}));
  84539. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84540. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84541. var BABYLON;
  84542. (function (BABYLON) {
  84543. var GLTF2;
  84544. (function (GLTF2) {
  84545. /**
  84546. * Enums
  84547. */
  84548. var EComponentType;
  84549. (function (EComponentType) {
  84550. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84551. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84552. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84553. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84554. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84555. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84556. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84557. var EMeshPrimitiveMode;
  84558. (function (EMeshPrimitiveMode) {
  84559. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84560. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84561. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84562. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84563. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84564. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84565. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84566. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84567. var ETextureMagFilter;
  84568. (function (ETextureMagFilter) {
  84569. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84570. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84571. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84572. var ETextureMinFilter;
  84573. (function (ETextureMinFilter) {
  84574. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84575. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84576. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84577. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84578. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84579. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84580. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84581. var ETextureWrapMode;
  84582. (function (ETextureWrapMode) {
  84583. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84584. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84585. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84586. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84587. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84588. })(BABYLON || (BABYLON = {}));
  84589. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84590. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84591. var BABYLON;
  84592. (function (BABYLON) {
  84593. var GLTF2;
  84594. (function (GLTF2) {
  84595. var GLTFLoaderTracker = /** @class */ (function () {
  84596. function GLTFLoaderTracker(onComplete) {
  84597. this._pendingCount = 0;
  84598. this._callback = onComplete;
  84599. }
  84600. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84601. this._pendingCount++;
  84602. };
  84603. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84604. if (--this._pendingCount === 0) {
  84605. this._callback();
  84606. }
  84607. };
  84608. return GLTFLoaderTracker;
  84609. }());
  84610. var GLTFLoader = /** @class */ (function () {
  84611. function GLTFLoader() {
  84612. this._disposed = false;
  84613. this._defaultSampler = {};
  84614. this._renderReady = false;
  84615. this._requests = new Array();
  84616. this._renderReadyObservable = new BABYLON.Observable();
  84617. // Count of pending work that needs to complete before the asset is rendered.
  84618. this._renderPendingCount = 0;
  84619. // Count of pending work that needs to complete before the loader is disposed.
  84620. this._loaderPendingCount = 0;
  84621. this._loaderTrackers = new Array();
  84622. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84623. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84624. this.compileMaterials = false;
  84625. this.useClipPlane = false;
  84626. this.compileShadowGenerators = false;
  84627. this.onDisposeObservable = new BABYLON.Observable();
  84628. this.onMeshLoadedObservable = new BABYLON.Observable();
  84629. this.onTextureLoadedObservable = new BABYLON.Observable();
  84630. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84631. this.onCompleteObservable = new BABYLON.Observable();
  84632. }
  84633. GLTFLoader.RegisterExtension = function (extension) {
  84634. if (GLTFLoader.Extensions[extension.name]) {
  84635. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84636. return;
  84637. }
  84638. GLTFLoader.Extensions[extension.name] = extension;
  84639. // Keep the order of registration so that extensions registered first are called first.
  84640. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84641. };
  84642. GLTFLoader.prototype.dispose = function () {
  84643. if (this._disposed) {
  84644. return;
  84645. }
  84646. this._disposed = true;
  84647. this._abortRequests();
  84648. this._releaseResources();
  84649. this.onDisposeObservable.notifyObservers(this);
  84650. };
  84651. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84652. var _this = this;
  84653. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84654. if (onSuccess) {
  84655. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84656. }
  84657. }, onProgress, onError);
  84658. };
  84659. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84660. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84661. };
  84662. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84663. var _this = this;
  84664. this._babylonScene = scene;
  84665. this._rootUrl = rootUrl;
  84666. this._successCallback = onSuccess;
  84667. this._progressCallback = onProgress;
  84668. this._errorCallback = onError;
  84669. this._tryCatchOnError(function () {
  84670. _this._loadData(data);
  84671. _this._addPendingData(_this);
  84672. _this._loadDefaultScene(nodeNames);
  84673. _this._loadAnimations();
  84674. _this._removePendingData(_this);
  84675. });
  84676. };
  84677. GLTFLoader.prototype._onProgress = function () {
  84678. if (!this._progressCallback) {
  84679. return;
  84680. }
  84681. var lengthComputable = true;
  84682. var loaded = 0;
  84683. var total = 0;
  84684. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84685. var request = _a[_i];
  84686. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84687. return;
  84688. }
  84689. lengthComputable = lengthComputable && request._lengthComputable;
  84690. loaded += request._loaded;
  84691. total += request._total;
  84692. }
  84693. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84694. };
  84695. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84696. if (this._renderReady) {
  84697. func();
  84698. }
  84699. else {
  84700. this._renderReadyObservable.add(func);
  84701. }
  84702. };
  84703. GLTFLoader.prototype._onRenderReady = function () {
  84704. this._rootNode.babylonMesh.setEnabled(true);
  84705. this._startAnimations();
  84706. if (this._successCallback) {
  84707. this._successCallback();
  84708. }
  84709. this._renderReadyObservable.notifyObservers(this);
  84710. };
  84711. GLTFLoader.prototype._onComplete = function () {
  84712. this._abortRequests();
  84713. this._releaseResources();
  84714. this.onCompleteObservable.notifyObservers(this);
  84715. };
  84716. GLTFLoader.prototype._loadData = function (data) {
  84717. this._gltf = data.json;
  84718. // Assign the index of each object for convinience.
  84719. GLTFLoader._AssignIndices(this._gltf.accessors);
  84720. GLTFLoader._AssignIndices(this._gltf.animations);
  84721. GLTFLoader._AssignIndices(this._gltf.buffers);
  84722. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84723. GLTFLoader._AssignIndices(this._gltf.images);
  84724. GLTFLoader._AssignIndices(this._gltf.materials);
  84725. GLTFLoader._AssignIndices(this._gltf.meshes);
  84726. GLTFLoader._AssignIndices(this._gltf.nodes);
  84727. GLTFLoader._AssignIndices(this._gltf.samplers);
  84728. GLTFLoader._AssignIndices(this._gltf.scenes);
  84729. GLTFLoader._AssignIndices(this._gltf.skins);
  84730. GLTFLoader._AssignIndices(this._gltf.textures);
  84731. if (data.bin) {
  84732. var buffers = this._gltf.buffers;
  84733. if (buffers && buffers[0] && !buffers[0].uri) {
  84734. var binaryBuffer = buffers[0];
  84735. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84736. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84737. }
  84738. binaryBuffer.loadedData = data.bin;
  84739. }
  84740. else {
  84741. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84742. }
  84743. }
  84744. };
  84745. GLTFLoader.prototype._getMeshes = function () {
  84746. var meshes = new Array();
  84747. // Root mesh is always first.
  84748. meshes.push(this._rootNode.babylonMesh);
  84749. var nodes = this._gltf.nodes;
  84750. if (nodes) {
  84751. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84752. var node = nodes_1[_i];
  84753. if (node.babylonMesh) {
  84754. meshes.push(node.babylonMesh);
  84755. }
  84756. }
  84757. }
  84758. return meshes;
  84759. };
  84760. GLTFLoader.prototype._getSkeletons = function () {
  84761. var skeletons = new Array();
  84762. var skins = this._gltf.skins;
  84763. if (skins) {
  84764. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84765. var skin = skins_1[_i];
  84766. if (skin.babylonSkeleton) {
  84767. skeletons.push(skin.babylonSkeleton);
  84768. }
  84769. }
  84770. }
  84771. return skeletons;
  84772. };
  84773. GLTFLoader.prototype._startAnimations = function () {
  84774. var animations = this._gltf.animations;
  84775. if (!animations) {
  84776. return;
  84777. }
  84778. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  84779. var animation = animations_1[_i];
  84780. animation.babylonAnimationGroup.normalize();
  84781. }
  84782. switch (this.animationStartMode) {
  84783. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84784. // do nothing
  84785. break;
  84786. }
  84787. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84788. var animation = animations[0];
  84789. animation.babylonAnimationGroup.start(true);
  84790. break;
  84791. }
  84792. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84793. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  84794. var animation = animations_2[_a];
  84795. animation.babylonAnimationGroup.start(true);
  84796. }
  84797. break;
  84798. }
  84799. default: {
  84800. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84801. return;
  84802. }
  84803. }
  84804. };
  84805. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84806. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84807. if (!scene) {
  84808. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84809. }
  84810. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84811. };
  84812. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84813. var _this = this;
  84814. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84815. switch (this.coordinateSystemMode) {
  84816. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84817. if (!this._babylonScene.useRightHandedSystem) {
  84818. this._rootNode.rotation = [0, 1, 0, 0];
  84819. this._rootNode.scale = [1, 1, -1];
  84820. this._loadTransform(this._rootNode);
  84821. }
  84822. break;
  84823. }
  84824. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84825. this._babylonScene.useRightHandedSystem = true;
  84826. break;
  84827. }
  84828. default: {
  84829. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84830. return;
  84831. }
  84832. }
  84833. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84834. var nodeIndices = scene.nodes;
  84835. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84836. node.parent = parentNode;
  84837. return true;
  84838. }, this._rootNode);
  84839. if (nodeNames) {
  84840. if (!(nodeNames instanceof Array)) {
  84841. nodeNames = [nodeNames];
  84842. }
  84843. var filteredNodeIndices_1 = new Array();
  84844. this._traverseNodes(context, nodeIndices, function (node) {
  84845. if (nodeNames.indexOf(node.name) !== -1) {
  84846. filteredNodeIndices_1.push(node.index);
  84847. node.parent = _this._rootNode;
  84848. return false;
  84849. }
  84850. return true;
  84851. }, this._rootNode);
  84852. nodeIndices = filteredNodeIndices_1;
  84853. }
  84854. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84855. var index = nodeIndices_1[_i];
  84856. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84857. if (!node) {
  84858. throw new Error(context + ": Failed to find node " + index);
  84859. }
  84860. this._loadNode("#/nodes/" + index, node);
  84861. }
  84862. // Disable the root mesh until the asset is ready to render.
  84863. this._rootNode.babylonMesh.setEnabled(false);
  84864. };
  84865. GLTFLoader.prototype._loadNode = function (context, node) {
  84866. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84867. return;
  84868. }
  84869. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84870. this._loadTransform(node);
  84871. if (node.mesh != null) {
  84872. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84873. if (!mesh) {
  84874. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84875. }
  84876. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84877. }
  84878. node.babylonMesh.parent = node.parent.babylonMesh;
  84879. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84880. node.babylonAnimationTargets.push(node.babylonMesh);
  84881. if (node.skin != null) {
  84882. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84883. if (!skin_1) {
  84884. throw new Error(context + ": Failed to find skin " + node.skin);
  84885. }
  84886. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84887. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84888. node.babylonMesh._refreshBoundingInfo(true);
  84889. });
  84890. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84891. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84892. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84893. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84894. }
  84895. if (node.camera != null) {
  84896. // TODO: handle cameras
  84897. }
  84898. if (node.children) {
  84899. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84900. var index = _a[_i];
  84901. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84902. if (!childNode) {
  84903. throw new Error(context + ": Failed to find child node " + index);
  84904. }
  84905. this._loadNode("#/nodes/" + index, childNode);
  84906. }
  84907. }
  84908. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84909. };
  84910. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84911. var _this = this;
  84912. var primitives = mesh.primitives;
  84913. if (!primitives || primitives.length === 0) {
  84914. throw new Error(context + ": Primitives are missing");
  84915. }
  84916. this._createMorphTargets(context, node, mesh);
  84917. this._loadAllVertexDataAsync(context, mesh, function () {
  84918. _this._loadMorphTargets(context, node, mesh);
  84919. var vertexData = new BABYLON.VertexData();
  84920. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84921. var primitive = primitives_1[_i];
  84922. vertexData.merge(primitive.vertexData);
  84923. }
  84924. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84925. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84926. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84927. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84928. node.babylonMesh.subMeshes = [];
  84929. var verticesStart = 0;
  84930. var indicesStart = 0;
  84931. for (var index = 0; index < primitives.length; index++) {
  84932. var vertexData_1 = primitives[index].vertexData;
  84933. var verticesCount = vertexData_1.positions.length;
  84934. var indicesCount = vertexData_1.indices.length;
  84935. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84936. verticesStart += verticesCount;
  84937. indicesStart += indicesCount;
  84938. }
  84939. ;
  84940. });
  84941. if (primitives.length === 1) {
  84942. var primitive = primitives[0];
  84943. if (primitive.material == null) {
  84944. node.babylonMesh.material = this._getDefaultMaterial();
  84945. }
  84946. else {
  84947. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84948. if (!material) {
  84949. throw new Error(context + ": Failed to find material " + primitive.material);
  84950. }
  84951. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84952. if (isNew) {
  84953. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84954. }
  84955. node.babylonMesh.material = babylonMaterial;
  84956. });
  84957. }
  84958. }
  84959. else {
  84960. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84961. node.babylonMesh.material = multiMaterial;
  84962. var subMaterials_1 = multiMaterial.subMaterials;
  84963. var _loop_1 = function (index) {
  84964. var primitive = primitives[index];
  84965. if (primitive.material == null) {
  84966. subMaterials_1[index] = this_1._getDefaultMaterial();
  84967. }
  84968. else {
  84969. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84970. if (!material) {
  84971. throw new Error(context + ": Failed to find material " + primitive.material);
  84972. }
  84973. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84974. if (isNew) {
  84975. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84976. }
  84977. subMaterials_1[index] = babylonMaterial;
  84978. });
  84979. }
  84980. };
  84981. var this_1 = this;
  84982. for (var index = 0; index < primitives.length; index++) {
  84983. _loop_1(index);
  84984. }
  84985. ;
  84986. }
  84987. };
  84988. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84989. var primitives = mesh.primitives;
  84990. var numRemainingPrimitives = primitives.length;
  84991. var _loop_2 = function (index) {
  84992. var primitive = primitives[index];
  84993. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84994. primitive.vertexData = vertexData;
  84995. if (--numRemainingPrimitives === 0) {
  84996. onSuccess();
  84997. }
  84998. });
  84999. };
  85000. var this_2 = this;
  85001. for (var index = 0; index < primitives.length; index++) {
  85002. _loop_2(index);
  85003. }
  85004. };
  85005. /**
  85006. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  85007. * @param {ArrayBufferView} data
  85008. * @param {IGLTFAccessor} accessor
  85009. */
  85010. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  85011. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  85012. return data;
  85013. }
  85014. var buffer = data;
  85015. var factor = 1;
  85016. switch (accessor.componentType) {
  85017. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85018. factor = 1 / 255;
  85019. break;
  85020. }
  85021. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85022. factor = 1 / 65535;
  85023. break;
  85024. }
  85025. default: {
  85026. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  85027. }
  85028. }
  85029. var result = new Float32Array(accessor.count * 2);
  85030. for (var i = 0; i < result.length; ++i) {
  85031. result[i] = buffer[i] * factor;
  85032. }
  85033. return result;
  85034. };
  85035. /**
  85036. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  85037. * @param {ArrayBufferView} data
  85038. * @param {IGLTFAccessor} accessor
  85039. */
  85040. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  85041. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  85042. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  85043. return data;
  85044. }
  85045. var buffer = data;
  85046. var factor = 1;
  85047. switch (accessor.componentType) {
  85048. case GLTF2.EComponentType.FLOAT: {
  85049. factor = 1;
  85050. break;
  85051. }
  85052. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85053. factor = 1 / 255;
  85054. break;
  85055. }
  85056. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85057. factor = 1 / 65535;
  85058. break;
  85059. }
  85060. default: {
  85061. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  85062. }
  85063. }
  85064. var result = new Float32Array(accessor.count * 4);
  85065. if (colorComponentCount === 4) {
  85066. for (var i = 0; i < result.length; ++i) {
  85067. result[i] = buffer[i] * factor;
  85068. }
  85069. }
  85070. else {
  85071. var offset = 0;
  85072. for (var i = 0; i < result.length; ++i) {
  85073. if ((i + 1) % 4 === 0) {
  85074. result[i] = 1;
  85075. }
  85076. else {
  85077. result[i] = buffer[offset++] * factor;
  85078. }
  85079. }
  85080. }
  85081. return result;
  85082. };
  85083. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  85084. var _this = this;
  85085. var attributes = primitive.attributes;
  85086. if (!attributes) {
  85087. throw new Error(context + ": Attributes are missing");
  85088. }
  85089. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  85090. // TODO: handle other primitive modes
  85091. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  85092. }
  85093. var vertexData = new BABYLON.VertexData();
  85094. var numRemainingAttributes = Object.keys(attributes).length;
  85095. var _loop_3 = function (attribute) {
  85096. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  85097. if (!accessor) {
  85098. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  85099. }
  85100. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85101. switch (attribute) {
  85102. case "POSITION": {
  85103. vertexData.positions = data;
  85104. break;
  85105. }
  85106. case "NORMAL": {
  85107. vertexData.normals = data;
  85108. break;
  85109. }
  85110. case "TANGENT": {
  85111. vertexData.tangents = data;
  85112. break;
  85113. }
  85114. case "TEXCOORD_0": {
  85115. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  85116. break;
  85117. }
  85118. case "TEXCOORD_1": {
  85119. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  85120. break;
  85121. }
  85122. case "JOINTS_0": {
  85123. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  85124. break;
  85125. }
  85126. case "WEIGHTS_0": {
  85127. //TODO: need to add support for normalized weights.
  85128. vertexData.matricesWeights = data;
  85129. break;
  85130. }
  85131. case "COLOR_0": {
  85132. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  85133. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  85134. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  85135. mesh.hasVertexAlpha = hasVertexAlpha;
  85136. }
  85137. break;
  85138. }
  85139. default: {
  85140. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85141. break;
  85142. }
  85143. }
  85144. if (--numRemainingAttributes === 0) {
  85145. if (primitive.indices == null) {
  85146. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  85147. for (var i = 0; i < vertexData.indices.length; i++) {
  85148. vertexData.indices[i] = i;
  85149. }
  85150. onSuccess(vertexData);
  85151. }
  85152. else {
  85153. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  85154. if (!indicesAccessor) {
  85155. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  85156. }
  85157. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  85158. vertexData.indices = data;
  85159. onSuccess(vertexData);
  85160. });
  85161. }
  85162. }
  85163. });
  85164. };
  85165. var this_3 = this;
  85166. for (var attribute in attributes) {
  85167. _loop_3(attribute);
  85168. }
  85169. };
  85170. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  85171. var primitives = mesh.primitives;
  85172. var targets = primitives[0].targets;
  85173. if (!targets) {
  85174. return;
  85175. }
  85176. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  85177. var primitive = primitives_2[_i];
  85178. if (!primitive.targets || primitive.targets.length != targets.length) {
  85179. throw new Error(context + ": All primitives are required to list the same number of targets");
  85180. }
  85181. }
  85182. var morphTargetManager = new BABYLON.MorphTargetManager();
  85183. node.babylonMesh.morphTargetManager = morphTargetManager;
  85184. for (var index = 0; index < targets.length; index++) {
  85185. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  85186. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  85187. }
  85188. };
  85189. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  85190. var morphTargetManager = node.babylonMesh.morphTargetManager;
  85191. if (!morphTargetManager) {
  85192. return;
  85193. }
  85194. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  85195. var numTargets = morphTargetManager.numTargets;
  85196. for (var index = 0; index < numTargets; index++) {
  85197. var vertexData = new BABYLON.VertexData();
  85198. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85199. var primitive = _a[_i];
  85200. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  85201. }
  85202. if (!vertexData.positions) {
  85203. throw new Error(context + ": Positions are missing");
  85204. }
  85205. var target = morphTargetManager.getTarget(index);
  85206. target.setPositions(vertexData.positions);
  85207. target.setNormals(vertexData.normals);
  85208. target.setTangents(vertexData.tangents);
  85209. }
  85210. });
  85211. };
  85212. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  85213. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  85214. var _loop_4 = function (primitive) {
  85215. var targets = primitive.targets;
  85216. primitive.targetsVertexData = new Array(targets.length);
  85217. var _loop_5 = function (index) {
  85218. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  85219. primitive.targetsVertexData[index] = vertexData;
  85220. if (--numRemainingTargets === 0) {
  85221. onSuccess();
  85222. }
  85223. });
  85224. };
  85225. for (var index = 0; index < targets.length; index++) {
  85226. _loop_5(index);
  85227. }
  85228. };
  85229. var this_4 = this;
  85230. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85231. var primitive = _a[_i];
  85232. _loop_4(primitive);
  85233. }
  85234. };
  85235. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  85236. var targetVertexData = new BABYLON.VertexData();
  85237. var numRemainingAttributes = Object.keys(attributes).length;
  85238. var _loop_6 = function (attribute) {
  85239. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  85240. if (!accessor) {
  85241. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  85242. }
  85243. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85244. // glTF stores morph target information as deltas while babylon.js expects the final data.
  85245. // As a result we have to add the original data to the delta to calculate the final data.
  85246. var values = data;
  85247. switch (attribute) {
  85248. case "POSITION": {
  85249. for (var i = 0; i < values.length; i++) {
  85250. values[i] += vertexData.positions[i];
  85251. }
  85252. targetVertexData.positions = values;
  85253. break;
  85254. }
  85255. case "NORMAL": {
  85256. for (var i = 0; i < values.length; i++) {
  85257. values[i] += vertexData.normals[i];
  85258. }
  85259. targetVertexData.normals = values;
  85260. break;
  85261. }
  85262. case "TANGENT": {
  85263. // Tangent data for morph targets is stored as xyz delta.
  85264. // The vertexData.tangent is stored as xyzw.
  85265. // So we need to skip every fourth vertexData.tangent.
  85266. for (var i = 0, j = 0; i < values.length; i++, j++) {
  85267. values[i] += vertexData.tangents[j];
  85268. if ((i + 1) % 3 == 0) {
  85269. j++;
  85270. }
  85271. }
  85272. targetVertexData.tangents = values;
  85273. break;
  85274. }
  85275. default: {
  85276. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85277. break;
  85278. }
  85279. }
  85280. if (--numRemainingAttributes === 0) {
  85281. onSuccess(targetVertexData);
  85282. }
  85283. });
  85284. };
  85285. var this_5 = this;
  85286. for (var attribute in attributes) {
  85287. _loop_6(attribute);
  85288. }
  85289. };
  85290. GLTFLoader.prototype._loadTransform = function (node) {
  85291. var position = BABYLON.Vector3.Zero();
  85292. var rotation = BABYLON.Quaternion.Identity();
  85293. var scaling = BABYLON.Vector3.One();
  85294. if (node.matrix) {
  85295. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  85296. matrix.decompose(scaling, rotation, position);
  85297. }
  85298. else {
  85299. if (node.translation)
  85300. position = BABYLON.Vector3.FromArray(node.translation);
  85301. if (node.rotation)
  85302. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  85303. if (node.scale)
  85304. scaling = BABYLON.Vector3.FromArray(node.scale);
  85305. }
  85306. node.babylonMesh.position = position;
  85307. node.babylonMesh.rotationQuaternion = rotation;
  85308. node.babylonMesh.scaling = scaling;
  85309. };
  85310. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  85311. var _this = this;
  85312. if (skin.babylonSkeleton) {
  85313. onSuccess();
  85314. return;
  85315. }
  85316. var skeletonId = "skeleton" + skin.index;
  85317. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  85318. if (skin.inverseBindMatrices == null) {
  85319. this._loadBones(context, skin, null);
  85320. onSuccess();
  85321. }
  85322. else {
  85323. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  85324. if (!accessor) {
  85325. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  85326. }
  85327. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85328. _this._loadBones(context, skin, data);
  85329. onSuccess();
  85330. });
  85331. }
  85332. };
  85333. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  85334. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  85335. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  85336. node.babylonAnimationTargets.push(babylonBone);
  85337. return babylonBone;
  85338. };
  85339. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  85340. var babylonBones = {};
  85341. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  85342. var index = _a[_i];
  85343. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85344. if (!node) {
  85345. throw new Error(context + ": Failed to find joint " + index);
  85346. }
  85347. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  85348. }
  85349. };
  85350. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  85351. var babylonBone = babylonBones[node.index];
  85352. if (babylonBone) {
  85353. return babylonBone;
  85354. }
  85355. var boneIndex = skin.joints.indexOf(node.index);
  85356. var baseMatrix = BABYLON.Matrix.Identity();
  85357. if (inverseBindMatrixData && boneIndex !== -1) {
  85358. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  85359. baseMatrix.invertToRef(baseMatrix);
  85360. }
  85361. var babylonParentBone = null;
  85362. if (node.parent !== this._rootNode) {
  85363. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  85364. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  85365. }
  85366. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  85367. babylonBones[node.index] = babylonBone;
  85368. return babylonBone;
  85369. };
  85370. GLTFLoader.prototype._getNodeMatrix = function (node) {
  85371. return node.matrix ?
  85372. BABYLON.Matrix.FromArray(node.matrix) :
  85373. 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());
  85374. };
  85375. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  85376. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  85377. var index = indices_1[_i];
  85378. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85379. if (!node) {
  85380. throw new Error(context + ": Failed to find node " + index);
  85381. }
  85382. this._traverseNode(context, node, action, parentNode);
  85383. }
  85384. };
  85385. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  85386. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  85387. return;
  85388. }
  85389. if (!action(node, parentNode)) {
  85390. return;
  85391. }
  85392. if (node.children) {
  85393. this._traverseNodes(context, node.children, action, node);
  85394. }
  85395. };
  85396. GLTFLoader.prototype._loadAnimations = function () {
  85397. var animations = this._gltf.animations;
  85398. if (!animations) {
  85399. return;
  85400. }
  85401. for (var index = 0; index < animations.length; index++) {
  85402. var animation = animations[index];
  85403. this._loadAnimation("#/animations/" + index, animation);
  85404. }
  85405. };
  85406. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  85407. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  85408. for (var index = 0; index < animation.channels.length; index++) {
  85409. var channel = GLTFLoader._GetProperty(animation.channels, index);
  85410. if (!channel) {
  85411. throw new Error(context + ": Failed to find channel " + index);
  85412. }
  85413. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  85414. if (!sampler) {
  85415. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  85416. }
  85417. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  85418. }
  85419. };
  85420. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  85421. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  85422. if (!targetNode) {
  85423. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  85424. }
  85425. var targetPath;
  85426. var animationType;
  85427. switch (channel.target.path) {
  85428. case "translation": {
  85429. targetPath = "position";
  85430. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85431. break;
  85432. }
  85433. case "rotation": {
  85434. targetPath = "rotationQuaternion";
  85435. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85436. break;
  85437. }
  85438. case "scale": {
  85439. targetPath = "scaling";
  85440. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85441. break;
  85442. }
  85443. case "weights": {
  85444. targetPath = "influence";
  85445. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  85446. break;
  85447. }
  85448. default: {
  85449. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  85450. }
  85451. }
  85452. var inputData;
  85453. var outputData;
  85454. var checkSuccess = function () {
  85455. if (!inputData || !outputData) {
  85456. return;
  85457. }
  85458. var outputBufferOffset = 0;
  85459. var getNextOutputValue;
  85460. switch (targetPath) {
  85461. case "position": {
  85462. getNextOutputValue = function () {
  85463. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85464. outputBufferOffset += 3;
  85465. return value;
  85466. };
  85467. break;
  85468. }
  85469. case "rotationQuaternion": {
  85470. getNextOutputValue = function () {
  85471. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  85472. outputBufferOffset += 4;
  85473. return value;
  85474. };
  85475. break;
  85476. }
  85477. case "scaling": {
  85478. getNextOutputValue = function () {
  85479. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85480. outputBufferOffset += 3;
  85481. return value;
  85482. };
  85483. break;
  85484. }
  85485. case "influence": {
  85486. getNextOutputValue = function () {
  85487. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  85488. var value = new Array(numTargets);
  85489. for (var i = 0; i < numTargets; i++) {
  85490. value[i] = outputData[outputBufferOffset++];
  85491. }
  85492. return value;
  85493. };
  85494. break;
  85495. }
  85496. }
  85497. sampler.interpolation = sampler.interpolation || "LINEAR";
  85498. var getNextKey;
  85499. switch (sampler.interpolation) {
  85500. case "STEP": {
  85501. getNextKey = function (frameIndex) { return ({
  85502. frame: inputData[frameIndex],
  85503. value: getNextOutputValue(),
  85504. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  85505. }); };
  85506. break;
  85507. }
  85508. case "LINEAR": {
  85509. getNextKey = function (frameIndex) { return ({
  85510. frame: inputData[frameIndex],
  85511. value: getNextOutputValue()
  85512. }); };
  85513. break;
  85514. }
  85515. case "CUBICSPLINE": {
  85516. getNextKey = function (frameIndex) { return ({
  85517. frame: inputData[frameIndex],
  85518. inTangent: getNextOutputValue(),
  85519. value: getNextOutputValue(),
  85520. outTangent: getNextOutputValue()
  85521. }); };
  85522. break;
  85523. }
  85524. default: {
  85525. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  85526. }
  85527. }
  85528. ;
  85529. var keys;
  85530. if (inputData.length === 1) {
  85531. var key = getNextKey(0);
  85532. keys = [
  85533. { frame: key.frame, value: key.value },
  85534. { frame: key.frame + 1, value: key.value }
  85535. ];
  85536. }
  85537. else {
  85538. keys = new Array(inputData.length);
  85539. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85540. keys[frameIndex] = getNextKey(frameIndex);
  85541. }
  85542. }
  85543. if (targetPath === "influence") {
  85544. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85545. var _loop_7 = function (targetIndex) {
  85546. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85547. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85548. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85549. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85550. frame: key.frame,
  85551. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85552. value: key.value[targetIndex],
  85553. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85554. }); }));
  85555. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  85556. };
  85557. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85558. _loop_7(targetIndex);
  85559. }
  85560. }
  85561. else {
  85562. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85563. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85564. babylonAnimation.setKeys(keys);
  85565. if (targetNode.babylonAnimationTargets) {
  85566. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85567. var target = _a[_i];
  85568. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  85569. }
  85570. }
  85571. }
  85572. };
  85573. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85574. if (!inputAccessor) {
  85575. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85576. }
  85577. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85578. inputData = data;
  85579. checkSuccess();
  85580. });
  85581. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85582. if (!outputAccessor) {
  85583. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85584. }
  85585. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85586. outputData = data;
  85587. checkSuccess();
  85588. });
  85589. };
  85590. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85591. var _this = this;
  85592. this._addPendingData(buffer);
  85593. if (buffer.loadedData) {
  85594. onSuccess(buffer.loadedData);
  85595. this._removePendingData(buffer);
  85596. }
  85597. else if (buffer.loadedObservable) {
  85598. buffer.loadedObservable.add(function (buffer) {
  85599. onSuccess(buffer.loadedData);
  85600. _this._removePendingData(buffer);
  85601. });
  85602. }
  85603. else {
  85604. if (!buffer.uri) {
  85605. throw new Error(context + ": Uri is missing");
  85606. }
  85607. buffer.loadedObservable = new BABYLON.Observable();
  85608. buffer.loadedObservable.add(function (buffer) {
  85609. onSuccess(buffer.loadedData);
  85610. _this._removePendingData(buffer);
  85611. });
  85612. this._loadUriAsync(context, buffer.uri, function (data) {
  85613. buffer.loadedData = data;
  85614. buffer.loadedObservable.notifyObservers(buffer);
  85615. buffer.loadedObservable = undefined;
  85616. });
  85617. }
  85618. };
  85619. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85620. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85621. if (!buffer) {
  85622. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85623. }
  85624. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85625. var data;
  85626. try {
  85627. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85628. }
  85629. catch (e) {
  85630. throw new Error(context + ": " + e.message);
  85631. }
  85632. onSuccess(data);
  85633. });
  85634. };
  85635. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85636. var _this = this;
  85637. if (accessor.sparse) {
  85638. throw new Error(context + ": Sparse accessors are not currently supported");
  85639. }
  85640. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85641. if (!bufferView) {
  85642. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85643. }
  85644. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85645. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85646. var data;
  85647. var byteOffset = accessor.byteOffset || 0;
  85648. var byteStride = bufferView.byteStride;
  85649. if (byteStride === 0) {
  85650. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85651. }
  85652. try {
  85653. switch (accessor.componentType) {
  85654. case GLTF2.EComponentType.BYTE: {
  85655. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85656. break;
  85657. }
  85658. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85659. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85660. break;
  85661. }
  85662. case GLTF2.EComponentType.SHORT: {
  85663. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85664. break;
  85665. }
  85666. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85667. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85668. break;
  85669. }
  85670. case GLTF2.EComponentType.UNSIGNED_INT: {
  85671. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85672. break;
  85673. }
  85674. case GLTF2.EComponentType.FLOAT: {
  85675. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85676. break;
  85677. }
  85678. default: {
  85679. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85680. }
  85681. }
  85682. }
  85683. catch (e) {
  85684. throw new Error(context + ": " + e);
  85685. }
  85686. onSuccess(data);
  85687. });
  85688. };
  85689. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85690. byteOffset += data.byteOffset;
  85691. var targetLength = count * numComponents;
  85692. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85693. return new typedArray(data.buffer, byteOffset, targetLength);
  85694. }
  85695. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85696. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85697. var targetBuffer = new typedArray(targetLength);
  85698. var sourceIndex = 0;
  85699. var targetIndex = 0;
  85700. while (targetIndex < targetLength) {
  85701. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85702. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85703. targetIndex++;
  85704. }
  85705. sourceIndex += elementStride;
  85706. }
  85707. return targetBuffer;
  85708. };
  85709. GLTFLoader.prototype._addPendingData = function (data) {
  85710. if (!this._renderReady) {
  85711. this._renderPendingCount++;
  85712. }
  85713. this._addLoaderPendingData(data);
  85714. };
  85715. GLTFLoader.prototype._removePendingData = function (data) {
  85716. var _this = this;
  85717. if (!this._renderReady) {
  85718. if (--this._renderPendingCount === 0) {
  85719. this._addLoaderPendingData(this);
  85720. this._compileMaterialsAsync(function () {
  85721. _this._compileShadowGeneratorsAsync(function () {
  85722. _this._removeLoaderPendingData(_this);
  85723. _this._renderReady = true;
  85724. _this._onRenderReady();
  85725. });
  85726. });
  85727. }
  85728. }
  85729. this._removeLoaderPendingData(data);
  85730. };
  85731. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85732. this._loaderPendingCount++;
  85733. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85734. var tracker = _a[_i];
  85735. tracker._addPendingData(data);
  85736. }
  85737. };
  85738. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85739. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85740. var tracker = _a[_i];
  85741. tracker._removePendingData(data);
  85742. }
  85743. if (--this._loaderPendingCount === 0) {
  85744. this._onComplete();
  85745. }
  85746. };
  85747. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85748. var _this = this;
  85749. var tracker = new GLTFLoaderTracker(function () {
  85750. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85751. onComplete();
  85752. });
  85753. this._loaderTrackers.push(tracker);
  85754. this._addLoaderPendingData(tracker);
  85755. action();
  85756. this._removeLoaderPendingData(tracker);
  85757. };
  85758. GLTFLoader.prototype._getDefaultMaterial = function () {
  85759. if (!this._defaultMaterial) {
  85760. var id = "__gltf_default";
  85761. var material = this._babylonScene.getMaterialByName(id);
  85762. if (!material) {
  85763. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85764. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85765. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85766. material.metallic = 1;
  85767. material.roughness = 1;
  85768. }
  85769. this._defaultMaterial = material;
  85770. }
  85771. return this._defaultMaterial;
  85772. };
  85773. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85774. var babylonMaterial = material.babylonMaterial;
  85775. // Ensure metallic workflow
  85776. babylonMaterial.metallic = 1;
  85777. babylonMaterial.roughness = 1;
  85778. var properties = material.pbrMetallicRoughness;
  85779. if (!properties) {
  85780. return;
  85781. }
  85782. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85783. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85784. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85785. if (properties.baseColorTexture) {
  85786. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85787. if (!texture) {
  85788. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85789. }
  85790. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85791. }
  85792. if (properties.metallicRoughnessTexture) {
  85793. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85794. if (!texture) {
  85795. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85796. }
  85797. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85798. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85799. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85800. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85801. }
  85802. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85803. };
  85804. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85805. if (material.babylonMaterial) {
  85806. assign(material.babylonMaterial, false);
  85807. return;
  85808. }
  85809. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85810. return;
  85811. }
  85812. this._createPbrMaterial(material);
  85813. this._loadMaterialBaseProperties(context, material);
  85814. this._loadMaterialMetallicRoughnessProperties(context, material);
  85815. assign(material.babylonMaterial, true);
  85816. };
  85817. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85818. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85819. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85820. material.babylonMaterial = babylonMaterial;
  85821. };
  85822. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85823. var babylonMaterial = material.babylonMaterial;
  85824. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85825. if (material.doubleSided) {
  85826. babylonMaterial.backFaceCulling = false;
  85827. babylonMaterial.twoSidedLighting = true;
  85828. }
  85829. if (material.normalTexture) {
  85830. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85831. if (!texture) {
  85832. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85833. }
  85834. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85835. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85836. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85837. if (material.normalTexture.scale != null) {
  85838. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85839. }
  85840. }
  85841. if (material.occlusionTexture) {
  85842. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85843. if (!texture) {
  85844. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85845. }
  85846. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85847. babylonMaterial.useAmbientInGrayScale = true;
  85848. if (material.occlusionTexture.strength != null) {
  85849. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85850. }
  85851. }
  85852. if (material.emissiveTexture) {
  85853. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85854. if (!texture) {
  85855. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85856. }
  85857. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85858. }
  85859. };
  85860. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85861. var babylonMaterial = material.babylonMaterial;
  85862. var alphaMode = material.alphaMode || "OPAQUE";
  85863. switch (alphaMode) {
  85864. case "OPAQUE": {
  85865. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85866. break;
  85867. }
  85868. case "MASK": {
  85869. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85870. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85871. if (colorFactor) {
  85872. if (colorFactor[3] == 0) {
  85873. babylonMaterial.alphaCutOff = 1;
  85874. }
  85875. else {
  85876. babylonMaterial.alphaCutOff /= colorFactor[3];
  85877. }
  85878. }
  85879. if (babylonMaterial.albedoTexture) {
  85880. babylonMaterial.albedoTexture.hasAlpha = true;
  85881. }
  85882. break;
  85883. }
  85884. case "BLEND": {
  85885. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85886. if (colorFactor) {
  85887. babylonMaterial.alpha = colorFactor[3];
  85888. }
  85889. if (babylonMaterial.albedoTexture) {
  85890. babylonMaterial.albedoTexture.hasAlpha = true;
  85891. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85892. }
  85893. break;
  85894. }
  85895. default: {
  85896. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85897. }
  85898. }
  85899. };
  85900. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85901. var _this = this;
  85902. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85903. if (!sampler) {
  85904. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85905. }
  85906. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85907. this._addPendingData(texture);
  85908. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85909. _this._tryCatchOnError(function () {
  85910. _this._removePendingData(texture);
  85911. });
  85912. }, function (message) {
  85913. _this._tryCatchOnError(function () {
  85914. throw new Error(context + ": " + message);
  85915. });
  85916. });
  85917. if (texture.url) {
  85918. babylonTexture.updateURL(texture.url);
  85919. }
  85920. else if (texture.dataReadyObservable) {
  85921. texture.dataReadyObservable.add(function (texture) {
  85922. babylonTexture.updateURL(texture.url);
  85923. });
  85924. }
  85925. else {
  85926. texture.dataReadyObservable = new BABYLON.Observable();
  85927. texture.dataReadyObservable.add(function (texture) {
  85928. babylonTexture.updateURL(texture.url);
  85929. });
  85930. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85931. if (!image_1) {
  85932. throw new Error(context + ": Failed to find source " + texture.source);
  85933. }
  85934. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85935. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85936. texture.dataReadyObservable.notifyObservers(texture);
  85937. texture.dataReadyObservable = undefined;
  85938. });
  85939. }
  85940. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85941. babylonTexture.wrapU = sampler.wrapU;
  85942. babylonTexture.wrapV = sampler.wrapV;
  85943. babylonTexture.name = texture.name || "texture" + texture.index;
  85944. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85945. return babylonTexture;
  85946. };
  85947. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85948. if (sampler.noMipMaps != undefined) {
  85949. return;
  85950. }
  85951. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85952. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85953. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85954. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85955. };
  85956. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85957. if (image.uri) {
  85958. this._loadUriAsync(context, image.uri, onSuccess);
  85959. }
  85960. else {
  85961. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85962. if (!bufferView) {
  85963. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85964. }
  85965. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85966. }
  85967. };
  85968. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85969. var _this = this;
  85970. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85971. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85972. return;
  85973. }
  85974. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85975. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85976. }
  85977. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85978. _this._tryCatchOnError(function () {
  85979. onSuccess(new Uint8Array(data));
  85980. });
  85981. }, function (event) {
  85982. _this._tryCatchOnError(function () {
  85983. if (request && !_this._renderReady) {
  85984. request._lengthComputable = event.lengthComputable;
  85985. request._loaded = event.loaded;
  85986. request._total = event.total;
  85987. _this._onProgress();
  85988. }
  85989. });
  85990. }, this._babylonScene.database, true, function (request, exception) {
  85991. _this._tryCatchOnError(function () {
  85992. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85993. });
  85994. });
  85995. this._requests.push(request);
  85996. request.onCompleteObservable.add(function () {
  85997. _this._requests.splice(_this._requests.indexOf(request), 1);
  85998. });
  85999. };
  86000. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  86001. if (this._disposed) {
  86002. return;
  86003. }
  86004. try {
  86005. handler();
  86006. }
  86007. catch (e) {
  86008. BABYLON.Tools.Error("glTF Loader: " + e.message);
  86009. if (this._errorCallback) {
  86010. this._errorCallback(e.message, e);
  86011. }
  86012. this.dispose();
  86013. }
  86014. };
  86015. GLTFLoader._AssignIndices = function (array) {
  86016. if (array) {
  86017. for (var index = 0; index < array.length; index++) {
  86018. array[index].index = index;
  86019. }
  86020. }
  86021. };
  86022. GLTFLoader._GetProperty = function (array, index) {
  86023. if (!array || index == undefined || !array[index]) {
  86024. return null;
  86025. }
  86026. return array[index];
  86027. };
  86028. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  86029. // Set defaults if undefined
  86030. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  86031. switch (mode) {
  86032. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  86033. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  86034. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86035. default:
  86036. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  86037. return BABYLON.Texture.WRAP_ADDRESSMODE;
  86038. }
  86039. };
  86040. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  86041. // Set defaults if undefined
  86042. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  86043. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  86044. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  86045. switch (minFilter) {
  86046. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  86047. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  86048. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  86049. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  86050. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  86051. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  86052. default:
  86053. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  86054. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  86055. }
  86056. }
  86057. else {
  86058. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  86059. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  86060. }
  86061. switch (minFilter) {
  86062. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  86063. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  86064. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  86065. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  86066. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  86067. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  86068. default:
  86069. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  86070. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  86071. }
  86072. }
  86073. };
  86074. GLTFLoader._GetNumComponents = function (context, type) {
  86075. switch (type) {
  86076. case "SCALAR": return 1;
  86077. case "VEC2": return 2;
  86078. case "VEC3": return 3;
  86079. case "VEC4": return 4;
  86080. case "MAT2": return 4;
  86081. case "MAT3": return 9;
  86082. case "MAT4": return 16;
  86083. }
  86084. throw new Error(context + ": Invalid type " + type);
  86085. };
  86086. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  86087. var _this = this;
  86088. if (this.useClipPlane) {
  86089. babylonMaterial.forceCompilation(babylonMesh, function () {
  86090. babylonMaterial.forceCompilation(babylonMesh, function () {
  86091. _this._tryCatchOnError(onSuccess);
  86092. }, { clipPlane: true });
  86093. });
  86094. }
  86095. else {
  86096. babylonMaterial.forceCompilation(babylonMesh, function () {
  86097. _this._tryCatchOnError(onSuccess);
  86098. });
  86099. }
  86100. };
  86101. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  86102. if (!this.compileMaterials || !this._gltf.materials) {
  86103. onSuccess();
  86104. return;
  86105. }
  86106. var meshes = this._getMeshes();
  86107. var remaining = 0;
  86108. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  86109. var mesh = meshes_1[_i];
  86110. if (mesh.material instanceof BABYLON.MultiMaterial) {
  86111. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  86112. var subMaterial = _b[_a];
  86113. if (subMaterial) {
  86114. remaining++;
  86115. }
  86116. }
  86117. }
  86118. else if (mesh.material) {
  86119. remaining++;
  86120. }
  86121. }
  86122. if (remaining === 0) {
  86123. onSuccess();
  86124. return;
  86125. }
  86126. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  86127. var mesh = meshes_2[_c];
  86128. if (mesh.material instanceof BABYLON.MultiMaterial) {
  86129. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  86130. var subMaterial = _e[_d];
  86131. if (subMaterial) {
  86132. this._compileMaterialAsync(subMaterial, mesh, function () {
  86133. if (--remaining === 0) {
  86134. onSuccess();
  86135. }
  86136. });
  86137. }
  86138. }
  86139. }
  86140. else if (mesh.material) {
  86141. this._compileMaterialAsync(mesh.material, mesh, function () {
  86142. if (--remaining === 0) {
  86143. onSuccess();
  86144. }
  86145. });
  86146. }
  86147. }
  86148. };
  86149. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  86150. var _this = this;
  86151. if (!this.compileShadowGenerators) {
  86152. onSuccess();
  86153. return;
  86154. }
  86155. var lights = this._babylonScene.lights;
  86156. var remaining = 0;
  86157. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  86158. var light = lights_1[_i];
  86159. var generator = light.getShadowGenerator();
  86160. if (generator) {
  86161. remaining++;
  86162. }
  86163. }
  86164. if (remaining === 0) {
  86165. onSuccess();
  86166. return;
  86167. }
  86168. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  86169. var light = lights_2[_a];
  86170. var generator = light.getShadowGenerator();
  86171. if (generator) {
  86172. generator.forceCompilation(function () {
  86173. if (--remaining === 0) {
  86174. _this._tryCatchOnError(onSuccess);
  86175. }
  86176. });
  86177. }
  86178. }
  86179. };
  86180. GLTFLoader.prototype._abortRequests = function () {
  86181. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86182. var request = _a[_i];
  86183. request.abort();
  86184. }
  86185. this._requests.length = 0;
  86186. };
  86187. GLTFLoader.prototype._releaseResources = function () {
  86188. if (this._gltf.textures) {
  86189. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  86190. var texture = _a[_i];
  86191. if (texture.url) {
  86192. URL.revokeObjectURL(texture.url);
  86193. texture.url = undefined;
  86194. }
  86195. }
  86196. }
  86197. };
  86198. GLTFLoader.Extensions = {};
  86199. return GLTFLoader;
  86200. }());
  86201. GLTF2.GLTFLoader = GLTFLoader;
  86202. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  86203. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86204. })(BABYLON || (BABYLON = {}));
  86205. //# sourceMappingURL=babylon.glTFLoader.js.map
  86206. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86207. var BABYLON;
  86208. (function (BABYLON) {
  86209. var GLTF2;
  86210. (function (GLTF2) {
  86211. /**
  86212. * Utils functions for GLTF
  86213. */
  86214. var GLTFUtils = /** @class */ (function () {
  86215. function GLTFUtils() {
  86216. }
  86217. /**
  86218. * If the uri is a base64 string
  86219. * @param uri: the uri to test
  86220. */
  86221. GLTFUtils.IsBase64 = function (uri) {
  86222. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86223. };
  86224. /**
  86225. * Decode the base64 uri
  86226. * @param uri: the uri to decode
  86227. */
  86228. GLTFUtils.DecodeBase64 = function (uri) {
  86229. var decodedString = atob(uri.split(",")[1]);
  86230. var bufferLength = decodedString.length;
  86231. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86232. for (var i = 0; i < bufferLength; i++) {
  86233. bufferView[i] = decodedString.charCodeAt(i);
  86234. }
  86235. return bufferView.buffer;
  86236. };
  86237. GLTFUtils.ValidateUri = function (uri) {
  86238. return (uri.indexOf("..") === -1);
  86239. };
  86240. return GLTFUtils;
  86241. }());
  86242. GLTF2.GLTFUtils = GLTFUtils;
  86243. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86244. })(BABYLON || (BABYLON = {}));
  86245. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86246. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86247. var BABYLON;
  86248. (function (BABYLON) {
  86249. var GLTF2;
  86250. (function (GLTF2) {
  86251. var GLTFLoaderExtension = /** @class */ (function () {
  86252. function GLTFLoaderExtension() {
  86253. this.enabled = true;
  86254. }
  86255. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  86256. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  86257. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  86258. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  86259. var _this = this;
  86260. if (!property.extensions) {
  86261. return false;
  86262. }
  86263. var extension = property.extensions[this.name];
  86264. if (!extension) {
  86265. return false;
  86266. }
  86267. // Clear out the extension before executing the action to avoid recursing into the same property.
  86268. property.extensions[this.name] = undefined;
  86269. action(context + "extensions/" + this.name, extension, function () {
  86270. // Restore the extension after completing the action.
  86271. property.extensions[_this.name] = extension;
  86272. });
  86273. return true;
  86274. };
  86275. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  86276. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  86277. };
  86278. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  86279. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  86280. };
  86281. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  86282. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  86283. };
  86284. GLTFLoaderExtension._ApplyExtensions = function (action) {
  86285. var extensions = GLTFLoaderExtension._Extensions;
  86286. if (!extensions) {
  86287. return false;
  86288. }
  86289. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  86290. var extension = extensions_1[_i];
  86291. if (extension.enabled && action(extension)) {
  86292. return true;
  86293. }
  86294. }
  86295. return false;
  86296. };
  86297. //
  86298. // Utilities
  86299. //
  86300. GLTFLoaderExtension._Extensions = [];
  86301. return GLTFLoaderExtension;
  86302. }());
  86303. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  86304. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86305. })(BABYLON || (BABYLON = {}));
  86306. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86307. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86308. var BABYLON;
  86309. (function (BABYLON) {
  86310. var GLTF2;
  86311. (function (GLTF2) {
  86312. var Extensions;
  86313. (function (Extensions) {
  86314. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  86315. var MSFTLOD = /** @class */ (function (_super) {
  86316. __extends(MSFTLOD, _super);
  86317. function MSFTLOD() {
  86318. var _this = _super !== null && _super.apply(this, arguments) || this;
  86319. /**
  86320. * Specify the minimal delay between LODs in ms (default = 250)
  86321. */
  86322. _this.Delay = 250;
  86323. return _this;
  86324. }
  86325. Object.defineProperty(MSFTLOD.prototype, "name", {
  86326. get: function () {
  86327. return "MSFT_lod";
  86328. },
  86329. enumerable: true,
  86330. configurable: true
  86331. });
  86332. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  86333. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86334. for (var i = extension.ids.length - 1; i >= 0; i--) {
  86335. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  86336. if (!lodNode) {
  86337. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  86338. }
  86339. loader._traverseNode(context, lodNode, action, parentNode);
  86340. }
  86341. loader._traverseNode(context, node, action, parentNode);
  86342. onComplete();
  86343. });
  86344. };
  86345. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  86346. var _this = this;
  86347. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86348. var nodes = [node];
  86349. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86350. var index = _a[_i];
  86351. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  86352. if (!lodNode) {
  86353. throw new Error(context + ": Failed to find node " + index);
  86354. }
  86355. nodes.push(lodNode);
  86356. }
  86357. loader._addLoaderPendingData(node);
  86358. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  86359. loader._removeLoaderPendingData(node);
  86360. onComplete();
  86361. });
  86362. });
  86363. };
  86364. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  86365. var _this = this;
  86366. loader._whenAction(function () {
  86367. loader._loadNode(context, nodes[index]);
  86368. }, function () {
  86369. if (index !== nodes.length - 1) {
  86370. var previousNode = nodes[index + 1];
  86371. previousNode.babylonMesh.setEnabled(false);
  86372. }
  86373. if (index === 0) {
  86374. onComplete();
  86375. return;
  86376. }
  86377. setTimeout(function () {
  86378. loader._tryCatchOnError(function () {
  86379. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  86380. });
  86381. }, _this.Delay);
  86382. });
  86383. };
  86384. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  86385. var _this = this;
  86386. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86387. var materials = [material];
  86388. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86389. var index = _a[_i];
  86390. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  86391. if (!lodMaterial) {
  86392. throw new Error(context + ": Failed to find material " + index);
  86393. }
  86394. materials.push(lodMaterial);
  86395. }
  86396. loader._addLoaderPendingData(material);
  86397. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  86398. loader._removeLoaderPendingData(material);
  86399. onComplete();
  86400. });
  86401. });
  86402. };
  86403. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  86404. var _this = this;
  86405. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  86406. if (index === materials.length - 1) {
  86407. assign(babylonMaterial, isNew);
  86408. // Load the next LOD when the loader is ready to render.
  86409. loader._executeWhenRenderReady(function () {
  86410. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86411. });
  86412. }
  86413. else {
  86414. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  86415. assign(babylonMaterial, isNew);
  86416. if (index === 0) {
  86417. onComplete();
  86418. }
  86419. else {
  86420. setTimeout(function () {
  86421. loader._tryCatchOnError(function () {
  86422. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86423. });
  86424. }, _this.Delay);
  86425. }
  86426. });
  86427. }
  86428. });
  86429. };
  86430. return MSFTLOD;
  86431. }(GLTF2.GLTFLoaderExtension));
  86432. Extensions.MSFTLOD = MSFTLOD;
  86433. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  86434. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86435. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86436. })(BABYLON || (BABYLON = {}));
  86437. //# sourceMappingURL=MSFT_lod.js.map
  86438. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86439. var BABYLON;
  86440. (function (BABYLON) {
  86441. var GLTF2;
  86442. (function (GLTF2) {
  86443. var Extensions;
  86444. (function (Extensions) {
  86445. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  86446. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  86447. function KHRMaterialsPbrSpecularGlossiness() {
  86448. return _super !== null && _super.apply(this, arguments) || this;
  86449. }
  86450. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  86451. get: function () {
  86452. return "KHR_materials_pbrSpecularGlossiness";
  86453. },
  86454. enumerable: true,
  86455. configurable: true
  86456. });
  86457. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  86458. var _this = this;
  86459. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86460. loader._createPbrMaterial(material);
  86461. loader._loadMaterialBaseProperties(context, material);
  86462. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  86463. assign(material.babylonMaterial, true);
  86464. onComplete();
  86465. });
  86466. };
  86467. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  86468. var babylonMaterial = material.babylonMaterial;
  86469. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  86470. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  86471. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  86472. if (properties.diffuseTexture) {
  86473. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  86474. if (!texture) {
  86475. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  86476. }
  86477. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  86478. }
  86479. if (properties.specularGlossinessTexture) {
  86480. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  86481. if (!texture) {
  86482. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  86483. }
  86484. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  86485. babylonMaterial.reflectivityTexture.hasAlpha = true;
  86486. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  86487. }
  86488. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  86489. };
  86490. return KHRMaterialsPbrSpecularGlossiness;
  86491. }(GLTF2.GLTFLoaderExtension));
  86492. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  86493. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  86494. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86495. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86496. })(BABYLON || (BABYLON = {}));
  86497. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  86498. (function universalModuleDefinition(root, factory) {
  86499. var f = factory();
  86500. if (root && root["BABYLON"]) {
  86501. return;
  86502. }
  86503. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86504. globalObject["BABYLON"] = f;
  86505. if(typeof exports === 'object' && typeof module === 'object')
  86506. module.exports = f;
  86507. else if(typeof define === 'function' && define.amd)
  86508. define(["BABYLON"], factory);
  86509. else if(typeof exports === 'object')
  86510. exports["BABYLON"] = f;
  86511. else {
  86512. root["BABYLON"] = f;
  86513. }
  86514. })(this, function() {
  86515. return BABYLON;
  86516. });