babylon.max.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * 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".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. 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);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. 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]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. 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]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. 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);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. 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);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. 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);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. 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);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. 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);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * 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".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * 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".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. 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);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new 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.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3762. };
  3763. /**
  3764. * 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.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * 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.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * 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.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * 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.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * 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.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * 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.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3835. };
  3836. /**
  3837. * 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.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * 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.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3861. };
  3862. /**
  3863. * 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.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. 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);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. 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);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * 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.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. 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)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. 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;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. 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)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * 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.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * 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).
  5462. * 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.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @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.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. var state = this._eventState;
  5535. state.mask = mask;
  5536. state.target = target;
  5537. state.currentTarget = currentTarget;
  5538. state.skipNextObservers = false;
  5539. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5540. var obs = _a[_i];
  5541. if (obs.mask & mask) {
  5542. if (obs.scope) {
  5543. obs.callback.apply(obs.scope, [eventData, state]);
  5544. }
  5545. else {
  5546. obs.callback(eventData, state);
  5547. }
  5548. }
  5549. if (state.skipNextObservers) {
  5550. return false;
  5551. }
  5552. }
  5553. return true;
  5554. };
  5555. /**
  5556. * Notify a specific observer
  5557. * @param eventData
  5558. * @param mask
  5559. */
  5560. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5561. if (mask === void 0) { mask = -1; }
  5562. var state = this._eventState;
  5563. state.mask = mask;
  5564. state.skipNextObservers = false;
  5565. observer.callback(eventData, state);
  5566. };
  5567. /**
  5568. * return true is the Observable has at least one Observer registered
  5569. */
  5570. Observable.prototype.hasObservers = function () {
  5571. return this._observers.length > 0;
  5572. };
  5573. /**
  5574. * Clear the list of observers
  5575. */
  5576. Observable.prototype.clear = function () {
  5577. this._observers = new Array();
  5578. this._onObserverAdded = null;
  5579. };
  5580. /**
  5581. * Clone the current observable
  5582. */
  5583. Observable.prototype.clone = function () {
  5584. var result = new Observable();
  5585. result._observers = this._observers.slice(0);
  5586. return result;
  5587. };
  5588. /**
  5589. * Does this observable handles observer registered with a given mask
  5590. * @param {number} trigger - the mask to be tested
  5591. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5592. **/
  5593. Observable.prototype.hasSpecificMask = function (mask) {
  5594. if (mask === void 0) { mask = -1; }
  5595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5596. var obs = _a[_i];
  5597. if (obs.mask & mask || obs.mask === mask) {
  5598. return true;
  5599. }
  5600. }
  5601. return false;
  5602. };
  5603. return Observable;
  5604. }());
  5605. BABYLON.Observable = Observable;
  5606. })(BABYLON || (BABYLON = {}));
  5607. //# sourceMappingURL=babylon.observable.js.map
  5608. var BABYLON;
  5609. (function (BABYLON) {
  5610. var SmartArray = /** @class */ (function () {
  5611. function SmartArray(capacity) {
  5612. this.length = 0;
  5613. this._duplicateId = 0;
  5614. this.data = new Array(capacity);
  5615. this._id = SmartArray._GlobalId++;
  5616. }
  5617. SmartArray.prototype.push = function (value) {
  5618. this.data[this.length++] = value;
  5619. if (this.length > this.data.length) {
  5620. this.data.length *= 2;
  5621. }
  5622. if (!value.__smartArrayFlags) {
  5623. value.__smartArrayFlags = {};
  5624. }
  5625. value.__smartArrayFlags[this._id] = this._duplicateId;
  5626. };
  5627. SmartArray.prototype.forEach = function (func) {
  5628. for (var index = 0; index < this.length; index++) {
  5629. func(this.data[index]);
  5630. }
  5631. };
  5632. SmartArray.prototype.pushNoDuplicate = function (value) {
  5633. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5634. return false;
  5635. }
  5636. this.push(value);
  5637. return true;
  5638. };
  5639. SmartArray.prototype.sort = function (compareFn) {
  5640. this.data.sort(compareFn);
  5641. };
  5642. SmartArray.prototype.reset = function () {
  5643. this.length = 0;
  5644. this._duplicateId++;
  5645. };
  5646. SmartArray.prototype.dispose = function () {
  5647. this.reset();
  5648. if (this.data) {
  5649. this.data.length = 0;
  5650. this.data = [];
  5651. }
  5652. };
  5653. SmartArray.prototype.concat = function (array) {
  5654. if (array.length === 0) {
  5655. return;
  5656. }
  5657. if (this.length + array.length > this.data.length) {
  5658. this.data.length = (this.length + array.length) * 2;
  5659. }
  5660. for (var index = 0; index < array.length; index++) {
  5661. this.data[this.length++] = (array.data || array)[index];
  5662. }
  5663. };
  5664. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5665. if (array.length === 0) {
  5666. return;
  5667. }
  5668. if (this.length + array.length > this.data.length) {
  5669. this.data.length = (this.length + array.length) * 2;
  5670. }
  5671. for (var index = 0; index < array.length; index++) {
  5672. var item = (array.data || array)[index];
  5673. this.pushNoDuplicate(item);
  5674. }
  5675. };
  5676. SmartArray.prototype.indexOf = function (value) {
  5677. var position = this.data.indexOf(value);
  5678. if (position >= this.length) {
  5679. return -1;
  5680. }
  5681. return position;
  5682. };
  5683. SmartArray.prototype.contains = function (value) {
  5684. return this.data.indexOf(value) !== -1;
  5685. };
  5686. // Statics
  5687. SmartArray._GlobalId = 0;
  5688. return SmartArray;
  5689. }());
  5690. BABYLON.SmartArray = SmartArray;
  5691. })(BABYLON || (BABYLON = {}));
  5692. //# sourceMappingURL=babylon.smartArray.js.map
  5693. var BABYLON;
  5694. (function (BABYLON) {
  5695. // Screenshots
  5696. var screenshotCanvas;
  5697. var cloneValue = function (source, destinationObject) {
  5698. if (!source)
  5699. return null;
  5700. if (source instanceof BABYLON.Mesh) {
  5701. return null;
  5702. }
  5703. if (source instanceof BABYLON.SubMesh) {
  5704. return source.clone(destinationObject);
  5705. }
  5706. else if (source.clone) {
  5707. return source.clone();
  5708. }
  5709. return null;
  5710. };
  5711. var Tools = /** @class */ (function () {
  5712. function Tools() {
  5713. }
  5714. ;
  5715. /**
  5716. * Interpolates between a and b via alpha
  5717. * @param a The lower value (returned when alpha = 0)
  5718. * @param b The upper value (returned when alpha = 1)
  5719. * @param alpha The interpolation-factor
  5720. * @return The mixed value
  5721. */
  5722. Tools.Mix = function (a, b, alpha) {
  5723. return a * (1 - alpha) + b * alpha;
  5724. };
  5725. Tools.Instantiate = function (className) {
  5726. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5727. return Tools.RegisteredExternalClasses[className];
  5728. }
  5729. var arr = className.split(".");
  5730. var fn = (window || this);
  5731. for (var i = 0, len = arr.length; i < len; i++) {
  5732. fn = fn[arr[i]];
  5733. }
  5734. if (typeof fn !== "function") {
  5735. return null;
  5736. }
  5737. return fn;
  5738. };
  5739. Tools.SetImmediate = function (action) {
  5740. if (window.setImmediate) {
  5741. window.setImmediate(action);
  5742. }
  5743. else {
  5744. setTimeout(action, 1);
  5745. }
  5746. };
  5747. Tools.IsExponentOfTwo = function (value) {
  5748. var count = 1;
  5749. do {
  5750. count *= 2;
  5751. } while (count < value);
  5752. return count === value;
  5753. };
  5754. /**
  5755. * Find the next highest power of two.
  5756. * @param x Number to start search from.
  5757. * @return Next highest power of two.
  5758. */
  5759. Tools.CeilingPOT = function (x) {
  5760. x--;
  5761. x |= x >> 1;
  5762. x |= x >> 2;
  5763. x |= x >> 4;
  5764. x |= x >> 8;
  5765. x |= x >> 16;
  5766. x++;
  5767. return x;
  5768. };
  5769. /**
  5770. * Find the next lowest power of two.
  5771. * @param x Number to start search from.
  5772. * @return Next lowest power of two.
  5773. */
  5774. Tools.FloorPOT = function (x) {
  5775. x = x | (x >> 1);
  5776. x = x | (x >> 2);
  5777. x = x | (x >> 4);
  5778. x = x | (x >> 8);
  5779. x = x | (x >> 16);
  5780. return x - (x >> 1);
  5781. };
  5782. /**
  5783. * Find the nearest power of two.
  5784. * @param x Number to start search from.
  5785. * @return Next nearest power of two.
  5786. */
  5787. Tools.NearestPOT = function (x) {
  5788. var c = Tools.CeilingPOT(x);
  5789. var f = Tools.FloorPOT(x);
  5790. return (c - x) > (x - f) ? f : c;
  5791. };
  5792. Tools.GetExponentOfTwo = function (value, max, mode) {
  5793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5794. var pot;
  5795. switch (mode) {
  5796. case BABYLON.Engine.SCALEMODE_FLOOR:
  5797. pot = Tools.FloorPOT(value);
  5798. break;
  5799. case BABYLON.Engine.SCALEMODE_NEAREST:
  5800. pot = Tools.NearestPOT(value);
  5801. break;
  5802. case BABYLON.Engine.SCALEMODE_CEILING:
  5803. default:
  5804. pot = Tools.CeilingPOT(value);
  5805. break;
  5806. }
  5807. return Math.min(pot, max);
  5808. };
  5809. Tools.GetFilename = function (path) {
  5810. var index = path.lastIndexOf("/");
  5811. if (index < 0)
  5812. return path;
  5813. return path.substring(index + 1);
  5814. };
  5815. Tools.GetDOMTextContent = function (element) {
  5816. var result = "";
  5817. var child = element.firstChild;
  5818. while (child) {
  5819. if (child.nodeType === 3) {
  5820. result += child.textContent;
  5821. }
  5822. child = child.nextSibling;
  5823. }
  5824. return result;
  5825. };
  5826. Tools.ToDegrees = function (angle) {
  5827. return angle * 180 / Math.PI;
  5828. };
  5829. Tools.ToRadians = function (angle) {
  5830. return angle * Math.PI / 180;
  5831. };
  5832. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5833. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5834. var output = "";
  5835. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5836. var i = 0;
  5837. var bytes = new Uint8Array(buffer);
  5838. while (i < bytes.length) {
  5839. chr1 = bytes[i++];
  5840. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5841. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5842. enc1 = chr1 >> 2;
  5843. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5844. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5845. enc4 = chr3 & 63;
  5846. if (isNaN(chr2)) {
  5847. enc3 = enc4 = 64;
  5848. }
  5849. else if (isNaN(chr3)) {
  5850. enc4 = 64;
  5851. }
  5852. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5853. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5854. }
  5855. return "data:image/png;base64," + output;
  5856. };
  5857. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5858. if (bias === void 0) { bias = null; }
  5859. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5860. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5861. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5862. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5863. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5864. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5865. }
  5866. if (bias) {
  5867. minimum.x -= minimum.x * bias.x + bias.y;
  5868. minimum.y -= minimum.y * bias.x + bias.y;
  5869. minimum.z -= minimum.z * bias.x + bias.y;
  5870. maximum.x += maximum.x * bias.x + bias.y;
  5871. maximum.y += maximum.y * bias.x + bias.y;
  5872. maximum.z += maximum.z * bias.x + bias.y;
  5873. }
  5874. return {
  5875. minimum: minimum,
  5876. maximum: maximum
  5877. };
  5878. };
  5879. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5880. if (bias === void 0) { bias = null; }
  5881. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5882. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5883. if (!stride) {
  5884. stride = 3;
  5885. }
  5886. for (var index = start; index < start + count; index++) {
  5887. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5888. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5889. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5890. }
  5891. if (bias) {
  5892. minimum.x -= minimum.x * bias.x + bias.y;
  5893. minimum.y -= minimum.y * bias.x + bias.y;
  5894. minimum.z -= minimum.z * bias.x + bias.y;
  5895. maximum.x += maximum.x * bias.x + bias.y;
  5896. maximum.y += maximum.y * bias.x + bias.y;
  5897. maximum.z += maximum.z * bias.x + bias.y;
  5898. }
  5899. return {
  5900. minimum: minimum,
  5901. maximum: maximum
  5902. };
  5903. };
  5904. Tools.Vector2ArrayFeeder = function (array) {
  5905. return function (index) {
  5906. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5907. var length = isFloatArray ? array.length / 2 : array.length;
  5908. if (index >= length) {
  5909. return null;
  5910. }
  5911. if (isFloatArray) {
  5912. var fa = array;
  5913. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5914. }
  5915. var a = array;
  5916. return a[index];
  5917. };
  5918. };
  5919. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5920. if (bias === void 0) { bias = null; }
  5921. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5922. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5923. var i = 0;
  5924. var cur = feeder(i++);
  5925. while (cur) {
  5926. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5927. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5928. cur = feeder(i++);
  5929. }
  5930. if (bias) {
  5931. minimum.x -= minimum.x * bias.x + bias.y;
  5932. minimum.y -= minimum.y * bias.x + bias.y;
  5933. maximum.x += maximum.x * bias.x + bias.y;
  5934. maximum.y += maximum.y * bias.x + bias.y;
  5935. }
  5936. return {
  5937. minimum: minimum,
  5938. maximum: maximum
  5939. };
  5940. };
  5941. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5942. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5943. return null;
  5944. return Array.isArray(obj) ? obj : [obj];
  5945. };
  5946. // Misc.
  5947. Tools.GetPointerPrefix = function () {
  5948. var eventPrefix = "pointer";
  5949. // Check if pointer events are supported
  5950. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5951. eventPrefix = "mouse";
  5952. }
  5953. return eventPrefix;
  5954. };
  5955. /**
  5956. * @param func - the function to be called
  5957. * @param requester - the object that will request the next frame. Falls back to window.
  5958. */
  5959. Tools.QueueNewFrame = function (func, requester) {
  5960. if (!Tools.IsWindowObjectExist()) {
  5961. return setTimeout(func, 16);
  5962. }
  5963. if (!requester) {
  5964. requester = window;
  5965. }
  5966. if (requester.requestAnimationFrame) {
  5967. return requester.requestAnimationFrame(func);
  5968. }
  5969. else if (requester.msRequestAnimationFrame) {
  5970. return requester.msRequestAnimationFrame(func);
  5971. }
  5972. else if (requester.webkitRequestAnimationFrame) {
  5973. return requester.webkitRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.mozRequestAnimationFrame) {
  5976. return requester.mozRequestAnimationFrame(func);
  5977. }
  5978. else if (requester.oRequestAnimationFrame) {
  5979. return requester.oRequestAnimationFrame(func);
  5980. }
  5981. else {
  5982. return window.setTimeout(func, 16);
  5983. }
  5984. };
  5985. Tools.RequestFullscreen = function (element) {
  5986. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5987. if (!requestFunction)
  5988. return;
  5989. requestFunction.call(element);
  5990. };
  5991. Tools.ExitFullscreen = function () {
  5992. if (document.exitFullscreen) {
  5993. document.exitFullscreen();
  5994. }
  5995. else if (document.mozCancelFullScreen) {
  5996. document.mozCancelFullScreen();
  5997. }
  5998. else if (document.webkitCancelFullScreen) {
  5999. document.webkitCancelFullScreen();
  6000. }
  6001. else if (document.msCancelFullScreen) {
  6002. document.msCancelFullScreen();
  6003. }
  6004. };
  6005. Tools.SetCorsBehavior = function (url, img) {
  6006. if (Tools.CorsBehavior) {
  6007. switch (typeof (Tools.CorsBehavior)) {
  6008. case "function":
  6009. var result = Tools.CorsBehavior(url);
  6010. if (result) {
  6011. img.crossOrigin = result;
  6012. }
  6013. break;
  6014. case "string":
  6015. default:
  6016. img.crossOrigin = Tools.CorsBehavior;
  6017. break;
  6018. }
  6019. }
  6020. };
  6021. // External files
  6022. Tools.CleanUrl = function (url) {
  6023. url = url.replace(/#/mg, "%23");
  6024. return url;
  6025. };
  6026. Tools.LoadImage = function (url, onLoad, onError, database) {
  6027. if (url instanceof ArrayBuffer) {
  6028. url = Tools.EncodeArrayBufferTobase64(url);
  6029. }
  6030. url = Tools.CleanUrl(url);
  6031. url = Tools.PreprocessUrl(url);
  6032. var img = new Image();
  6033. if (url.substr(0, 5) !== "data:") {
  6034. Tools.SetCorsBehavior(url, img);
  6035. }
  6036. img.onload = function () {
  6037. onLoad(img);
  6038. };
  6039. img.onerror = function (err) {
  6040. Tools.Error("Error while trying to load image: " + url);
  6041. if (Tools.UseFallbackTexture) {
  6042. img.src = Tools.fallbackTexture;
  6043. onLoad(img);
  6044. }
  6045. else {
  6046. onError("Error while trying to load image: " + url, err);
  6047. }
  6048. };
  6049. var noIndexedDB = function () {
  6050. img.src = url;
  6051. };
  6052. var loadFromIndexedDB = function () {
  6053. if (database) {
  6054. database.loadImageFromDB(url, img);
  6055. }
  6056. };
  6057. //ANY database to do!
  6058. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6059. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6060. }
  6061. else {
  6062. if (url.indexOf("file:") !== 0) {
  6063. noIndexedDB();
  6064. }
  6065. else {
  6066. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6067. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6068. try {
  6069. var blobURL;
  6070. try {
  6071. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6072. }
  6073. catch (ex) {
  6074. // Chrome doesn't support oneTimeOnly parameter
  6075. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6076. }
  6077. img.src = blobURL;
  6078. }
  6079. catch (e) {
  6080. img.src = "";
  6081. }
  6082. }
  6083. else {
  6084. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6085. img.src = Tools.fallbackTexture;
  6086. }
  6087. }
  6088. }
  6089. return img;
  6090. };
  6091. //ANY
  6092. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6093. url = Tools.CleanUrl(url);
  6094. url = Tools.PreprocessUrl(url);
  6095. var request = null;
  6096. var noIndexedDB = function () {
  6097. request = new XMLHttpRequest();
  6098. var loadUrl = Tools.BaseUrl + url;
  6099. request.open('GET', loadUrl, true);
  6100. if (useArrayBuffer) {
  6101. request.responseType = "arraybuffer";
  6102. }
  6103. if (progressCallBack) {
  6104. request.onprogress = progressCallBack;
  6105. }
  6106. request.onreadystatechange = function () {
  6107. var req = request;
  6108. // In case of undefined state in some browsers.
  6109. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6110. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6111. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6112. callback(!useArrayBuffer ? req.responseText : req.response);
  6113. }
  6114. else {
  6115. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6116. if (onError) {
  6117. onError(req, e);
  6118. }
  6119. else {
  6120. throw e;
  6121. }
  6122. }
  6123. }
  6124. };
  6125. request.send(null);
  6126. };
  6127. var loadFromIndexedDB = function () {
  6128. if (database) {
  6129. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6130. }
  6131. };
  6132. if (url.indexOf("file:") !== -1) {
  6133. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6134. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6135. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6136. }
  6137. else {
  6138. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6139. if (onError) {
  6140. var e = new Error(errorMessage);
  6141. onError(undefined, e);
  6142. }
  6143. else {
  6144. Tools.Error(errorMessage);
  6145. }
  6146. }
  6147. }
  6148. else {
  6149. // Caching all files
  6150. if (database && database.enableSceneOffline) {
  6151. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6152. }
  6153. else {
  6154. noIndexedDB();
  6155. }
  6156. }
  6157. return request;
  6158. };
  6159. /**
  6160. * Load a script (identified by an url). When the url returns, the
  6161. * content of this file is added into a new script element, attached to the DOM (body element)
  6162. */
  6163. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6164. var head = document.getElementsByTagName('head')[0];
  6165. var script = document.createElement('script');
  6166. script.type = 'text/javascript';
  6167. script.src = scriptUrl;
  6168. script.onload = function () {
  6169. if (onSuccess) {
  6170. onSuccess();
  6171. }
  6172. };
  6173. script.onerror = function (e) {
  6174. if (onError) {
  6175. onError("Unable to load script", e);
  6176. }
  6177. };
  6178. head.appendChild(script);
  6179. };
  6180. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6181. var reader = new FileReader();
  6182. reader.onload = function (e) {
  6183. //target doesn't have result from ts 1.3
  6184. callback(e.target['result']);
  6185. };
  6186. reader.onprogress = progressCallback;
  6187. reader.readAsDataURL(fileToLoad);
  6188. };
  6189. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6190. var reader = new FileReader();
  6191. reader.onerror = function (e) {
  6192. Tools.Log("Error while reading file: " + fileToLoad.name);
  6193. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6194. };
  6195. reader.onload = function (e) {
  6196. //target doesn't have result from ts 1.3
  6197. callback(e.target['result']);
  6198. };
  6199. if (progressCallBack) {
  6200. reader.onprogress = progressCallBack;
  6201. }
  6202. if (!useArrayBuffer) {
  6203. // Asynchronous read
  6204. reader.readAsText(fileToLoad);
  6205. }
  6206. else {
  6207. reader.readAsArrayBuffer(fileToLoad);
  6208. }
  6209. };
  6210. //returns a downloadable url to a file content.
  6211. Tools.FileAsURL = function (content) {
  6212. var fileBlob = new Blob([content]);
  6213. var url = window.URL || window.webkitURL;
  6214. var link = url.createObjectURL(fileBlob);
  6215. return link;
  6216. };
  6217. // Misc.
  6218. Tools.Format = function (value, decimals) {
  6219. if (decimals === void 0) { decimals = 2; }
  6220. return value.toFixed(decimals);
  6221. };
  6222. Tools.CheckExtends = function (v, min, max) {
  6223. if (v.x < min.x)
  6224. min.x = v.x;
  6225. if (v.y < min.y)
  6226. min.y = v.y;
  6227. if (v.z < min.z)
  6228. min.z = v.z;
  6229. if (v.x > max.x)
  6230. max.x = v.x;
  6231. if (v.y > max.y)
  6232. max.y = v.y;
  6233. if (v.z > max.z)
  6234. max.z = v.z;
  6235. };
  6236. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6237. for (var prop in source) {
  6238. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6239. continue;
  6240. }
  6241. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6242. continue;
  6243. }
  6244. var sourceValue = source[prop];
  6245. var typeOfSourceValue = typeof sourceValue;
  6246. if (typeOfSourceValue === "function") {
  6247. continue;
  6248. }
  6249. if (typeOfSourceValue === "object") {
  6250. if (sourceValue instanceof Array) {
  6251. destination[prop] = [];
  6252. if (sourceValue.length > 0) {
  6253. if (typeof sourceValue[0] == "object") {
  6254. for (var index = 0; index < sourceValue.length; index++) {
  6255. var clonedValue = cloneValue(sourceValue[index], destination);
  6256. if (destination[prop].indexOf(clonedValue) === -1) {
  6257. destination[prop].push(clonedValue);
  6258. }
  6259. }
  6260. }
  6261. else {
  6262. destination[prop] = sourceValue.slice(0);
  6263. }
  6264. }
  6265. }
  6266. else {
  6267. destination[prop] = cloneValue(sourceValue, destination);
  6268. }
  6269. }
  6270. else {
  6271. destination[prop] = sourceValue;
  6272. }
  6273. }
  6274. };
  6275. Tools.IsEmpty = function (obj) {
  6276. for (var i in obj) {
  6277. if (obj.hasOwnProperty(i)) {
  6278. return false;
  6279. }
  6280. }
  6281. return true;
  6282. };
  6283. Tools.RegisterTopRootEvents = function (events) {
  6284. for (var index = 0; index < events.length; index++) {
  6285. var event = events[index];
  6286. window.addEventListener(event.name, event.handler, false);
  6287. try {
  6288. if (window.parent) {
  6289. window.parent.addEventListener(event.name, event.handler, false);
  6290. }
  6291. }
  6292. catch (e) {
  6293. // Silently fails...
  6294. }
  6295. }
  6296. };
  6297. Tools.UnregisterTopRootEvents = function (events) {
  6298. for (var index = 0; index < events.length; index++) {
  6299. var event = events[index];
  6300. window.removeEventListener(event.name, event.handler);
  6301. try {
  6302. if (window.parent) {
  6303. window.parent.removeEventListener(event.name, event.handler);
  6304. }
  6305. }
  6306. catch (e) {
  6307. // Silently fails...
  6308. }
  6309. }
  6310. };
  6311. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6312. if (mimeType === void 0) { mimeType = "image/png"; }
  6313. // Read the contents of the framebuffer
  6314. var numberOfChannelsByLine = width * 4;
  6315. var halfHeight = height / 2;
  6316. //Reading datas from WebGL
  6317. var data = engine.readPixels(0, 0, width, height);
  6318. //To flip image on Y axis.
  6319. for (var i = 0; i < halfHeight; i++) {
  6320. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6321. var currentCell = j + i * numberOfChannelsByLine;
  6322. var targetLine = height - i - 1;
  6323. var targetCell = j + targetLine * numberOfChannelsByLine;
  6324. var temp = data[currentCell];
  6325. data[currentCell] = data[targetCell];
  6326. data[targetCell] = temp;
  6327. }
  6328. }
  6329. // Create a 2D canvas to store the result
  6330. if (!screenshotCanvas) {
  6331. screenshotCanvas = document.createElement('canvas');
  6332. }
  6333. screenshotCanvas.width = width;
  6334. screenshotCanvas.height = height;
  6335. var context = screenshotCanvas.getContext('2d');
  6336. if (context) {
  6337. // Copy the pixels to a 2D canvas
  6338. var imageData = context.createImageData(width, height);
  6339. var castData = (imageData.data);
  6340. castData.set(data);
  6341. context.putImageData(imageData, 0, 0);
  6342. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6343. }
  6344. };
  6345. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6346. if (mimeType === void 0) { mimeType = "image/png"; }
  6347. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6348. if (successCallback) {
  6349. successCallback(base64Image);
  6350. }
  6351. else {
  6352. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6353. if (("download" in document.createElement("a"))) {
  6354. var a = window.document.createElement("a");
  6355. a.href = base64Image;
  6356. var date = new Date();
  6357. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6358. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6359. window.document.body.appendChild(a);
  6360. a.addEventListener("click", function () {
  6361. if (a.parentElement) {
  6362. a.parentElement.removeChild(a);
  6363. }
  6364. });
  6365. a.click();
  6366. //Or opening a new tab with the image if it is not possible to automatically start download.
  6367. }
  6368. else {
  6369. var newWindow = window.open("");
  6370. var img = newWindow.document.createElement("img");
  6371. img.src = base64Image;
  6372. newWindow.document.body.appendChild(img);
  6373. }
  6374. }
  6375. };
  6376. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6377. if (mimeType === void 0) { mimeType = "image/png"; }
  6378. var width;
  6379. var height;
  6380. // If a precision value is specified
  6381. if (size.precision) {
  6382. width = Math.round(engine.getRenderWidth() * size.precision);
  6383. height = Math.round(width / engine.getAspectRatio(camera));
  6384. }
  6385. else if (size.width && size.height) {
  6386. width = size.width;
  6387. height = size.height;
  6388. }
  6389. else if (size.width && !size.height) {
  6390. width = size.width;
  6391. height = Math.round(width / engine.getAspectRatio(camera));
  6392. }
  6393. else if (size.height && !size.width) {
  6394. height = size.height;
  6395. width = Math.round(height * engine.getAspectRatio(camera));
  6396. }
  6397. else if (!isNaN(size)) {
  6398. height = size;
  6399. width = size;
  6400. }
  6401. else {
  6402. Tools.Error("Invalid 'size' parameter !");
  6403. return;
  6404. }
  6405. if (!screenshotCanvas) {
  6406. screenshotCanvas = document.createElement('canvas');
  6407. }
  6408. screenshotCanvas.width = width;
  6409. screenshotCanvas.height = height;
  6410. var renderContext = screenshotCanvas.getContext("2d");
  6411. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6412. var newWidth = width;
  6413. var newHeight = newWidth / ratio;
  6414. if (newHeight > height) {
  6415. newHeight = height;
  6416. newWidth = newHeight * ratio;
  6417. }
  6418. var offsetX = Math.max(0, width - newWidth) / 2;
  6419. var offsetY = Math.max(0, height - newHeight) / 2;
  6420. var renderingCanvas = engine.getRenderingCanvas();
  6421. if (renderContext && renderingCanvas) {
  6422. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6423. }
  6424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6425. };
  6426. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6427. if (mimeType === void 0) { mimeType = "image/png"; }
  6428. if (samples === void 0) { samples = 1; }
  6429. var width;
  6430. var height;
  6431. //If a precision value is specified
  6432. if (size.precision) {
  6433. width = Math.round(engine.getRenderWidth() * size.precision);
  6434. height = Math.round(width / engine.getAspectRatio(camera));
  6435. size = { width: width, height: height };
  6436. }
  6437. else if (size.width && size.height) {
  6438. width = size.width;
  6439. height = size.height;
  6440. }
  6441. else if (size.width && !size.height) {
  6442. width = size.width;
  6443. height = Math.round(width / engine.getAspectRatio(camera));
  6444. size = { width: width, height: height };
  6445. }
  6446. else if (size.height && !size.width) {
  6447. height = size.height;
  6448. width = Math.round(height * engine.getAspectRatio(camera));
  6449. size = { width: width, height: height };
  6450. }
  6451. else if (!isNaN(size)) {
  6452. height = size;
  6453. width = size;
  6454. }
  6455. else {
  6456. Tools.Error("Invalid 'size' parameter !");
  6457. return;
  6458. }
  6459. var scene = camera.getScene();
  6460. var previousCamera = null;
  6461. if (scene.activeCamera !== camera) {
  6462. previousCamera = scene.activeCamera;
  6463. scene.activeCamera = camera;
  6464. }
  6465. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6466. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6467. texture.renderList = null;
  6468. texture.samples = samples;
  6469. texture.onAfterRenderObservable.add(function () {
  6470. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6471. });
  6472. scene.incrementRenderId();
  6473. scene.resetCachedMaterial();
  6474. texture.render(true);
  6475. texture.dispose();
  6476. if (previousCamera) {
  6477. scene.activeCamera = previousCamera;
  6478. }
  6479. camera.getProjectionMatrix(true); // Force cache refresh;
  6480. };
  6481. // XHR response validator for local file scenario
  6482. Tools.ValidateXHRData = function (xhr, dataType) {
  6483. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6484. if (dataType === void 0) { dataType = 7; }
  6485. try {
  6486. if (dataType & 1) {
  6487. if (xhr.responseText && xhr.responseText.length > 0) {
  6488. return true;
  6489. }
  6490. else if (dataType === 1) {
  6491. return false;
  6492. }
  6493. }
  6494. if (dataType & 2) {
  6495. // Check header width and height since there is no "TGA" magic number
  6496. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6497. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6498. return true;
  6499. }
  6500. else if (dataType === 2) {
  6501. return false;
  6502. }
  6503. }
  6504. if (dataType & 4) {
  6505. // Check for the "DDS" magic number
  6506. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6507. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6508. return true;
  6509. }
  6510. else {
  6511. return false;
  6512. }
  6513. }
  6514. }
  6515. catch (e) {
  6516. // Global protection
  6517. }
  6518. return false;
  6519. };
  6520. /**
  6521. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6522. * Be aware Math.random() could cause collisions, but:
  6523. * "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"
  6524. */
  6525. Tools.RandomId = function () {
  6526. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6527. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6528. return v.toString(16);
  6529. });
  6530. };
  6531. Object.defineProperty(Tools, "NoneLogLevel", {
  6532. get: function () {
  6533. return Tools._NoneLogLevel;
  6534. },
  6535. enumerable: true,
  6536. configurable: true
  6537. });
  6538. Object.defineProperty(Tools, "MessageLogLevel", {
  6539. get: function () {
  6540. return Tools._MessageLogLevel;
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Tools, "WarningLogLevel", {
  6546. get: function () {
  6547. return Tools._WarningLogLevel;
  6548. },
  6549. enumerable: true,
  6550. configurable: true
  6551. });
  6552. Object.defineProperty(Tools, "ErrorLogLevel", {
  6553. get: function () {
  6554. return Tools._ErrorLogLevel;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(Tools, "AllLogLevel", {
  6560. get: function () {
  6561. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Tools._AddLogEntry = function (entry) {
  6567. Tools._LogCache = entry + Tools._LogCache;
  6568. if (Tools.OnNewCacheEntry) {
  6569. Tools.OnNewCacheEntry(entry);
  6570. }
  6571. };
  6572. Tools._FormatMessage = function (message) {
  6573. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6574. var date = new Date();
  6575. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6576. };
  6577. Tools._LogDisabled = function (message) {
  6578. // nothing to do
  6579. };
  6580. Tools._LogEnabled = function (message) {
  6581. var formattedMessage = Tools._FormatMessage(message);
  6582. console.log("BJS - " + formattedMessage);
  6583. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6584. Tools._AddLogEntry(entry);
  6585. };
  6586. Tools._WarnDisabled = function (message) {
  6587. // nothing to do
  6588. };
  6589. Tools._WarnEnabled = function (message) {
  6590. var formattedMessage = Tools._FormatMessage(message);
  6591. console.warn("BJS - " + formattedMessage);
  6592. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6593. Tools._AddLogEntry(entry);
  6594. };
  6595. Tools._ErrorDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._ErrorEnabled = function (message) {
  6599. Tools.errorsCount++;
  6600. var formattedMessage = Tools._FormatMessage(message);
  6601. console.error("BJS - " + formattedMessage);
  6602. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6603. Tools._AddLogEntry(entry);
  6604. };
  6605. Object.defineProperty(Tools, "LogCache", {
  6606. get: function () {
  6607. return Tools._LogCache;
  6608. },
  6609. enumerable: true,
  6610. configurable: true
  6611. });
  6612. Tools.ClearLogCache = function () {
  6613. Tools._LogCache = "";
  6614. Tools.errorsCount = 0;
  6615. };
  6616. Object.defineProperty(Tools, "LogLevels", {
  6617. set: function (level) {
  6618. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6619. Tools.Log = Tools._LogEnabled;
  6620. }
  6621. else {
  6622. Tools.Log = Tools._LogDisabled;
  6623. }
  6624. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6625. Tools.Warn = Tools._WarnEnabled;
  6626. }
  6627. else {
  6628. Tools.Warn = Tools._WarnDisabled;
  6629. }
  6630. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6631. Tools.Error = Tools._ErrorEnabled;
  6632. }
  6633. else {
  6634. Tools.Error = Tools._ErrorDisabled;
  6635. }
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Tools.IsWindowObjectExist = function () {
  6641. return (typeof window) !== "undefined";
  6642. };
  6643. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6644. get: function () {
  6645. return Tools._PerformanceNoneLogLevel;
  6646. },
  6647. enumerable: true,
  6648. configurable: true
  6649. });
  6650. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6651. get: function () {
  6652. return Tools._PerformanceUserMarkLogLevel;
  6653. },
  6654. enumerable: true,
  6655. configurable: true
  6656. });
  6657. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6658. get: function () {
  6659. return Tools._PerformanceConsoleLogLevel;
  6660. },
  6661. enumerable: true,
  6662. configurable: true
  6663. });
  6664. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6665. set: function (level) {
  6666. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6667. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6668. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6669. return;
  6670. }
  6671. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6672. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6673. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6674. return;
  6675. }
  6676. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6677. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6683. };
  6684. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6685. };
  6686. Tools._StartUserMark = function (counterName, condition) {
  6687. if (condition === void 0) { condition = true; }
  6688. if (!Tools._performance) {
  6689. if (!Tools.IsWindowObjectExist()) {
  6690. return;
  6691. }
  6692. Tools._performance = window.performance;
  6693. }
  6694. if (!condition || !Tools._performance.mark) {
  6695. return;
  6696. }
  6697. Tools._performance.mark(counterName + "-Begin");
  6698. };
  6699. Tools._EndUserMark = function (counterName, condition) {
  6700. if (condition === void 0) { condition = true; }
  6701. if (!condition || !Tools._performance.mark) {
  6702. return;
  6703. }
  6704. Tools._performance.mark(counterName + "-End");
  6705. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6706. };
  6707. Tools._StartPerformanceConsole = function (counterName, condition) {
  6708. if (condition === void 0) { condition = true; }
  6709. if (!condition) {
  6710. return;
  6711. }
  6712. Tools._StartUserMark(counterName, condition);
  6713. if (console.time) {
  6714. console.time(counterName);
  6715. }
  6716. };
  6717. Tools._EndPerformanceConsole = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition) {
  6720. return;
  6721. }
  6722. Tools._EndUserMark(counterName, condition);
  6723. if (console.time) {
  6724. console.timeEnd(counterName);
  6725. }
  6726. };
  6727. Object.defineProperty(Tools, "Now", {
  6728. get: function () {
  6729. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6730. return window.performance.now();
  6731. }
  6732. return new Date().getTime();
  6733. },
  6734. enumerable: true,
  6735. configurable: true
  6736. });
  6737. /**
  6738. * This method will return the name of the class used to create the instance of the given object.
  6739. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6740. * @param object the object to get the class name from
  6741. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6742. */
  6743. Tools.GetClassName = function (object, isType) {
  6744. if (isType === void 0) { isType = false; }
  6745. var name = null;
  6746. if (!isType && object.getClassName) {
  6747. name = object.getClassName();
  6748. }
  6749. else {
  6750. if (object instanceof Object) {
  6751. var classObj = isType ? object : Object.getPrototypeOf(object);
  6752. name = classObj.constructor["__bjsclassName__"];
  6753. }
  6754. if (!name) {
  6755. name = typeof object;
  6756. }
  6757. }
  6758. return name;
  6759. };
  6760. Tools.First = function (array, predicate) {
  6761. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6762. var el = array_1[_i];
  6763. if (predicate(el)) {
  6764. return el;
  6765. }
  6766. }
  6767. return null;
  6768. };
  6769. /**
  6770. * This method will return the name of the full name of the class, including its owning module (if any).
  6771. * 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).
  6772. * @param object the object to get the class name from
  6773. * @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.
  6774. */
  6775. Tools.getFullClassName = function (object, isType) {
  6776. if (isType === void 0) { isType = false; }
  6777. var className = null;
  6778. var moduleName = null;
  6779. if (!isType && object.getClassName) {
  6780. className = object.getClassName();
  6781. }
  6782. else {
  6783. if (object instanceof Object) {
  6784. var classObj = isType ? object : Object.getPrototypeOf(object);
  6785. className = classObj.constructor["__bjsclassName__"];
  6786. moduleName = classObj.constructor["__bjsmoduleName__"];
  6787. }
  6788. if (!className) {
  6789. className = typeof object;
  6790. }
  6791. }
  6792. if (!className) {
  6793. return null;
  6794. }
  6795. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6796. };
  6797. /**
  6798. * 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.
  6799. * @param array
  6800. */
  6801. Tools.arrayOrStringFeeder = function (array) {
  6802. return function (index) {
  6803. if (index >= array.length) {
  6804. return null;
  6805. }
  6806. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6807. if (val && val.getHashCode) {
  6808. val = val.getHashCode();
  6809. }
  6810. if (typeof val === "string") {
  6811. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6812. }
  6813. return val;
  6814. };
  6815. };
  6816. /**
  6817. * Compute the hashCode of a stream of number
  6818. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6819. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6820. * @return the hash code computed
  6821. */
  6822. Tools.hashCodeFromStream = function (feeder) {
  6823. // Based from here: http://stackoverflow.com/a/7616484/802124
  6824. var hash = 0;
  6825. var index = 0;
  6826. var chr = feeder(index++);
  6827. while (chr != null) {
  6828. hash = ((hash << 5) - hash) + chr;
  6829. hash |= 0; // Convert to 32bit integer
  6830. chr = feeder(index++);
  6831. }
  6832. return hash;
  6833. };
  6834. Tools.BaseUrl = "";
  6835. Tools.CorsBehavior = "anonymous";
  6836. Tools.UseFallbackTexture = true;
  6837. /**
  6838. * Use this object to register external classes like custom textures or material
  6839. * to allow the laoders to instantiate them
  6840. */
  6841. Tools.RegisteredExternalClasses = {};
  6842. // Used in case of a texture loading problem
  6843. 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";
  6844. Tools.PreprocessUrl = function (url) {
  6845. return url;
  6846. };
  6847. // Logs
  6848. Tools._NoneLogLevel = 0;
  6849. Tools._MessageLogLevel = 1;
  6850. Tools._WarningLogLevel = 2;
  6851. Tools._ErrorLogLevel = 4;
  6852. Tools._LogCache = "";
  6853. Tools.errorsCount = 0;
  6854. Tools.Log = Tools._LogEnabled;
  6855. Tools.Warn = Tools._WarnEnabled;
  6856. Tools.Error = Tools._ErrorEnabled;
  6857. // Performances
  6858. Tools._PerformanceNoneLogLevel = 0;
  6859. Tools._PerformanceUserMarkLogLevel = 1;
  6860. Tools._PerformanceConsoleLogLevel = 2;
  6861. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6862. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6863. return Tools;
  6864. }());
  6865. BABYLON.Tools = Tools;
  6866. /**
  6867. * This class is used to track a performance counter which is number based.
  6868. * The user has access to many properties which give statistics of different nature
  6869. *
  6870. * The implementer can track two kinds of Performance Counter: time and count
  6871. * 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.
  6872. * 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.
  6873. */
  6874. var PerfCounter = /** @class */ (function () {
  6875. function PerfCounter() {
  6876. this._startMonitoringTime = 0;
  6877. this._min = 0;
  6878. this._max = 0;
  6879. this._average = 0;
  6880. this._lastSecAverage = 0;
  6881. this._current = 0;
  6882. this._totalValueCount = 0;
  6883. this._totalAccumulated = 0;
  6884. this._lastSecAccumulated = 0;
  6885. this._lastSecTime = 0;
  6886. this._lastSecValueCount = 0;
  6887. }
  6888. Object.defineProperty(PerfCounter.prototype, "min", {
  6889. /**
  6890. * Returns the smallest value ever
  6891. */
  6892. get: function () {
  6893. return this._min;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(PerfCounter.prototype, "max", {
  6899. /**
  6900. * Returns the biggest value ever
  6901. */
  6902. get: function () {
  6903. return this._max;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(PerfCounter.prototype, "average", {
  6909. /**
  6910. * Returns the average value since the performance counter is running
  6911. */
  6912. get: function () {
  6913. return this._average;
  6914. },
  6915. enumerable: true,
  6916. configurable: true
  6917. });
  6918. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6919. /**
  6920. * Returns the average value of the last second the counter was monitored
  6921. */
  6922. get: function () {
  6923. return this._lastSecAverage;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(PerfCounter.prototype, "current", {
  6929. /**
  6930. * Returns the current value
  6931. */
  6932. get: function () {
  6933. return this._current;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(PerfCounter.prototype, "total", {
  6939. get: function () {
  6940. return this._totalAccumulated;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(PerfCounter.prototype, "count", {
  6946. get: function () {
  6947. return this._totalValueCount;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. /**
  6953. * Call this method to start monitoring a new frame.
  6954. * 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.
  6955. */
  6956. PerfCounter.prototype.fetchNewFrame = function () {
  6957. this._totalValueCount++;
  6958. this._current = 0;
  6959. this._lastSecValueCount++;
  6960. };
  6961. /**
  6962. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6963. * @param newCount the count value to add to the monitored count
  6964. * @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.
  6965. */
  6966. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6967. if (!PerfCounter.Enabled) {
  6968. return;
  6969. }
  6970. this._current += newCount;
  6971. if (fetchResult) {
  6972. this._fetchResult();
  6973. }
  6974. };
  6975. /**
  6976. * Start monitoring this performance counter
  6977. */
  6978. PerfCounter.prototype.beginMonitoring = function () {
  6979. if (!PerfCounter.Enabled) {
  6980. return;
  6981. }
  6982. this._startMonitoringTime = Tools.Now;
  6983. };
  6984. /**
  6985. * Compute the time lapsed since the previous beginMonitoring() call.
  6986. * @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
  6987. */
  6988. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6989. if (newFrame === void 0) { newFrame = true; }
  6990. if (!PerfCounter.Enabled) {
  6991. return;
  6992. }
  6993. if (newFrame) {
  6994. this.fetchNewFrame();
  6995. }
  6996. var currentTime = Tools.Now;
  6997. this._current = currentTime - this._startMonitoringTime;
  6998. if (newFrame) {
  6999. this._fetchResult();
  7000. }
  7001. };
  7002. PerfCounter.prototype._fetchResult = function () {
  7003. this._totalAccumulated += this._current;
  7004. this._lastSecAccumulated += this._current;
  7005. // Min/Max update
  7006. this._min = Math.min(this._min, this._current);
  7007. this._max = Math.max(this._max, this._current);
  7008. this._average = this._totalAccumulated / this._totalValueCount;
  7009. // Reset last sec?
  7010. var now = Tools.Now;
  7011. if ((now - this._lastSecTime) > 1000) {
  7012. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7013. this._lastSecTime = now;
  7014. this._lastSecAccumulated = 0;
  7015. this._lastSecValueCount = 0;
  7016. }
  7017. };
  7018. PerfCounter.Enabled = true;
  7019. return PerfCounter;
  7020. }());
  7021. BABYLON.PerfCounter = PerfCounter;
  7022. /**
  7023. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7024. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7025. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7026. * @param name The name of the class, case should be preserved
  7027. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7028. */
  7029. function className(name, module) {
  7030. return function (target) {
  7031. target["__bjsclassName__"] = name;
  7032. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7033. };
  7034. }
  7035. BABYLON.className = className;
  7036. /**
  7037. * An implementation of a loop for asynchronous functions.
  7038. */
  7039. var AsyncLoop = /** @class */ (function () {
  7040. /**
  7041. * Constroctor.
  7042. * @param iterations the number of iterations.
  7043. * @param _fn the function to run each iteration
  7044. * @param _successCallback the callback that will be called upon succesful execution
  7045. * @param offset starting offset.
  7046. */
  7047. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7048. if (offset === void 0) { offset = 0; }
  7049. this.iterations = iterations;
  7050. this._fn = _fn;
  7051. this._successCallback = _successCallback;
  7052. this.index = offset - 1;
  7053. this._done = false;
  7054. }
  7055. /**
  7056. * Execute the next iteration. Must be called after the last iteration was finished.
  7057. */
  7058. AsyncLoop.prototype.executeNext = function () {
  7059. if (!this._done) {
  7060. if (this.index + 1 < this.iterations) {
  7061. ++this.index;
  7062. this._fn(this);
  7063. }
  7064. else {
  7065. this.breakLoop();
  7066. }
  7067. }
  7068. };
  7069. /**
  7070. * Break the loop and run the success callback.
  7071. */
  7072. AsyncLoop.prototype.breakLoop = function () {
  7073. this._done = true;
  7074. this._successCallback();
  7075. };
  7076. /**
  7077. * Helper function
  7078. */
  7079. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7080. if (offset === void 0) { offset = 0; }
  7081. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7082. loop.executeNext();
  7083. return loop;
  7084. };
  7085. /**
  7086. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7087. * @param iterations total number of iterations
  7088. * @param syncedIterations number of synchronous iterations in each async iteration.
  7089. * @param fn the function to call each iteration.
  7090. * @param callback a success call back that will be called when iterating stops.
  7091. * @param breakFunction a break condition (optional)
  7092. * @param timeout timeout settings for the setTimeout function. default - 0.
  7093. * @constructor
  7094. */
  7095. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7096. if (timeout === void 0) { timeout = 0; }
  7097. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7098. if (breakFunction && breakFunction())
  7099. loop.breakLoop();
  7100. else {
  7101. setTimeout(function () {
  7102. for (var i = 0; i < syncedIterations; ++i) {
  7103. var iteration = (loop.index * syncedIterations) + i;
  7104. if (iteration >= iterations)
  7105. break;
  7106. fn(iteration);
  7107. if (breakFunction && breakFunction()) {
  7108. loop.breakLoop();
  7109. break;
  7110. }
  7111. }
  7112. loop.executeNext();
  7113. }, timeout);
  7114. }
  7115. }, callback);
  7116. };
  7117. return AsyncLoop;
  7118. }());
  7119. BABYLON.AsyncLoop = AsyncLoop;
  7120. })(BABYLON || (BABYLON = {}));
  7121. //# sourceMappingURL=babylon.tools.js.map
  7122. var BABYLON;
  7123. (function (BABYLON) {
  7124. var Internals;
  7125. (function (Internals) {
  7126. var _AlphaState = /** @class */ (function () {
  7127. /**
  7128. * Initializes the state.
  7129. */
  7130. function _AlphaState() {
  7131. this._isAlphaBlendDirty = false;
  7132. this._isBlendFunctionParametersDirty = false;
  7133. this._isBlendEquationParametersDirty = false;
  7134. this._isBlendConstantsDirty = false;
  7135. this._alphaBlend = false;
  7136. this._blendFunctionParameters = new Array(4);
  7137. this._blendEquationParameters = new Array(2);
  7138. this._blendConstants = new Array(4);
  7139. this.reset();
  7140. }
  7141. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7142. get: function () {
  7143. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7144. },
  7145. enumerable: true,
  7146. configurable: true
  7147. });
  7148. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7149. get: function () {
  7150. return this._alphaBlend;
  7151. },
  7152. set: function (value) {
  7153. if (this._alphaBlend === value) {
  7154. return;
  7155. }
  7156. this._alphaBlend = value;
  7157. this._isAlphaBlendDirty = true;
  7158. },
  7159. enumerable: true,
  7160. configurable: true
  7161. });
  7162. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7163. if (this._blendConstants[0] === r &&
  7164. this._blendConstants[1] === g &&
  7165. this._blendConstants[2] === b &&
  7166. this._blendConstants[3] === a) {
  7167. return;
  7168. }
  7169. this._blendConstants[0] = r;
  7170. this._blendConstants[1] = g;
  7171. this._blendConstants[2] = b;
  7172. this._blendConstants[3] = a;
  7173. this._isBlendConstantsDirty = true;
  7174. };
  7175. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7176. if (this._blendFunctionParameters[0] === value0 &&
  7177. this._blendFunctionParameters[1] === value1 &&
  7178. this._blendFunctionParameters[2] === value2 &&
  7179. this._blendFunctionParameters[3] === value3) {
  7180. return;
  7181. }
  7182. this._blendFunctionParameters[0] = value0;
  7183. this._blendFunctionParameters[1] = value1;
  7184. this._blendFunctionParameters[2] = value2;
  7185. this._blendFunctionParameters[3] = value3;
  7186. this._isBlendFunctionParametersDirty = true;
  7187. };
  7188. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7189. if (this._blendEquationParameters[0] === rgb &&
  7190. this._blendEquationParameters[1] === alpha) {
  7191. return;
  7192. }
  7193. this._blendEquationParameters[0] = rgb;
  7194. this._blendEquationParameters[1] = alpha;
  7195. this._isBlendEquationParametersDirty = true;
  7196. };
  7197. _AlphaState.prototype.reset = function () {
  7198. this._alphaBlend = false;
  7199. this._blendFunctionParameters[0] = null;
  7200. this._blendFunctionParameters[1] = null;
  7201. this._blendFunctionParameters[2] = null;
  7202. this._blendFunctionParameters[3] = null;
  7203. this._blendEquationParameters[0] = null;
  7204. this._blendEquationParameters[1] = null;
  7205. this._blendConstants[0] = null;
  7206. this._blendConstants[1] = null;
  7207. this._blendConstants[2] = null;
  7208. this._blendConstants[3] = null;
  7209. this._isAlphaBlendDirty = true;
  7210. this._isBlendFunctionParametersDirty = false;
  7211. this._isBlendEquationParametersDirty = false;
  7212. this._isBlendConstantsDirty = false;
  7213. };
  7214. _AlphaState.prototype.apply = function (gl) {
  7215. if (!this.isDirty) {
  7216. return;
  7217. }
  7218. // Alpha blend
  7219. if (this._isAlphaBlendDirty) {
  7220. if (this._alphaBlend) {
  7221. gl.enable(gl.BLEND);
  7222. }
  7223. else {
  7224. gl.disable(gl.BLEND);
  7225. }
  7226. this._isAlphaBlendDirty = false;
  7227. }
  7228. // Alpha function
  7229. if (this._isBlendFunctionParametersDirty) {
  7230. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7231. this._isBlendFunctionParametersDirty = false;
  7232. }
  7233. // Alpha equation
  7234. if (this._isBlendEquationParametersDirty) {
  7235. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7236. this._isBlendEquationParametersDirty = false;
  7237. }
  7238. // Constants
  7239. if (this._isBlendConstantsDirty) {
  7240. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7241. this._isBlendConstantsDirty = false;
  7242. }
  7243. };
  7244. return _AlphaState;
  7245. }());
  7246. Internals._AlphaState = _AlphaState;
  7247. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7248. })(BABYLON || (BABYLON = {}));
  7249. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7250. var BABYLON;
  7251. (function (BABYLON) {
  7252. var Internals;
  7253. (function (Internals) {
  7254. var _DepthCullingState = /** @class */ (function () {
  7255. /**
  7256. * Initializes the state.
  7257. */
  7258. function _DepthCullingState() {
  7259. this._isDepthTestDirty = false;
  7260. this._isDepthMaskDirty = false;
  7261. this._isDepthFuncDirty = false;
  7262. this._isCullFaceDirty = false;
  7263. this._isCullDirty = false;
  7264. this._isZOffsetDirty = false;
  7265. this.reset();
  7266. }
  7267. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7268. get: function () {
  7269. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7270. },
  7271. enumerable: true,
  7272. configurable: true
  7273. });
  7274. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7275. get: function () {
  7276. return this._zOffset;
  7277. },
  7278. set: function (value) {
  7279. if (this._zOffset === value) {
  7280. return;
  7281. }
  7282. this._zOffset = value;
  7283. this._isZOffsetDirty = true;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7289. get: function () {
  7290. return this._cullFace;
  7291. },
  7292. set: function (value) {
  7293. if (this._cullFace === value) {
  7294. return;
  7295. }
  7296. this._cullFace = value;
  7297. this._isCullFaceDirty = true;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7303. get: function () {
  7304. return this._cull;
  7305. },
  7306. set: function (value) {
  7307. if (this._cull === value) {
  7308. return;
  7309. }
  7310. this._cull = value;
  7311. this._isCullDirty = true;
  7312. },
  7313. enumerable: true,
  7314. configurable: true
  7315. });
  7316. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7317. get: function () {
  7318. return this._depthFunc;
  7319. },
  7320. set: function (value) {
  7321. if (this._depthFunc === value) {
  7322. return;
  7323. }
  7324. this._depthFunc = value;
  7325. this._isDepthFuncDirty = true;
  7326. },
  7327. enumerable: true,
  7328. configurable: true
  7329. });
  7330. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7331. get: function () {
  7332. return this._depthMask;
  7333. },
  7334. set: function (value) {
  7335. if (this._depthMask === value) {
  7336. return;
  7337. }
  7338. this._depthMask = value;
  7339. this._isDepthMaskDirty = true;
  7340. },
  7341. enumerable: true,
  7342. configurable: true
  7343. });
  7344. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7345. get: function () {
  7346. return this._depthTest;
  7347. },
  7348. set: function (value) {
  7349. if (this._depthTest === value) {
  7350. return;
  7351. }
  7352. this._depthTest = value;
  7353. this._isDepthTestDirty = true;
  7354. },
  7355. enumerable: true,
  7356. configurable: true
  7357. });
  7358. _DepthCullingState.prototype.reset = function () {
  7359. this._depthMask = true;
  7360. this._depthTest = true;
  7361. this._depthFunc = null;
  7362. this._cullFace = null;
  7363. this._cull = null;
  7364. this._zOffset = 0;
  7365. this._isDepthTestDirty = true;
  7366. this._isDepthMaskDirty = true;
  7367. this._isDepthFuncDirty = false;
  7368. this._isCullFaceDirty = false;
  7369. this._isCullDirty = false;
  7370. this._isZOffsetDirty = false;
  7371. };
  7372. _DepthCullingState.prototype.apply = function (gl) {
  7373. if (!this.isDirty) {
  7374. return;
  7375. }
  7376. // Cull
  7377. if (this._isCullDirty) {
  7378. if (this.cull) {
  7379. gl.enable(gl.CULL_FACE);
  7380. }
  7381. else {
  7382. gl.disable(gl.CULL_FACE);
  7383. }
  7384. this._isCullDirty = false;
  7385. }
  7386. // Cull face
  7387. if (this._isCullFaceDirty) {
  7388. gl.cullFace(this.cullFace);
  7389. this._isCullFaceDirty = false;
  7390. }
  7391. // Depth mask
  7392. if (this._isDepthMaskDirty) {
  7393. gl.depthMask(this.depthMask);
  7394. this._isDepthMaskDirty = false;
  7395. }
  7396. // Depth test
  7397. if (this._isDepthTestDirty) {
  7398. if (this.depthTest) {
  7399. gl.enable(gl.DEPTH_TEST);
  7400. }
  7401. else {
  7402. gl.disable(gl.DEPTH_TEST);
  7403. }
  7404. this._isDepthTestDirty = false;
  7405. }
  7406. // Depth func
  7407. if (this._isDepthFuncDirty) {
  7408. gl.depthFunc(this.depthFunc);
  7409. this._isDepthFuncDirty = false;
  7410. }
  7411. // zOffset
  7412. if (this._isZOffsetDirty) {
  7413. if (this.zOffset) {
  7414. gl.enable(gl.POLYGON_OFFSET_FILL);
  7415. gl.polygonOffset(this.zOffset, 0);
  7416. }
  7417. else {
  7418. gl.disable(gl.POLYGON_OFFSET_FILL);
  7419. }
  7420. this._isZOffsetDirty = false;
  7421. }
  7422. };
  7423. return _DepthCullingState;
  7424. }());
  7425. Internals._DepthCullingState = _DepthCullingState;
  7426. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7427. })(BABYLON || (BABYLON = {}));
  7428. //# sourceMappingURL=babylon.depthCullingState.js.map
  7429. var BABYLON;
  7430. (function (BABYLON) {
  7431. var Internals;
  7432. (function (Internals) {
  7433. var _StencilState = /** @class */ (function () {
  7434. function _StencilState() {
  7435. this._isStencilTestDirty = false;
  7436. this._isStencilMaskDirty = false;
  7437. this._isStencilFuncDirty = false;
  7438. this._isStencilOpDirty = false;
  7439. this.reset();
  7440. }
  7441. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7442. get: function () {
  7443. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7449. get: function () {
  7450. return this._stencilFunc;
  7451. },
  7452. set: function (value) {
  7453. if (this._stencilFunc === value) {
  7454. return;
  7455. }
  7456. this._stencilFunc = value;
  7457. this._isStencilFuncDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7463. get: function () {
  7464. return this._stencilFuncRef;
  7465. },
  7466. set: function (value) {
  7467. if (this._stencilFuncRef === value) {
  7468. return;
  7469. }
  7470. this._stencilFuncRef = value;
  7471. this._isStencilFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7477. get: function () {
  7478. return this._stencilFuncMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._stencilFuncMask === value) {
  7482. return;
  7483. }
  7484. this._stencilFuncMask = value;
  7485. this._isStencilFuncDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7491. get: function () {
  7492. return this._stencilOpStencilFail;
  7493. },
  7494. set: function (value) {
  7495. if (this._stencilOpStencilFail === value) {
  7496. return;
  7497. }
  7498. this._stencilOpStencilFail = value;
  7499. this._isStencilOpDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7505. get: function () {
  7506. return this._stencilOpDepthFail;
  7507. },
  7508. set: function (value) {
  7509. if (this._stencilOpDepthFail === value) {
  7510. return;
  7511. }
  7512. this._stencilOpDepthFail = value;
  7513. this._isStencilOpDirty = true;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7519. get: function () {
  7520. return this._stencilOpStencilDepthPass;
  7521. },
  7522. set: function (value) {
  7523. if (this._stencilOpStencilDepthPass === value) {
  7524. return;
  7525. }
  7526. this._stencilOpStencilDepthPass = value;
  7527. this._isStencilOpDirty = true;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7533. get: function () {
  7534. return this._stencilMask;
  7535. },
  7536. set: function (value) {
  7537. if (this._stencilMask === value) {
  7538. return;
  7539. }
  7540. this._stencilMask = value;
  7541. this._isStencilMaskDirty = true;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7547. get: function () {
  7548. return this._stencilTest;
  7549. },
  7550. set: function (value) {
  7551. if (this._stencilTest === value) {
  7552. return;
  7553. }
  7554. this._stencilTest = value;
  7555. this._isStencilTestDirty = true;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. _StencilState.prototype.reset = function () {
  7561. this._stencilTest = false;
  7562. this._stencilMask = 0xFF;
  7563. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7564. this._stencilFuncRef = 1;
  7565. this._stencilFuncMask = 0xFF;
  7566. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7567. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7568. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7569. this._isStencilTestDirty = true;
  7570. this._isStencilMaskDirty = true;
  7571. this._isStencilFuncDirty = true;
  7572. this._isStencilOpDirty = true;
  7573. };
  7574. _StencilState.prototype.apply = function (gl) {
  7575. if (!this.isDirty) {
  7576. return;
  7577. }
  7578. // Stencil test
  7579. if (this._isStencilTestDirty) {
  7580. if (this.stencilTest) {
  7581. gl.enable(gl.STENCIL_TEST);
  7582. }
  7583. else {
  7584. gl.disable(gl.STENCIL_TEST);
  7585. }
  7586. this._isStencilTestDirty = false;
  7587. }
  7588. // Stencil mask
  7589. if (this._isStencilMaskDirty) {
  7590. gl.stencilMask(this.stencilMask);
  7591. this._isStencilMaskDirty = false;
  7592. }
  7593. // Stencil func
  7594. if (this._isStencilFuncDirty) {
  7595. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7596. this._isStencilFuncDirty = false;
  7597. }
  7598. // Stencil op
  7599. if (this._isStencilOpDirty) {
  7600. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7601. this._isStencilOpDirty = false;
  7602. }
  7603. };
  7604. return _StencilState;
  7605. }());
  7606. Internals._StencilState = _StencilState;
  7607. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7608. })(BABYLON || (BABYLON = {}));
  7609. //# sourceMappingURL=babylon.stencilState.js.map
  7610. var BABYLON;
  7611. (function (BABYLON) {
  7612. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7613. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7614. };
  7615. var compileRawShader = function (gl, source, type) {
  7616. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7617. gl.shaderSource(shader, source);
  7618. gl.compileShader(shader);
  7619. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7620. var log = gl.getShaderInfoLog(shader);
  7621. if (log) {
  7622. throw new Error(log);
  7623. }
  7624. }
  7625. if (!shader) {
  7626. throw new Error("Something went wrong while compile the shader.");
  7627. }
  7628. return shader;
  7629. };
  7630. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7631. var magFilter = gl.NEAREST;
  7632. var minFilter = gl.NEAREST;
  7633. switch (samplingMode) {
  7634. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7635. magFilter = gl.LINEAR;
  7636. if (generateMipMaps) {
  7637. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7638. }
  7639. else {
  7640. minFilter = gl.LINEAR;
  7641. }
  7642. break;
  7643. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7644. magFilter = gl.LINEAR;
  7645. if (generateMipMaps) {
  7646. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7647. }
  7648. else {
  7649. minFilter = gl.LINEAR;
  7650. }
  7651. break;
  7652. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7653. magFilter = gl.NEAREST;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7656. }
  7657. else {
  7658. minFilter = gl.NEAREST;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7662. magFilter = gl.NEAREST;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7665. }
  7666. else {
  7667. minFilter = gl.NEAREST;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7674. }
  7675. else {
  7676. minFilter = gl.LINEAR;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7683. }
  7684. else {
  7685. minFilter = gl.LINEAR;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR:
  7689. magFilter = gl.NEAREST;
  7690. minFilter = gl.LINEAR;
  7691. break;
  7692. case BABYLON.Texture.NEAREST_NEAREST:
  7693. magFilter = gl.NEAREST;
  7694. minFilter = gl.NEAREST;
  7695. break;
  7696. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7697. magFilter = gl.LINEAR;
  7698. if (generateMipMaps) {
  7699. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7700. }
  7701. else {
  7702. minFilter = gl.NEAREST;
  7703. }
  7704. break;
  7705. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7706. magFilter = gl.LINEAR;
  7707. if (generateMipMaps) {
  7708. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7709. }
  7710. else {
  7711. minFilter = gl.NEAREST;
  7712. }
  7713. break;
  7714. case BABYLON.Texture.LINEAR_LINEAR:
  7715. magFilter = gl.LINEAR;
  7716. minFilter = gl.LINEAR;
  7717. break;
  7718. case BABYLON.Texture.LINEAR_NEAREST:
  7719. magFilter = gl.LINEAR;
  7720. minFilter = gl.NEAREST;
  7721. break;
  7722. }
  7723. return {
  7724. min: minFilter,
  7725. mag: magFilter
  7726. };
  7727. };
  7728. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7729. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7730. var img;
  7731. var onload = function () {
  7732. loadedImages[index] = img;
  7733. loadedImages._internalCount++;
  7734. if (scene) {
  7735. scene._removePendingData(img);
  7736. }
  7737. if (loadedImages._internalCount === 6) {
  7738. onfinish(loadedImages);
  7739. }
  7740. };
  7741. var onerror = function (message, exception) {
  7742. if (scene) {
  7743. scene._removePendingData(img);
  7744. }
  7745. if (onErrorCallBack) {
  7746. onErrorCallBack(message, exception);
  7747. }
  7748. };
  7749. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7750. if (scene) {
  7751. scene._addPendingData(img);
  7752. }
  7753. };
  7754. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7755. if (onError === void 0) { onError = null; }
  7756. var loadedImages = [];
  7757. loadedImages._internalCount = 0;
  7758. for (var index = 0; index < 6; index++) {
  7759. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7760. }
  7761. };
  7762. var BufferPointer = /** @class */ (function () {
  7763. function BufferPointer() {
  7764. }
  7765. return BufferPointer;
  7766. }());
  7767. var InstancingAttributeInfo = /** @class */ (function () {
  7768. function InstancingAttributeInfo() {
  7769. }
  7770. return InstancingAttributeInfo;
  7771. }());
  7772. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7773. /**
  7774. * Define options used to create a render target texture
  7775. */
  7776. var RenderTargetCreationOptions = /** @class */ (function () {
  7777. function RenderTargetCreationOptions() {
  7778. }
  7779. return RenderTargetCreationOptions;
  7780. }());
  7781. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7782. /**
  7783. * Regroup several parameters relative to the browser in use
  7784. */
  7785. var EngineCapabilities = /** @class */ (function () {
  7786. function EngineCapabilities() {
  7787. }
  7788. return EngineCapabilities;
  7789. }());
  7790. BABYLON.EngineCapabilities = EngineCapabilities;
  7791. /**
  7792. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7793. */
  7794. var Engine = /** @class */ (function () {
  7795. /**
  7796. * @constructor
  7797. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7798. * @param {boolean} [antialias] - enable antialias
  7799. * @param options - further options to be sent to the getContext function
  7800. */
  7801. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7802. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7803. var _this = this;
  7804. // Public members
  7805. this.forcePOTTextures = false;
  7806. this.isFullscreen = false;
  7807. this.isPointerLock = false;
  7808. this.cullBackFaces = true;
  7809. this.renderEvenInBackground = true;
  7810. this.preventCacheWipeBetweenFrames = false;
  7811. // To enable/disable IDB support and avoid XHR on .manifest
  7812. this.enableOfflineSupport = false;
  7813. this.scenes = new Array();
  7814. this.postProcesses = new Array();
  7815. // Observables
  7816. /**
  7817. * Observable event triggered each time the rendering canvas is resized
  7818. */
  7819. this.onResizeObservable = new BABYLON.Observable();
  7820. /**
  7821. * Observable event triggered each time the canvas loses focus
  7822. */
  7823. this.onCanvasBlurObservable = new BABYLON.Observable();
  7824. /**
  7825. * Observable event triggered each time the canvas gains focus
  7826. */
  7827. this.onCanvasFocusObservable = new BABYLON.Observable();
  7828. /**
  7829. * Observable event triggered each time the canvas receives pointerout event
  7830. */
  7831. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7832. /**
  7833. * Observable event triggered before each texture is initialized
  7834. */
  7835. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7836. //WebVR
  7837. this._vrDisplay = undefined;
  7838. this._vrSupported = false;
  7839. this._vrExclusivePointerMode = false;
  7840. // Uniform buffers list
  7841. this.disableUniformBuffers = false;
  7842. this._uniformBuffers = new Array();
  7843. // Observables
  7844. /**
  7845. * Observable raised when the engine begins a new frame
  7846. */
  7847. this.onBeginFrameObservable = new BABYLON.Observable();
  7848. /**
  7849. * Observable raised when the engine ends the current frame
  7850. */
  7851. this.onEndFrameObservable = new BABYLON.Observable();
  7852. /**
  7853. * Observable raised when the engine is about to compile a shader
  7854. */
  7855. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7856. /**
  7857. * Observable raised when the engine has jsut compiled a shader
  7858. */
  7859. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7860. this._windowIsBackground = false;
  7861. this._webGLVersion = 1.0;
  7862. this._badOS = false;
  7863. this._badDesktopOS = false;
  7864. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7865. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7866. this.onVRRequestPresentStart = new BABYLON.Observable();
  7867. this._colorWrite = true;
  7868. this._drawCalls = new BABYLON.PerfCounter();
  7869. this._renderingQueueLaunched = false;
  7870. this._activeRenderLoops = new Array();
  7871. // Deterministic lockstepMaxSteps
  7872. this._deterministicLockstep = false;
  7873. this._lockstepMaxSteps = 4;
  7874. // Lost context
  7875. this.onContextLostObservable = new BABYLON.Observable();
  7876. this.onContextRestoredObservable = new BABYLON.Observable();
  7877. this._contextWasLost = false;
  7878. this._doNotHandleContextLost = false;
  7879. // FPS
  7880. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7881. this._fps = 60;
  7882. this._deltaTime = 0;
  7883. /**
  7884. * Turn this value on if you want to pause FPS computation when in background
  7885. */
  7886. this.disablePerformanceMonitorInBackground = false;
  7887. // States
  7888. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7889. this._stencilState = new BABYLON.Internals._StencilState();
  7890. this._alphaState = new BABYLON.Internals._AlphaState();
  7891. this._alphaMode = Engine.ALPHA_DISABLE;
  7892. // Cache
  7893. this._internalTexturesCache = new Array();
  7894. this._activeTexturesCache = {};
  7895. this._compiledEffects = {};
  7896. this._vertexAttribArraysEnabled = [];
  7897. this._uintIndicesCurrentlySet = false;
  7898. this._currentBoundBuffer = new Array();
  7899. this._currentBufferPointers = new Array();
  7900. this._currentInstanceLocations = new Array();
  7901. this._currentInstanceBuffers = new Array();
  7902. this._vaoRecordInProgress = false;
  7903. this._mustWipeVertexAttributes = false;
  7904. // Hardware supported Compressed Textures
  7905. this._texturesSupported = new Array();
  7906. this._onVRFullScreenTriggered = function () {
  7907. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7908. //get the old size before we change
  7909. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7910. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7911. //get the width and height, change the render size
  7912. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7913. _this.setHardwareScalingLevel(1);
  7914. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7915. }
  7916. else {
  7917. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7918. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7919. }
  7920. };
  7921. var canvas = null;
  7922. Engine.Instances.push(this);
  7923. if (!canvasOrContext) {
  7924. return;
  7925. }
  7926. options = options || {};
  7927. if (canvasOrContext.getContext) {
  7928. canvas = canvasOrContext;
  7929. this._renderingCanvas = canvas;
  7930. if (antialias != null) {
  7931. options.antialias = antialias;
  7932. }
  7933. if (options.deterministicLockstep === undefined) {
  7934. options.deterministicLockstep = false;
  7935. }
  7936. if (options.lockstepMaxSteps === undefined) {
  7937. options.lockstepMaxSteps = 4;
  7938. }
  7939. if (options.preserveDrawingBuffer === undefined) {
  7940. options.preserveDrawingBuffer = false;
  7941. }
  7942. if (options.audioEngine === undefined) {
  7943. options.audioEngine = true;
  7944. }
  7945. if (options.stencil === undefined) {
  7946. options.stencil = true;
  7947. }
  7948. this._deterministicLockstep = options.deterministicLockstep;
  7949. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7950. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7951. // GL
  7952. if (!options.disableWebGL2Support) {
  7953. try {
  7954. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7955. if (this._gl) {
  7956. this._webGLVersion = 2.0;
  7957. }
  7958. }
  7959. catch (e) {
  7960. // Do nothing
  7961. }
  7962. }
  7963. if (!this._gl) {
  7964. if (!canvas) {
  7965. throw new Error("The provided canvas is null or undefined.");
  7966. }
  7967. try {
  7968. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7969. }
  7970. catch (e) {
  7971. throw new Error("WebGL not supported");
  7972. }
  7973. }
  7974. if (!this._gl) {
  7975. throw new Error("WebGL not supported");
  7976. }
  7977. this._onCanvasFocus = function () {
  7978. _this.onCanvasFocusObservable.notifyObservers(_this);
  7979. };
  7980. this._onCanvasBlur = function () {
  7981. _this.onCanvasBlurObservable.notifyObservers(_this);
  7982. };
  7983. canvas.addEventListener("focus", this._onCanvasFocus);
  7984. canvas.addEventListener("blur", this._onCanvasBlur);
  7985. this._onBlur = function () {
  7986. if (_this.disablePerformanceMonitorInBackground) {
  7987. _this._performanceMonitor.disable();
  7988. }
  7989. _this._windowIsBackground = true;
  7990. };
  7991. this._onFocus = function () {
  7992. if (_this.disablePerformanceMonitorInBackground) {
  7993. _this._performanceMonitor.enable();
  7994. }
  7995. _this._windowIsBackground = false;
  7996. };
  7997. this._onCanvasPointerOut = function () {
  7998. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7999. };
  8000. window.addEventListener("blur", this._onBlur);
  8001. window.addEventListener("focus", this._onFocus);
  8002. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8003. // Context lost
  8004. if (!this._doNotHandleContextLost) {
  8005. this._onContextLost = function (evt) {
  8006. evt.preventDefault();
  8007. _this._contextWasLost = true;
  8008. BABYLON.Tools.Warn("WebGL context lost.");
  8009. _this.onContextLostObservable.notifyObservers(_this);
  8010. };
  8011. this._onContextRestored = function (evt) {
  8012. // Adding a timeout to avoid race condition at browser level
  8013. setTimeout(function () {
  8014. // Rebuild gl context
  8015. _this._initGLContext();
  8016. // Rebuild effects
  8017. _this._rebuildEffects();
  8018. // Rebuild textures
  8019. _this._rebuildInternalTextures();
  8020. // Rebuild buffers
  8021. _this._rebuildBuffers();
  8022. // Cache
  8023. _this.wipeCaches(true);
  8024. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8025. _this.onContextRestoredObservable.notifyObservers(_this);
  8026. _this._contextWasLost = false;
  8027. }, 0);
  8028. };
  8029. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8030. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8031. }
  8032. }
  8033. else {
  8034. this._gl = canvasOrContext;
  8035. this._renderingCanvas = this._gl.canvas;
  8036. if (this._gl.renderbufferStorageMultisample) {
  8037. this._webGLVersion = 2.0;
  8038. }
  8039. options.stencil = this._gl.getContextAttributes().stencil;
  8040. }
  8041. // Viewport
  8042. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8043. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8044. this.resize();
  8045. this._isStencilEnable = options.stencil ? true : false;
  8046. this._initGLContext();
  8047. if (canvas) {
  8048. // Fullscreen
  8049. this._onFullscreenChange = function () {
  8050. if (document.fullscreen !== undefined) {
  8051. _this.isFullscreen = document.fullscreen;
  8052. }
  8053. else if (document.mozFullScreen !== undefined) {
  8054. _this.isFullscreen = document.mozFullScreen;
  8055. }
  8056. else if (document.webkitIsFullScreen !== undefined) {
  8057. _this.isFullscreen = document.webkitIsFullScreen;
  8058. }
  8059. else if (document.msIsFullScreen !== undefined) {
  8060. _this.isFullscreen = document.msIsFullScreen;
  8061. }
  8062. // Pointer lock
  8063. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8064. canvas.requestPointerLock = canvas.requestPointerLock ||
  8065. canvas.msRequestPointerLock ||
  8066. canvas.mozRequestPointerLock ||
  8067. canvas.webkitRequestPointerLock;
  8068. if (canvas.requestPointerLock) {
  8069. canvas.requestPointerLock();
  8070. }
  8071. }
  8072. };
  8073. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8074. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8075. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8076. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8077. // Pointer lock
  8078. this._onPointerLockChange = function () {
  8079. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8080. document.webkitPointerLockElement === canvas ||
  8081. document.msPointerLockElement === canvas ||
  8082. document.pointerLockElement === canvas);
  8083. };
  8084. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8085. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8086. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8087. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8088. this._onVRDisplayPointerRestricted = function () {
  8089. if (canvas) {
  8090. canvas.requestPointerLock();
  8091. }
  8092. };
  8093. this._onVRDisplayPointerUnrestricted = function () {
  8094. document.exitPointerLock();
  8095. };
  8096. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8097. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8098. }
  8099. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8100. Engine.audioEngine = new BABYLON.AudioEngine();
  8101. }
  8102. // Prepare buffer pointers
  8103. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8104. this._currentBufferPointers[i] = new BufferPointer();
  8105. }
  8106. // Load WebVR Devices
  8107. if (options.autoEnableWebVR) {
  8108. this.initWebVR();
  8109. }
  8110. // Detect if we are running on a faulty buggy OS.
  8111. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8112. // Detect if we are running on a faulty buggy desktop OS.
  8113. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8114. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8115. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8116. }
  8117. Object.defineProperty(Engine, "LastCreatedEngine", {
  8118. get: function () {
  8119. if (Engine.Instances.length === 0) {
  8120. return null;
  8121. }
  8122. return Engine.Instances[Engine.Instances.length - 1];
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "LastCreatedScene", {
  8128. get: function () {
  8129. var lastCreatedEngine = Engine.LastCreatedEngine;
  8130. if (!lastCreatedEngine) {
  8131. return null;
  8132. }
  8133. if (lastCreatedEngine.scenes.length === 0) {
  8134. return null;
  8135. }
  8136. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. /**
  8142. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8143. */
  8144. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8145. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8146. var engine = Engine.Instances[engineIndex];
  8147. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8148. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8149. }
  8150. }
  8151. };
  8152. Object.defineProperty(Engine, "NEVER", {
  8153. get: function () {
  8154. return Engine._NEVER;
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. Object.defineProperty(Engine, "ALWAYS", {
  8160. get: function () {
  8161. return Engine._ALWAYS;
  8162. },
  8163. enumerable: true,
  8164. configurable: true
  8165. });
  8166. Object.defineProperty(Engine, "LESS", {
  8167. get: function () {
  8168. return Engine._LESS;
  8169. },
  8170. enumerable: true,
  8171. configurable: true
  8172. });
  8173. Object.defineProperty(Engine, "EQUAL", {
  8174. get: function () {
  8175. return Engine._EQUAL;
  8176. },
  8177. enumerable: true,
  8178. configurable: true
  8179. });
  8180. Object.defineProperty(Engine, "LEQUAL", {
  8181. get: function () {
  8182. return Engine._LEQUAL;
  8183. },
  8184. enumerable: true,
  8185. configurable: true
  8186. });
  8187. Object.defineProperty(Engine, "GREATER", {
  8188. get: function () {
  8189. return Engine._GREATER;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(Engine, "GEQUAL", {
  8195. get: function () {
  8196. return Engine._GEQUAL;
  8197. },
  8198. enumerable: true,
  8199. configurable: true
  8200. });
  8201. Object.defineProperty(Engine, "NOTEQUAL", {
  8202. get: function () {
  8203. return Engine._NOTEQUAL;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine, "KEEP", {
  8209. get: function () {
  8210. return Engine._KEEP;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Object.defineProperty(Engine, "REPLACE", {
  8216. get: function () {
  8217. return Engine._REPLACE;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. Object.defineProperty(Engine, "INCR", {
  8223. get: function () {
  8224. return Engine._INCR;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine, "DECR", {
  8230. get: function () {
  8231. return Engine._DECR;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Engine, "INVERT", {
  8237. get: function () {
  8238. return Engine._INVERT;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Engine, "INCR_WRAP", {
  8244. get: function () {
  8245. return Engine._INCR_WRAP;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(Engine, "DECR_WRAP", {
  8251. get: function () {
  8252. return Engine._DECR_WRAP;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8258. get: function () {
  8259. return Engine._ALPHA_DISABLE;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8265. get: function () {
  8266. return Engine._ALPHA_ONEONE;
  8267. },
  8268. enumerable: true,
  8269. configurable: true
  8270. });
  8271. Object.defineProperty(Engine, "ALPHA_ADD", {
  8272. get: function () {
  8273. return Engine._ALPHA_ADD;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8279. get: function () {
  8280. return Engine._ALPHA_COMBINE;
  8281. },
  8282. enumerable: true,
  8283. configurable: true
  8284. });
  8285. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8286. get: function () {
  8287. return Engine._ALPHA_SUBTRACT;
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8293. get: function () {
  8294. return Engine._ALPHA_MULTIPLY;
  8295. },
  8296. enumerable: true,
  8297. configurable: true
  8298. });
  8299. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8300. get: function () {
  8301. return Engine._ALPHA_MAXIMIZED;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8307. get: function () {
  8308. return Engine._ALPHA_PREMULTIPLIED;
  8309. },
  8310. enumerable: true,
  8311. configurable: true
  8312. });
  8313. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8314. get: function () {
  8315. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8321. get: function () {
  8322. return Engine._ALPHA_INTERPOLATE;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8328. get: function () {
  8329. return Engine._ALPHA_SCREENMODE;
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8335. get: function () {
  8336. return Engine._DELAYLOADSTATE_NONE;
  8337. },
  8338. enumerable: true,
  8339. configurable: true
  8340. });
  8341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8342. get: function () {
  8343. return Engine._DELAYLOADSTATE_LOADED;
  8344. },
  8345. enumerable: true,
  8346. configurable: true
  8347. });
  8348. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8349. get: function () {
  8350. return Engine._DELAYLOADSTATE_LOADING;
  8351. },
  8352. enumerable: true,
  8353. configurable: true
  8354. });
  8355. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8356. get: function () {
  8357. return Engine._DELAYLOADSTATE_NOTLOADED;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8363. get: function () {
  8364. return Engine._TEXTUREFORMAT_ALPHA;
  8365. },
  8366. enumerable: true,
  8367. configurable: true
  8368. });
  8369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8370. get: function () {
  8371. return Engine._TEXTUREFORMAT_LUMINANCE;
  8372. },
  8373. enumerable: true,
  8374. configurable: true
  8375. });
  8376. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8377. get: function () {
  8378. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8384. get: function () {
  8385. return Engine._TEXTUREFORMAT_RGB;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8391. get: function () {
  8392. return Engine._TEXTUREFORMAT_RGBA;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8398. get: function () {
  8399. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8405. get: function () {
  8406. return Engine._TEXTURETYPE_FLOAT;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8412. get: function () {
  8413. return Engine._TEXTURETYPE_HALF_FLOAT;
  8414. },
  8415. enumerable: true,
  8416. configurable: true
  8417. });
  8418. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8419. get: function () {
  8420. return Engine._SCALEMODE_FLOOR;
  8421. },
  8422. enumerable: true,
  8423. configurable: true
  8424. });
  8425. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8426. get: function () {
  8427. return Engine._SCALEMODE_NEAREST;
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8433. get: function () {
  8434. return Engine._SCALEMODE_CEILING;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. Object.defineProperty(Engine, "Version", {
  8440. get: function () {
  8441. return "3.1-alpha";
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8447. get: function () {
  8448. return this._vrExclusivePointerMode;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8454. get: function () {
  8455. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8461. get: function () {
  8462. return this._webGLVersion < 2 || this.forcePOTTextures;
  8463. },
  8464. enumerable: true,
  8465. configurable: true
  8466. });
  8467. Object.defineProperty(Engine.prototype, "badOS", {
  8468. get: function () {
  8469. return this._badOS;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8475. get: function () {
  8476. return this._badDesktopOS;
  8477. },
  8478. enumerable: true,
  8479. configurable: true
  8480. });
  8481. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8482. get: function () {
  8483. return this._performanceMonitor;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8489. get: function () {
  8490. return this._texturesSupported;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8496. get: function () {
  8497. return this._textureFormatInUse;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Object.defineProperty(Engine.prototype, "currentViewport", {
  8503. get: function () {
  8504. return this._cachedViewport;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8510. // Empty texture
  8511. get: function () {
  8512. if (!this._emptyTexture) {
  8513. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8514. }
  8515. return this._emptyTexture;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8521. get: function () {
  8522. if (!this._emptyTexture3D) {
  8523. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8524. }
  8525. return this._emptyTexture3D;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8531. get: function () {
  8532. if (!this._emptyCubeTexture) {
  8533. var faceData = new Uint8Array(4);
  8534. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8535. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8536. }
  8537. return this._emptyCubeTexture;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Engine.prototype._rebuildInternalTextures = function () {
  8543. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8544. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8545. var internalTexture = currentState_1[_i];
  8546. internalTexture._rebuild();
  8547. }
  8548. };
  8549. Engine.prototype._rebuildEffects = function () {
  8550. for (var key in this._compiledEffects) {
  8551. var effect = this._compiledEffects[key];
  8552. effect._prepareEffect();
  8553. }
  8554. BABYLON.Effect.ResetCache();
  8555. };
  8556. Engine.prototype._rebuildBuffers = function () {
  8557. // Index / Vertex
  8558. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8559. var scene = _a[_i];
  8560. scene.resetCachedMaterial();
  8561. scene._rebuildGeometries();
  8562. scene._rebuildTextures();
  8563. }
  8564. // Uniforms
  8565. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8566. var uniformBuffer = _c[_b];
  8567. uniformBuffer._rebuild();
  8568. }
  8569. };
  8570. Engine.prototype._initGLContext = function () {
  8571. // Caps
  8572. this._caps = new EngineCapabilities();
  8573. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8574. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8575. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8576. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8577. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8578. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8579. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8580. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8581. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8582. // Infos
  8583. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8584. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8585. if (rendererInfo != null) {
  8586. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8587. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8588. }
  8589. if (!this._glVendor) {
  8590. this._glVendor = "Unknown vendor";
  8591. }
  8592. if (!this._glRenderer) {
  8593. this._glRenderer = "Unknown renderer";
  8594. }
  8595. // Constants
  8596. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8597. if (this._gl.RGBA16F !== 0x881A) {
  8598. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8599. }
  8600. if (this._gl.RGBA32F !== 0x8814) {
  8601. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8602. }
  8603. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8604. this._gl.DEPTH24_STENCIL8 = 35056;
  8605. }
  8606. // Extensions
  8607. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8608. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8609. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8610. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8611. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8612. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8613. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8614. 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');
  8615. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8616. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8617. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8618. this._caps.highPrecisionShaderSupported = true;
  8619. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8620. if (this._caps.timerQuery) {
  8621. if (this._webGLVersion === 1) {
  8622. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8623. }
  8624. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8625. }
  8626. // Checks if some of the format renders first to allow the use of webgl inspector.
  8627. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8628. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8629. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8630. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8631. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8632. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8633. if (this._webGLVersion > 1) {
  8634. this._gl.HALF_FLOAT_OES = 0x140B;
  8635. }
  8636. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8637. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8638. // Draw buffers
  8639. if (this._webGLVersion > 1) {
  8640. this._caps.drawBuffersExtension = true;
  8641. }
  8642. else {
  8643. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8644. if (drawBuffersExtension !== null) {
  8645. this._caps.drawBuffersExtension = true;
  8646. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8647. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8648. for (var i = 0; i < 16; i++) {
  8649. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8650. }
  8651. }
  8652. else {
  8653. this._caps.drawBuffersExtension = false;
  8654. }
  8655. }
  8656. // Depth Texture
  8657. if (this._webGLVersion > 1) {
  8658. this._caps.depthTextureExtension = true;
  8659. }
  8660. else {
  8661. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8662. if (depthTextureExtension != null) {
  8663. this._caps.depthTextureExtension = true;
  8664. }
  8665. }
  8666. // Vertex array object
  8667. if (this._webGLVersion > 1) {
  8668. this._caps.vertexArrayObject = true;
  8669. }
  8670. else {
  8671. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8672. if (vertexArrayObjectExtension != null) {
  8673. this._caps.vertexArrayObject = true;
  8674. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8675. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8676. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8677. }
  8678. else {
  8679. this._caps.vertexArrayObject = false;
  8680. }
  8681. }
  8682. // Instances count
  8683. if (this._webGLVersion > 1) {
  8684. this._caps.instancedArrays = true;
  8685. }
  8686. else {
  8687. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8688. if (instanceExtension != null) {
  8689. this._caps.instancedArrays = true;
  8690. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8691. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8692. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8693. }
  8694. else {
  8695. this._caps.instancedArrays = false;
  8696. }
  8697. }
  8698. // Intelligently add supported compressed formats in order to check for.
  8699. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8700. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8701. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8702. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8703. if (this._caps.astc)
  8704. this.texturesSupported.push('-astc.ktx');
  8705. if (this._caps.s3tc)
  8706. this.texturesSupported.push('-dxt.ktx');
  8707. if (this._caps.pvrtc)
  8708. this.texturesSupported.push('-pvrtc.ktx');
  8709. if (this._caps.etc2)
  8710. this.texturesSupported.push('-etc2.ktx');
  8711. if (this._caps.etc1)
  8712. this.texturesSupported.push('-etc1.ktx');
  8713. if (this._gl.getShaderPrecisionFormat) {
  8714. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8715. if (highp) {
  8716. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8717. }
  8718. }
  8719. // Depth buffer
  8720. this.setDepthBuffer(true);
  8721. this.setDepthFunctionToLessOrEqual();
  8722. this.setDepthWrite(true);
  8723. };
  8724. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8725. get: function () {
  8726. return this._webGLVersion;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8732. /**
  8733. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8734. */
  8735. get: function () {
  8736. return this._isStencilEnable;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Engine.prototype._prepareWorkingCanvas = function () {
  8742. if (this._workingCanvas) {
  8743. return;
  8744. }
  8745. this._workingCanvas = document.createElement("canvas");
  8746. var context = this._workingCanvas.getContext("2d");
  8747. if (context) {
  8748. this._workingContext = context;
  8749. }
  8750. };
  8751. Engine.prototype.resetTextureCache = function () {
  8752. for (var key in this._activeTexturesCache) {
  8753. this._activeTexturesCache[key] = null;
  8754. }
  8755. };
  8756. Engine.prototype.isDeterministicLockStep = function () {
  8757. return this._deterministicLockstep;
  8758. };
  8759. Engine.prototype.getLockstepMaxSteps = function () {
  8760. return this._lockstepMaxSteps;
  8761. };
  8762. Engine.prototype.getGlInfo = function () {
  8763. return {
  8764. vendor: this._glVendor,
  8765. renderer: this._glRenderer,
  8766. version: this._glVersion
  8767. };
  8768. };
  8769. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8770. if (useScreen === void 0) { useScreen = false; }
  8771. var viewport = camera.viewport;
  8772. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8773. };
  8774. Engine.prototype.getRenderWidth = function (useScreen) {
  8775. if (useScreen === void 0) { useScreen = false; }
  8776. if (!useScreen && this._currentRenderTarget) {
  8777. return this._currentRenderTarget.width;
  8778. }
  8779. return this._gl.drawingBufferWidth;
  8780. };
  8781. Engine.prototype.getRenderHeight = function (useScreen) {
  8782. if (useScreen === void 0) { useScreen = false; }
  8783. if (!useScreen && this._currentRenderTarget) {
  8784. return this._currentRenderTarget.height;
  8785. }
  8786. return this._gl.drawingBufferHeight;
  8787. };
  8788. Engine.prototype.getRenderingCanvas = function () {
  8789. return this._renderingCanvas;
  8790. };
  8791. Engine.prototype.getRenderingCanvasClientRect = function () {
  8792. if (!this._renderingCanvas) {
  8793. return null;
  8794. }
  8795. return this._renderingCanvas.getBoundingClientRect();
  8796. };
  8797. Engine.prototype.setHardwareScalingLevel = function (level) {
  8798. this._hardwareScalingLevel = level;
  8799. this.resize();
  8800. };
  8801. Engine.prototype.getHardwareScalingLevel = function () {
  8802. return this._hardwareScalingLevel;
  8803. };
  8804. Engine.prototype.getLoadedTexturesCache = function () {
  8805. return this._internalTexturesCache;
  8806. };
  8807. Engine.prototype.getCaps = function () {
  8808. return this._caps;
  8809. };
  8810. Object.defineProperty(Engine.prototype, "drawCalls", {
  8811. /** The number of draw calls submitted last frame */
  8812. get: function () {
  8813. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8814. return 0;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8820. get: function () {
  8821. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8822. return null;
  8823. },
  8824. enumerable: true,
  8825. configurable: true
  8826. });
  8827. Engine.prototype.getDepthFunction = function () {
  8828. return this._depthCullingState.depthFunc;
  8829. };
  8830. Engine.prototype.setDepthFunction = function (depthFunc) {
  8831. this._depthCullingState.depthFunc = depthFunc;
  8832. };
  8833. Engine.prototype.setDepthFunctionToGreater = function () {
  8834. this._depthCullingState.depthFunc = this._gl.GREATER;
  8835. };
  8836. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8837. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8838. };
  8839. Engine.prototype.setDepthFunctionToLess = function () {
  8840. this._depthCullingState.depthFunc = this._gl.LESS;
  8841. };
  8842. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8843. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8844. };
  8845. Engine.prototype.getStencilBuffer = function () {
  8846. return this._stencilState.stencilTest;
  8847. };
  8848. Engine.prototype.setStencilBuffer = function (enable) {
  8849. this._stencilState.stencilTest = enable;
  8850. };
  8851. Engine.prototype.getStencilMask = function () {
  8852. return this._stencilState.stencilMask;
  8853. };
  8854. Engine.prototype.setStencilMask = function (mask) {
  8855. this._stencilState.stencilMask = mask;
  8856. };
  8857. Engine.prototype.getStencilFunction = function () {
  8858. return this._stencilState.stencilFunc;
  8859. };
  8860. Engine.prototype.getStencilFunctionReference = function () {
  8861. return this._stencilState.stencilFuncRef;
  8862. };
  8863. Engine.prototype.getStencilFunctionMask = function () {
  8864. return this._stencilState.stencilFuncMask;
  8865. };
  8866. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8867. this._stencilState.stencilFunc = stencilFunc;
  8868. };
  8869. Engine.prototype.setStencilFunctionReference = function (reference) {
  8870. this._stencilState.stencilFuncRef = reference;
  8871. };
  8872. Engine.prototype.setStencilFunctionMask = function (mask) {
  8873. this._stencilState.stencilFuncMask = mask;
  8874. };
  8875. Engine.prototype.getStencilOperationFail = function () {
  8876. return this._stencilState.stencilOpStencilFail;
  8877. };
  8878. Engine.prototype.getStencilOperationDepthFail = function () {
  8879. return this._stencilState.stencilOpDepthFail;
  8880. };
  8881. Engine.prototype.getStencilOperationPass = function () {
  8882. return this._stencilState.stencilOpStencilDepthPass;
  8883. };
  8884. Engine.prototype.setStencilOperationFail = function (operation) {
  8885. this._stencilState.stencilOpStencilFail = operation;
  8886. };
  8887. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8888. this._stencilState.stencilOpDepthFail = operation;
  8889. };
  8890. Engine.prototype.setStencilOperationPass = function (operation) {
  8891. this._stencilState.stencilOpStencilDepthPass = operation;
  8892. };
  8893. Engine.prototype.setDitheringState = function (value) {
  8894. if (value) {
  8895. this._gl.enable(this._gl.DITHER);
  8896. }
  8897. else {
  8898. this._gl.disable(this._gl.DITHER);
  8899. }
  8900. };
  8901. /**
  8902. * stop executing a render loop function and remove it from the execution array
  8903. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8904. */
  8905. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8906. if (!renderFunction) {
  8907. this._activeRenderLoops = [];
  8908. return;
  8909. }
  8910. var index = this._activeRenderLoops.indexOf(renderFunction);
  8911. if (index >= 0) {
  8912. this._activeRenderLoops.splice(index, 1);
  8913. }
  8914. };
  8915. Engine.prototype._renderLoop = function () {
  8916. if (!this._contextWasLost) {
  8917. var shouldRender = true;
  8918. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8919. shouldRender = false;
  8920. }
  8921. if (shouldRender) {
  8922. // Start new frame
  8923. this.beginFrame();
  8924. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8925. var renderFunction = this._activeRenderLoops[index];
  8926. renderFunction();
  8927. }
  8928. // Present
  8929. this.endFrame();
  8930. }
  8931. }
  8932. if (this._activeRenderLoops.length > 0) {
  8933. // Register new frame
  8934. var requester = null;
  8935. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8936. requester = this._vrDisplay;
  8937. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8938. }
  8939. else {
  8940. this._renderingQueueLaunched = false;
  8941. }
  8942. };
  8943. /**
  8944. * Register and execute a render loop. The engine can have more than one render function.
  8945. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8946. * @example
  8947. * engine.runRenderLoop(function () {
  8948. * scene.render()
  8949. * })
  8950. */
  8951. Engine.prototype.runRenderLoop = function (renderFunction) {
  8952. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8953. return;
  8954. }
  8955. this._activeRenderLoops.push(renderFunction);
  8956. if (!this._renderingQueueLaunched) {
  8957. this._renderingQueueLaunched = true;
  8958. this._bindedRenderFunction = this._renderLoop.bind(this);
  8959. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8960. }
  8961. };
  8962. /**
  8963. * Toggle full screen mode.
  8964. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8965. * @param {any} options - an options object to be sent to the requestFullscreen function
  8966. */
  8967. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8968. if (this.isFullscreen) {
  8969. BABYLON.Tools.ExitFullscreen();
  8970. }
  8971. else {
  8972. this._pointerLockRequested = requestPointerLock;
  8973. if (this._renderingCanvas) {
  8974. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8975. }
  8976. }
  8977. };
  8978. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8979. if (stencil === void 0) { stencil = false; }
  8980. this.applyStates();
  8981. var mode = 0;
  8982. if (backBuffer && color) {
  8983. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8984. mode |= this._gl.COLOR_BUFFER_BIT;
  8985. }
  8986. if (depth) {
  8987. this._gl.clearDepth(1.0);
  8988. mode |= this._gl.DEPTH_BUFFER_BIT;
  8989. }
  8990. if (stencil) {
  8991. this._gl.clearStencil(0);
  8992. mode |= this._gl.STENCIL_BUFFER_BIT;
  8993. }
  8994. this._gl.clear(mode);
  8995. };
  8996. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8997. var gl = this._gl;
  8998. // Save state
  8999. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9000. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9001. // Change state
  9002. gl.enable(gl.SCISSOR_TEST);
  9003. gl.scissor(x, y, width, height);
  9004. // Clear
  9005. this.clear(clearColor, true, true, true);
  9006. // Restore state
  9007. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9008. if (curScissor === true) {
  9009. gl.enable(gl.SCISSOR_TEST);
  9010. }
  9011. else {
  9012. gl.disable(gl.SCISSOR_TEST);
  9013. }
  9014. };
  9015. /**
  9016. * Set the WebGL's viewport
  9017. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9018. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9019. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9020. */
  9021. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9022. var width = requiredWidth || this.getRenderWidth();
  9023. var height = requiredHeight || this.getRenderHeight();
  9024. var x = viewport.x || 0;
  9025. var y = viewport.y || 0;
  9026. this._cachedViewport = viewport;
  9027. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9028. };
  9029. /**
  9030. * Directly set the WebGL Viewport
  9031. * The x, y, width & height are directly passed to the WebGL call
  9032. * @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.
  9033. */
  9034. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9035. var currentViewport = this._cachedViewport;
  9036. this._cachedViewport = null;
  9037. this._gl.viewport(x, y, width, height);
  9038. return currentViewport;
  9039. };
  9040. Engine.prototype.beginFrame = function () {
  9041. this.onBeginFrameObservable.notifyObservers(this);
  9042. this._measureFps();
  9043. };
  9044. Engine.prototype.endFrame = function () {
  9045. //force a flush in case we are using a bad OS.
  9046. if (this._badOS) {
  9047. this.flushFramebuffer();
  9048. }
  9049. //submit frame to the vr device, if enabled
  9050. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9051. // TODO: We should only submit the frame if we read frameData successfully.
  9052. this._vrDisplay.submitFrame();
  9053. }
  9054. this.onEndFrameObservable.notifyObservers(this);
  9055. };
  9056. /**
  9057. * resize the view according to the canvas' size.
  9058. * @example
  9059. * window.addEventListener("resize", function () {
  9060. * engine.resize();
  9061. * });
  9062. */
  9063. Engine.prototype.resize = function () {
  9064. // We're not resizing the size of the canvas while in VR mode & presenting
  9065. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9066. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9067. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9068. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9069. }
  9070. };
  9071. /**
  9072. * force a specific size of the canvas
  9073. * @param {number} width - the new canvas' width
  9074. * @param {number} height - the new canvas' height
  9075. */
  9076. Engine.prototype.setSize = function (width, height) {
  9077. if (!this._renderingCanvas) {
  9078. return;
  9079. }
  9080. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9081. return;
  9082. }
  9083. this._renderingCanvas.width = width;
  9084. this._renderingCanvas.height = height;
  9085. for (var index = 0; index < this.scenes.length; index++) {
  9086. var scene = this.scenes[index];
  9087. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9088. var cam = scene.cameras[camIndex];
  9089. cam._currentRenderId = 0;
  9090. }
  9091. }
  9092. if (this.onResizeObservable.hasObservers) {
  9093. this.onResizeObservable.notifyObservers(this);
  9094. }
  9095. };
  9096. // WebVR functions
  9097. Engine.prototype.isVRDevicePresent = function () {
  9098. return !!this._vrDisplay;
  9099. };
  9100. Engine.prototype.getVRDevice = function () {
  9101. return this._vrDisplay;
  9102. };
  9103. Engine.prototype.initWebVR = function () {
  9104. var _this = this;
  9105. var notifyObservers = function () {
  9106. var eventArgs = {
  9107. vrDisplay: _this._vrDisplay,
  9108. vrSupported: _this._vrSupported
  9109. };
  9110. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9111. };
  9112. if (!this._onVrDisplayConnect) {
  9113. this._onVrDisplayConnect = function (event) {
  9114. _this._vrDisplay = event.display;
  9115. notifyObservers();
  9116. };
  9117. this._onVrDisplayDisconnect = function () {
  9118. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9119. _this._vrDisplay = undefined;
  9120. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9121. notifyObservers();
  9122. };
  9123. this._onVrDisplayPresentChange = function () {
  9124. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9125. };
  9126. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9127. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9128. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9129. }
  9130. this._getVRDisplays(notifyObservers);
  9131. return this.onVRDisplayChangedObservable;
  9132. };
  9133. Engine.prototype.enableVR = function () {
  9134. var _this = this;
  9135. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9136. var onResolved = function () {
  9137. _this.onVRRequestPresentComplete.notifyObservers(true);
  9138. _this._onVRFullScreenTriggered();
  9139. };
  9140. var onRejected = function () {
  9141. _this.onVRRequestPresentComplete.notifyObservers(false);
  9142. };
  9143. this.onVRRequestPresentStart.notifyObservers(this);
  9144. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9145. }
  9146. };
  9147. Engine.prototype.disableVR = function () {
  9148. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9149. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9150. }
  9151. };
  9152. Engine.prototype._getVRDisplays = function (callback) {
  9153. var _this = this;
  9154. var getWebVRDevices = function (devices) {
  9155. _this._vrSupported = true;
  9156. // note that devices may actually be an empty array. This is fine;
  9157. // we expect this._vrDisplay to be undefined in this case.
  9158. return _this._vrDisplay = devices[0];
  9159. };
  9160. if (navigator.getVRDisplays) {
  9161. // TODO: Backwards compatible for 1.0?
  9162. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9163. // TODO: System CANNOT support WebVR, despite API presence.
  9164. _this._vrSupported = false;
  9165. callback();
  9166. });
  9167. }
  9168. else {
  9169. // TODO: Browser does not support WebVR
  9170. this._vrDisplay = undefined;
  9171. this._vrSupported = false;
  9172. callback();
  9173. }
  9174. };
  9175. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9176. if (this._currentRenderTarget) {
  9177. this.unBindFramebuffer(this._currentRenderTarget);
  9178. }
  9179. this._currentRenderTarget = texture;
  9180. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9181. var gl = this._gl;
  9182. if (texture.isCube) {
  9183. if (faceIndex === undefined) {
  9184. faceIndex = 0;
  9185. }
  9186. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9187. }
  9188. if (this._cachedViewport && !forceFullscreenViewport) {
  9189. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9190. }
  9191. else {
  9192. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9193. }
  9194. this.wipeCaches();
  9195. };
  9196. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9197. if (this._currentFramebuffer !== framebuffer) {
  9198. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9199. this._currentFramebuffer = framebuffer;
  9200. }
  9201. };
  9202. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9203. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9204. this._currentRenderTarget = null;
  9205. // If MSAA, we need to bitblt back to main texture
  9206. var gl = this._gl;
  9207. if (texture._MSAAFramebuffer) {
  9208. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9209. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9210. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9211. }
  9212. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9213. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9214. gl.generateMipmap(gl.TEXTURE_2D);
  9215. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9216. }
  9217. if (onBeforeUnbind) {
  9218. if (texture._MSAAFramebuffer) {
  9219. // Bind the correct framebuffer
  9220. this.bindUnboundFramebuffer(texture._framebuffer);
  9221. }
  9222. onBeforeUnbind();
  9223. }
  9224. this.bindUnboundFramebuffer(null);
  9225. };
  9226. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9227. if (texture.generateMipMaps) {
  9228. var gl = this._gl;
  9229. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9230. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9232. }
  9233. };
  9234. Engine.prototype.flushFramebuffer = function () {
  9235. this._gl.flush();
  9236. };
  9237. Engine.prototype.restoreDefaultFramebuffer = function () {
  9238. if (this._currentRenderTarget) {
  9239. this.unBindFramebuffer(this._currentRenderTarget);
  9240. }
  9241. else {
  9242. this.bindUnboundFramebuffer(null);
  9243. }
  9244. if (this._cachedViewport) {
  9245. this.setViewport(this._cachedViewport);
  9246. }
  9247. this.wipeCaches();
  9248. };
  9249. // UBOs
  9250. Engine.prototype.createUniformBuffer = function (elements) {
  9251. var ubo = this._gl.createBuffer();
  9252. if (!ubo) {
  9253. throw new Error("Unable to create uniform buffer");
  9254. }
  9255. this.bindUniformBuffer(ubo);
  9256. if (elements instanceof Float32Array) {
  9257. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9258. }
  9259. else {
  9260. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9261. }
  9262. this.bindUniformBuffer(null);
  9263. ubo.references = 1;
  9264. return ubo;
  9265. };
  9266. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9267. var ubo = this._gl.createBuffer();
  9268. if (!ubo) {
  9269. throw new Error("Unable to create dynamic uniform buffer");
  9270. }
  9271. this.bindUniformBuffer(ubo);
  9272. if (elements instanceof Float32Array) {
  9273. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9274. }
  9275. else {
  9276. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9277. }
  9278. this.bindUniformBuffer(null);
  9279. ubo.references = 1;
  9280. return ubo;
  9281. };
  9282. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9283. this.bindUniformBuffer(uniformBuffer);
  9284. if (offset === undefined) {
  9285. offset = 0;
  9286. }
  9287. if (count === undefined) {
  9288. if (elements instanceof Float32Array) {
  9289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9290. }
  9291. else {
  9292. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9293. }
  9294. }
  9295. else {
  9296. if (elements instanceof Float32Array) {
  9297. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9298. }
  9299. else {
  9300. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9301. }
  9302. }
  9303. this.bindUniformBuffer(null);
  9304. };
  9305. // VBOs
  9306. Engine.prototype._resetVertexBufferBinding = function () {
  9307. this.bindArrayBuffer(null);
  9308. this._cachedVertexBuffers = null;
  9309. };
  9310. Engine.prototype.createVertexBuffer = function (vertices) {
  9311. var vbo = this._gl.createBuffer();
  9312. if (!vbo) {
  9313. throw new Error("Unable to create vertex buffer");
  9314. }
  9315. this.bindArrayBuffer(vbo);
  9316. if (vertices instanceof Float32Array) {
  9317. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9318. }
  9319. else {
  9320. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9321. }
  9322. this._resetVertexBufferBinding();
  9323. vbo.references = 1;
  9324. return vbo;
  9325. };
  9326. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9327. var vbo = this._gl.createBuffer();
  9328. if (!vbo) {
  9329. throw new Error("Unable to create dynamic vertex buffer");
  9330. }
  9331. this.bindArrayBuffer(vbo);
  9332. if (vertices instanceof Float32Array) {
  9333. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9334. }
  9335. else {
  9336. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9337. }
  9338. this._resetVertexBufferBinding();
  9339. vbo.references = 1;
  9340. return vbo;
  9341. };
  9342. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9343. if (offset === void 0) { offset = 0; }
  9344. // Force cache update
  9345. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9346. this.bindIndexBuffer(indexBuffer);
  9347. var arrayBuffer;
  9348. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9349. arrayBuffer = indices;
  9350. }
  9351. else {
  9352. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9353. }
  9354. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9355. this._resetIndexBufferBinding();
  9356. };
  9357. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9358. this.bindArrayBuffer(vertexBuffer);
  9359. if (offset === undefined) {
  9360. offset = 0;
  9361. }
  9362. if (count === undefined) {
  9363. if (vertices instanceof Float32Array) {
  9364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9365. }
  9366. else {
  9367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9368. }
  9369. }
  9370. else {
  9371. if (vertices instanceof Float32Array) {
  9372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9373. }
  9374. else {
  9375. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9376. }
  9377. }
  9378. this._resetVertexBufferBinding();
  9379. };
  9380. Engine.prototype._resetIndexBufferBinding = function () {
  9381. this.bindIndexBuffer(null);
  9382. this._cachedIndexBuffer = null;
  9383. };
  9384. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9385. var vbo = this._gl.createBuffer();
  9386. if (!vbo) {
  9387. throw new Error("Unable to create index buffer");
  9388. }
  9389. this.bindIndexBuffer(vbo);
  9390. // Check for 32 bits indices
  9391. var arrayBuffer;
  9392. var need32Bits = false;
  9393. if (indices instanceof Uint16Array) {
  9394. arrayBuffer = indices;
  9395. }
  9396. else {
  9397. //check 32 bit support
  9398. if (this._caps.uintIndices) {
  9399. if (indices instanceof Uint32Array) {
  9400. arrayBuffer = indices;
  9401. need32Bits = true;
  9402. }
  9403. else {
  9404. //number[] or Int32Array, check if 32 bit is necessary
  9405. for (var index = 0; index < indices.length; index++) {
  9406. if (indices[index] > 65535) {
  9407. need32Bits = true;
  9408. break;
  9409. }
  9410. }
  9411. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9412. }
  9413. }
  9414. else {
  9415. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9416. arrayBuffer = new Uint16Array(indices);
  9417. }
  9418. }
  9419. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9420. this._resetIndexBufferBinding();
  9421. vbo.references = 1;
  9422. vbo.is32Bits = need32Bits;
  9423. return vbo;
  9424. };
  9425. Engine.prototype.bindArrayBuffer = function (buffer) {
  9426. if (!this._vaoRecordInProgress) {
  9427. this._unbindVertexArrayObject();
  9428. }
  9429. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9430. };
  9431. Engine.prototype.bindUniformBuffer = function (buffer) {
  9432. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9433. };
  9434. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9435. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9436. };
  9437. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9438. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9439. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9440. };
  9441. ;
  9442. Engine.prototype.bindIndexBuffer = function (buffer) {
  9443. if (!this._vaoRecordInProgress) {
  9444. this._unbindVertexArrayObject();
  9445. }
  9446. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9447. };
  9448. Engine.prototype.bindBuffer = function (buffer, target) {
  9449. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9450. this._gl.bindBuffer(target, buffer);
  9451. this._currentBoundBuffer[target] = buffer;
  9452. }
  9453. };
  9454. Engine.prototype.updateArrayBuffer = function (data) {
  9455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9456. };
  9457. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9458. var pointer = this._currentBufferPointers[indx];
  9459. var changed = false;
  9460. if (!pointer.active) {
  9461. changed = true;
  9462. pointer.active = true;
  9463. pointer.index = indx;
  9464. pointer.size = size;
  9465. pointer.type = type;
  9466. pointer.normalized = normalized;
  9467. pointer.stride = stride;
  9468. pointer.offset = offset;
  9469. pointer.buffer = buffer;
  9470. }
  9471. else {
  9472. if (pointer.buffer !== buffer) {
  9473. pointer.buffer = buffer;
  9474. changed = true;
  9475. }
  9476. if (pointer.size !== size) {
  9477. pointer.size = size;
  9478. changed = true;
  9479. }
  9480. if (pointer.type !== type) {
  9481. pointer.type = type;
  9482. changed = true;
  9483. }
  9484. if (pointer.normalized !== normalized) {
  9485. pointer.normalized = normalized;
  9486. changed = true;
  9487. }
  9488. if (pointer.stride !== stride) {
  9489. pointer.stride = stride;
  9490. changed = true;
  9491. }
  9492. if (pointer.offset !== offset) {
  9493. pointer.offset = offset;
  9494. changed = true;
  9495. }
  9496. }
  9497. if (changed || this._vaoRecordInProgress) {
  9498. this.bindArrayBuffer(buffer);
  9499. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9500. }
  9501. };
  9502. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9503. if (indexBuffer == null) {
  9504. return;
  9505. }
  9506. if (this._cachedIndexBuffer !== indexBuffer) {
  9507. this._cachedIndexBuffer = indexBuffer;
  9508. this.bindIndexBuffer(indexBuffer);
  9509. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9510. }
  9511. };
  9512. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9513. var attributes = effect.getAttributesNames();
  9514. if (!this._vaoRecordInProgress) {
  9515. this._unbindVertexArrayObject();
  9516. }
  9517. this.unbindAllAttributes();
  9518. for (var index = 0; index < attributes.length; index++) {
  9519. var order = effect.getAttributeLocation(index);
  9520. if (order >= 0) {
  9521. var vertexBuffer = vertexBuffers[attributes[index]];
  9522. if (!vertexBuffer) {
  9523. continue;
  9524. }
  9525. this._gl.enableVertexAttribArray(order);
  9526. if (!this._vaoRecordInProgress) {
  9527. this._vertexAttribArraysEnabled[order] = true;
  9528. }
  9529. var buffer = vertexBuffer.getBuffer();
  9530. if (buffer) {
  9531. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9532. if (vertexBuffer.getIsInstanced()) {
  9533. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9534. if (!this._vaoRecordInProgress) {
  9535. this._currentInstanceLocations.push(order);
  9536. this._currentInstanceBuffers.push(buffer);
  9537. }
  9538. }
  9539. }
  9540. }
  9541. }
  9542. };
  9543. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9544. var vao = this._gl.createVertexArray();
  9545. this._vaoRecordInProgress = true;
  9546. this._gl.bindVertexArray(vao);
  9547. this._mustWipeVertexAttributes = true;
  9548. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9549. this.bindIndexBuffer(indexBuffer);
  9550. this._vaoRecordInProgress = false;
  9551. this._gl.bindVertexArray(null);
  9552. return vao;
  9553. };
  9554. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9555. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9556. this._cachedVertexArrayObject = vertexArrayObject;
  9557. this._gl.bindVertexArray(vertexArrayObject);
  9558. this._cachedVertexBuffers = null;
  9559. this._cachedIndexBuffer = null;
  9560. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9561. this._mustWipeVertexAttributes = true;
  9562. }
  9563. };
  9564. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9565. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9566. this._cachedVertexBuffers = vertexBuffer;
  9567. this._cachedEffectForVertexBuffers = effect;
  9568. var attributesCount = effect.getAttributesCount();
  9569. this._unbindVertexArrayObject();
  9570. this.unbindAllAttributes();
  9571. var offset = 0;
  9572. for (var index = 0; index < attributesCount; index++) {
  9573. if (index < vertexDeclaration.length) {
  9574. var order = effect.getAttributeLocation(index);
  9575. if (order >= 0) {
  9576. this._gl.enableVertexAttribArray(order);
  9577. this._vertexAttribArraysEnabled[order] = true;
  9578. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9579. }
  9580. offset += vertexDeclaration[index] * 4;
  9581. }
  9582. }
  9583. }
  9584. this._bindIndexBufferWithCache(indexBuffer);
  9585. };
  9586. Engine.prototype._unbindVertexArrayObject = function () {
  9587. if (!this._cachedVertexArrayObject) {
  9588. return;
  9589. }
  9590. this._cachedVertexArrayObject = null;
  9591. this._gl.bindVertexArray(null);
  9592. };
  9593. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9594. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9595. this._cachedVertexBuffers = vertexBuffers;
  9596. this._cachedEffectForVertexBuffers = effect;
  9597. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9598. }
  9599. this._bindIndexBufferWithCache(indexBuffer);
  9600. };
  9601. Engine.prototype.unbindInstanceAttributes = function () {
  9602. var boundBuffer;
  9603. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9604. var instancesBuffer = this._currentInstanceBuffers[i];
  9605. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9606. boundBuffer = instancesBuffer;
  9607. this.bindArrayBuffer(instancesBuffer);
  9608. }
  9609. var offsetLocation = this._currentInstanceLocations[i];
  9610. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9611. }
  9612. this._currentInstanceBuffers.length = 0;
  9613. this._currentInstanceLocations.length = 0;
  9614. };
  9615. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9616. this._gl.deleteVertexArray(vao);
  9617. };
  9618. Engine.prototype._releaseBuffer = function (buffer) {
  9619. buffer.references--;
  9620. if (buffer.references === 0) {
  9621. this._gl.deleteBuffer(buffer);
  9622. return true;
  9623. }
  9624. return false;
  9625. };
  9626. Engine.prototype.createInstancesBuffer = function (capacity) {
  9627. var buffer = this._gl.createBuffer();
  9628. if (!buffer) {
  9629. throw new Error("Unable to create instance buffer");
  9630. }
  9631. buffer.capacity = capacity;
  9632. this.bindArrayBuffer(buffer);
  9633. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9634. return buffer;
  9635. };
  9636. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9637. this._gl.deleteBuffer(buffer);
  9638. };
  9639. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9640. this.bindArrayBuffer(instancesBuffer);
  9641. if (data) {
  9642. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9643. }
  9644. if (offsetLocations[0].index !== undefined) {
  9645. var stride = 0;
  9646. for (var i = 0; i < offsetLocations.length; i++) {
  9647. var ai = offsetLocations[i];
  9648. stride += ai.attributeSize * 4;
  9649. }
  9650. for (var i = 0; i < offsetLocations.length; i++) {
  9651. var ai = offsetLocations[i];
  9652. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9653. this._gl.enableVertexAttribArray(ai.index);
  9654. this._vertexAttribArraysEnabled[ai.index] = true;
  9655. }
  9656. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9657. this._gl.vertexAttribDivisor(ai.index, 1);
  9658. this._currentInstanceLocations.push(ai.index);
  9659. this._currentInstanceBuffers.push(instancesBuffer);
  9660. }
  9661. }
  9662. else {
  9663. for (var index = 0; index < 4; index++) {
  9664. var offsetLocation = offsetLocations[index];
  9665. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9666. this._gl.enableVertexAttribArray(offsetLocation);
  9667. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9668. }
  9669. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9670. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9671. this._currentInstanceLocations.push(offsetLocation);
  9672. this._currentInstanceBuffers.push(instancesBuffer);
  9673. }
  9674. }
  9675. };
  9676. Engine.prototype.applyStates = function () {
  9677. this._depthCullingState.apply(this._gl);
  9678. this._stencilState.apply(this._gl);
  9679. this._alphaState.apply(this._gl);
  9680. };
  9681. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9682. // Apply states
  9683. this.applyStates();
  9684. this._drawCalls.addCount(1, false);
  9685. // Render
  9686. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9687. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9688. if (instancesCount) {
  9689. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9690. return;
  9691. }
  9692. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9693. };
  9694. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9695. // Apply states
  9696. this.applyStates();
  9697. this._drawCalls.addCount(1, false);
  9698. if (instancesCount) {
  9699. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9700. return;
  9701. }
  9702. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9703. };
  9704. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9705. // Apply states
  9706. this.applyStates();
  9707. this._drawCalls.addCount(1, false);
  9708. if (instancesCount) {
  9709. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9710. return;
  9711. }
  9712. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9713. };
  9714. // Shaders
  9715. Engine.prototype._releaseEffect = function (effect) {
  9716. if (this._compiledEffects[effect._key]) {
  9717. delete this._compiledEffects[effect._key];
  9718. this._deleteProgram(effect.getProgram());
  9719. }
  9720. };
  9721. Engine.prototype._deleteProgram = function (program) {
  9722. if (program) {
  9723. program.__SPECTOR_rebuildProgram = null;
  9724. this._gl.deleteProgram(program);
  9725. }
  9726. };
  9727. /**
  9728. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9729. * @param samplers An array of string used to represent textures
  9730. */
  9731. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9732. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9733. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9734. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9735. if (this._compiledEffects[name]) {
  9736. var compiledEffect = this._compiledEffects[name];
  9737. if (onCompiled && compiledEffect.isReady()) {
  9738. onCompiled(compiledEffect);
  9739. }
  9740. return compiledEffect;
  9741. }
  9742. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9743. effect._key = name;
  9744. this._compiledEffects[name] = effect;
  9745. return effect;
  9746. };
  9747. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9748. if (uniformsNames === void 0) { uniformsNames = []; }
  9749. if (samplers === void 0) { samplers = []; }
  9750. if (defines === void 0) { defines = ""; }
  9751. return this.createEffect({
  9752. vertex: "particles",
  9753. fragmentElement: fragmentName
  9754. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9755. };
  9756. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9757. context = context || this._gl;
  9758. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9759. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9760. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9761. };
  9762. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9763. context = context || this._gl;
  9764. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9765. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9766. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9767. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9768. var program = this._createShaderProgram(vertexShader, fragmentShader, context);
  9769. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9770. return program;
  9771. };
  9772. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9773. var shaderProgram = context.createProgram();
  9774. if (!shaderProgram) {
  9775. throw new Error("Unable to create program");
  9776. }
  9777. context.attachShader(shaderProgram, vertexShader);
  9778. context.attachShader(shaderProgram, fragmentShader);
  9779. context.linkProgram(shaderProgram);
  9780. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9781. if (!linked) {
  9782. context.validateProgram(shaderProgram);
  9783. var error = context.getProgramInfoLog(shaderProgram);
  9784. if (error) {
  9785. throw new Error(error);
  9786. }
  9787. }
  9788. context.deleteShader(vertexShader);
  9789. context.deleteShader(fragmentShader);
  9790. return shaderProgram;
  9791. };
  9792. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9793. var results = new Array();
  9794. for (var index = 0; index < uniformsNames.length; index++) {
  9795. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9796. }
  9797. return results;
  9798. };
  9799. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9800. var results = [];
  9801. for (var index = 0; index < attributesNames.length; index++) {
  9802. try {
  9803. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9804. }
  9805. catch (e) {
  9806. results.push(-1);
  9807. }
  9808. }
  9809. return results;
  9810. };
  9811. Engine.prototype.enableEffect = function (effect) {
  9812. if (!effect) {
  9813. return;
  9814. }
  9815. // Use program
  9816. this.setProgram(effect.getProgram());
  9817. this._currentEffect = effect;
  9818. if (effect.onBind) {
  9819. effect.onBind(effect);
  9820. }
  9821. effect.onBindObservable.notifyObservers(effect);
  9822. };
  9823. Engine.prototype.setIntArray = function (uniform, array) {
  9824. if (!uniform)
  9825. return;
  9826. this._gl.uniform1iv(uniform, array);
  9827. };
  9828. Engine.prototype.setIntArray2 = function (uniform, array) {
  9829. if (!uniform || array.length % 2 !== 0)
  9830. return;
  9831. this._gl.uniform2iv(uniform, array);
  9832. };
  9833. Engine.prototype.setIntArray3 = function (uniform, array) {
  9834. if (!uniform || array.length % 3 !== 0)
  9835. return;
  9836. this._gl.uniform3iv(uniform, array);
  9837. };
  9838. Engine.prototype.setIntArray4 = function (uniform, array) {
  9839. if (!uniform || array.length % 4 !== 0)
  9840. return;
  9841. this._gl.uniform4iv(uniform, array);
  9842. };
  9843. Engine.prototype.setFloatArray = function (uniform, array) {
  9844. if (!uniform)
  9845. return;
  9846. this._gl.uniform1fv(uniform, array);
  9847. };
  9848. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9849. if (!uniform || array.length % 2 !== 0)
  9850. return;
  9851. this._gl.uniform2fv(uniform, array);
  9852. };
  9853. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9854. if (!uniform || array.length % 3 !== 0)
  9855. return;
  9856. this._gl.uniform3fv(uniform, array);
  9857. };
  9858. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9859. if (!uniform || array.length % 4 !== 0)
  9860. return;
  9861. this._gl.uniform4fv(uniform, array);
  9862. };
  9863. Engine.prototype.setArray = function (uniform, array) {
  9864. if (!uniform)
  9865. return;
  9866. this._gl.uniform1fv(uniform, array);
  9867. };
  9868. Engine.prototype.setArray2 = function (uniform, array) {
  9869. if (!uniform || array.length % 2 !== 0)
  9870. return;
  9871. this._gl.uniform2fv(uniform, array);
  9872. };
  9873. Engine.prototype.setArray3 = function (uniform, array) {
  9874. if (!uniform || array.length % 3 !== 0)
  9875. return;
  9876. this._gl.uniform3fv(uniform, array);
  9877. };
  9878. Engine.prototype.setArray4 = function (uniform, array) {
  9879. if (!uniform || array.length % 4 !== 0)
  9880. return;
  9881. this._gl.uniform4fv(uniform, array);
  9882. };
  9883. Engine.prototype.setMatrices = function (uniform, matrices) {
  9884. if (!uniform)
  9885. return;
  9886. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9887. };
  9888. Engine.prototype.setMatrix = function (uniform, matrix) {
  9889. if (!uniform)
  9890. return;
  9891. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9892. };
  9893. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9894. if (!uniform)
  9895. return;
  9896. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9897. };
  9898. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9899. if (!uniform)
  9900. return;
  9901. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9902. };
  9903. Engine.prototype.setFloat = function (uniform, value) {
  9904. if (!uniform)
  9905. return;
  9906. this._gl.uniform1f(uniform, value);
  9907. };
  9908. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9909. if (!uniform)
  9910. return;
  9911. this._gl.uniform2f(uniform, x, y);
  9912. };
  9913. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9914. if (!uniform)
  9915. return;
  9916. this._gl.uniform3f(uniform, x, y, z);
  9917. };
  9918. Engine.prototype.setBool = function (uniform, bool) {
  9919. if (!uniform)
  9920. return;
  9921. this._gl.uniform1i(uniform, bool);
  9922. };
  9923. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9924. if (!uniform)
  9925. return;
  9926. this._gl.uniform4f(uniform, x, y, z, w);
  9927. };
  9928. Engine.prototype.setColor3 = function (uniform, color3) {
  9929. if (!uniform)
  9930. return;
  9931. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9932. };
  9933. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9934. if (!uniform)
  9935. return;
  9936. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9937. };
  9938. // States
  9939. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9940. if (zOffset === void 0) { zOffset = 0; }
  9941. if (reverseSide === void 0) { reverseSide = false; }
  9942. // Culling
  9943. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9944. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9945. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9946. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9947. if (culling) {
  9948. this._depthCullingState.cullFace = cullFace;
  9949. this._depthCullingState.cull = true;
  9950. }
  9951. else {
  9952. this._depthCullingState.cull = false;
  9953. }
  9954. }
  9955. // Z offset
  9956. this.setZOffset(zOffset);
  9957. };
  9958. Engine.prototype.setZOffset = function (value) {
  9959. this._depthCullingState.zOffset = value;
  9960. };
  9961. Engine.prototype.getZOffset = function () {
  9962. return this._depthCullingState.zOffset;
  9963. };
  9964. Engine.prototype.setDepthBuffer = function (enable) {
  9965. this._depthCullingState.depthTest = enable;
  9966. };
  9967. Engine.prototype.getDepthWrite = function () {
  9968. return this._depthCullingState.depthMask;
  9969. };
  9970. Engine.prototype.setDepthWrite = function (enable) {
  9971. this._depthCullingState.depthMask = enable;
  9972. };
  9973. Engine.prototype.setColorWrite = function (enable) {
  9974. this._gl.colorMask(enable, enable, enable, enable);
  9975. this._colorWrite = enable;
  9976. };
  9977. Engine.prototype.getColorWrite = function () {
  9978. return this._colorWrite;
  9979. };
  9980. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9981. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9982. };
  9983. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9984. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9985. if (this._alphaMode === mode) {
  9986. return;
  9987. }
  9988. switch (mode) {
  9989. case Engine.ALPHA_DISABLE:
  9990. this._alphaState.alphaBlend = false;
  9991. break;
  9992. case Engine.ALPHA_PREMULTIPLIED:
  9993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9994. this._alphaState.alphaBlend = true;
  9995. break;
  9996. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9998. this._alphaState.alphaBlend = true;
  9999. break;
  10000. case Engine.ALPHA_COMBINE:
  10001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10002. this._alphaState.alphaBlend = true;
  10003. break;
  10004. case Engine.ALPHA_ONEONE:
  10005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10006. this._alphaState.alphaBlend = true;
  10007. break;
  10008. case Engine.ALPHA_ADD:
  10009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10010. this._alphaState.alphaBlend = true;
  10011. break;
  10012. case Engine.ALPHA_SUBTRACT:
  10013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10014. this._alphaState.alphaBlend = true;
  10015. break;
  10016. case Engine.ALPHA_MULTIPLY:
  10017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10018. this._alphaState.alphaBlend = true;
  10019. break;
  10020. case Engine.ALPHA_MAXIMIZED:
  10021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10022. this._alphaState.alphaBlend = true;
  10023. break;
  10024. case Engine.ALPHA_INTERPOLATE:
  10025. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10026. this._alphaState.alphaBlend = true;
  10027. break;
  10028. case Engine.ALPHA_SCREENMODE:
  10029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10030. this._alphaState.alphaBlend = true;
  10031. break;
  10032. }
  10033. if (!noDepthWriteChange) {
  10034. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10035. }
  10036. this._alphaMode = mode;
  10037. };
  10038. Engine.prototype.getAlphaMode = function () {
  10039. return this._alphaMode;
  10040. };
  10041. Engine.prototype.setAlphaTesting = function (enable) {
  10042. this._alphaTest = enable;
  10043. };
  10044. Engine.prototype.getAlphaTesting = function () {
  10045. return !!this._alphaTest;
  10046. };
  10047. // Textures
  10048. Engine.prototype.wipeCaches = function (bruteForce) {
  10049. if (this.preventCacheWipeBetweenFrames) {
  10050. return;
  10051. }
  10052. this.resetTextureCache();
  10053. this._currentEffect = null;
  10054. // 6/8/2017: deltakosh: Should not be required anymore.
  10055. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10056. if (bruteForce) {
  10057. this._currentProgram = null;
  10058. this._stencilState.reset();
  10059. this._depthCullingState.reset();
  10060. this.setDepthFunctionToLessOrEqual();
  10061. this._alphaState.reset();
  10062. }
  10063. this._cachedVertexBuffers = null;
  10064. this._cachedIndexBuffer = null;
  10065. this._cachedEffectForVertexBuffers = null;
  10066. this._unbindVertexArrayObject();
  10067. this.bindIndexBuffer(null);
  10068. this.bindArrayBuffer(null);
  10069. };
  10070. /**
  10071. * Set the compressed texture format to use, based on the formats you have, and the formats
  10072. * supported by the hardware / browser.
  10073. *
  10074. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10075. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10076. * to API arguments needed to compressed textures. This puts the burden on the container
  10077. * generator to house the arcane code for determining these for current & future formats.
  10078. *
  10079. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10080. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10081. *
  10082. * Note: The result of this call is not taken into account when a texture is base64.
  10083. *
  10084. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10085. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10086. *
  10087. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10088. * @returns The extension selected.
  10089. */
  10090. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10091. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10092. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10093. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10094. return this._textureFormatInUse = this._texturesSupported[i];
  10095. }
  10096. }
  10097. }
  10098. // actively set format to nothing, to allow this to be called more than once
  10099. // and possibly fail the 2nd time
  10100. this._textureFormatInUse = null;
  10101. return null;
  10102. };
  10103. Engine.prototype._createTexture = function () {
  10104. var texture = this._gl.createTexture();
  10105. if (!texture) {
  10106. throw new Error("Unable to create texture");
  10107. }
  10108. return texture;
  10109. };
  10110. /**
  10111. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10112. * @param {string} urlArg- This contains one of the following:
  10113. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10114. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10115. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10116. *
  10117. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10118. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10119. * @param {Scene} scene- Needed for loading to the correct scene.
  10120. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10121. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10122. * @param {callback} onError- Optional callback to be called upon failure.
  10123. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10124. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10125. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10126. *
  10127. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10128. */
  10129. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10130. var _this = this;
  10131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10132. if (onLoad === void 0) { onLoad = null; }
  10133. if (onError === void 0) { onError = null; }
  10134. if (buffer === void 0) { buffer = null; }
  10135. if (fallBack === void 0) { fallBack = null; }
  10136. if (format === void 0) { format = null; }
  10137. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10138. var fromData = url.substr(0, 5) === "data:";
  10139. var fromBlob = url.substr(0, 5) === "blob:";
  10140. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10141. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10142. // establish the file extension, if possible
  10143. var lastDot = url.lastIndexOf('.');
  10144. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10145. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10146. var isTGA = (extension === ".tga");
  10147. // determine if a ktx file should be substituted
  10148. var isKTX = false;
  10149. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10150. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10151. isKTX = true;
  10152. }
  10153. if (scene) {
  10154. scene._addPendingData(texture);
  10155. }
  10156. texture.url = url;
  10157. texture.generateMipMaps = !noMipmap;
  10158. texture.samplingMode = samplingMode;
  10159. texture.invertY = invertY;
  10160. if (!this._doNotHandleContextLost) {
  10161. // Keep a link to the buffer only if we plan to handle context lost
  10162. texture._buffer = buffer;
  10163. }
  10164. if (onLoad) {
  10165. texture.onLoadedObservable.add(onLoad);
  10166. }
  10167. if (!fallBack)
  10168. this._internalTexturesCache.push(texture);
  10169. var onerror = function () {
  10170. if (scene) {
  10171. scene._removePendingData(texture);
  10172. }
  10173. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10174. if (isKTX) {
  10175. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10176. }
  10177. else if (onError) {
  10178. onError();
  10179. }
  10180. };
  10181. var callback = null;
  10182. // processing for non-image formats
  10183. if (isKTX || isTGA || isDDS) {
  10184. if (isKTX) {
  10185. callback = function (data) {
  10186. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10187. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10188. ktx.uploadLevels(_this._gl, !noMipmap);
  10189. return false;
  10190. }, samplingMode);
  10191. };
  10192. }
  10193. else if (isTGA) {
  10194. callback = function (arrayBuffer) {
  10195. var data = new Uint8Array(arrayBuffer);
  10196. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10197. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10198. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10199. return false;
  10200. }, samplingMode);
  10201. };
  10202. }
  10203. else if (isDDS) {
  10204. callback = function (data) {
  10205. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10206. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10207. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10208. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10209. return false;
  10210. }, samplingMode);
  10211. };
  10212. }
  10213. if (!buffer) {
  10214. BABYLON.Tools.LoadFile(url, function (data) {
  10215. if (callback) {
  10216. callback(data);
  10217. }
  10218. }, undefined, scene ? scene.database : undefined, true, onerror);
  10219. }
  10220. else {
  10221. if (callback) {
  10222. callback(buffer);
  10223. }
  10224. }
  10225. // image format processing
  10226. }
  10227. else {
  10228. var onload = function (img) {
  10229. if (fromBlob && !_this._doNotHandleContextLost) {
  10230. // We need to store the image if we need to rebuild the texture
  10231. // in case of a webgl context lost
  10232. texture._buffer = img;
  10233. }
  10234. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10235. var gl = _this._gl;
  10236. var isPot = (img.width === potWidth && img.height === potHeight);
  10237. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10238. if (isPot) {
  10239. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10240. return false;
  10241. }
  10242. // Using shaders to rescale because canvas.drawImage is lossy
  10243. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10244. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10245. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10250. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10251. _this._releaseTexture(source);
  10252. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10253. continuationCallback();
  10254. });
  10255. return true;
  10256. }, samplingMode);
  10257. };
  10258. if (!fromData || isBase64)
  10259. if (buffer instanceof HTMLImageElement) {
  10260. onload(buffer);
  10261. }
  10262. else {
  10263. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10264. }
  10265. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10266. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10267. else
  10268. onload(buffer);
  10269. }
  10270. return texture;
  10271. };
  10272. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10273. var _this = this;
  10274. var rtt = this.createRenderTargetTexture({
  10275. width: destination.width,
  10276. height: destination.height,
  10277. }, {
  10278. generateMipMaps: false,
  10279. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10280. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10281. generateDepthBuffer: false,
  10282. generateStencilBuffer: false
  10283. });
  10284. if (!this._rescalePostProcess) {
  10285. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10286. }
  10287. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10288. _this._rescalePostProcess.onApply = function (effect) {
  10289. effect._bindTexture("textureSampler", source);
  10290. };
  10291. var hostingScene = scene;
  10292. if (!hostingScene) {
  10293. hostingScene = _this.scenes[_this.scenes.length - 1];
  10294. }
  10295. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10296. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10297. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10298. _this.unBindFramebuffer(rtt);
  10299. _this._releaseTexture(rtt);
  10300. if (onComplete) {
  10301. onComplete();
  10302. }
  10303. });
  10304. };
  10305. Engine.prototype._getInternalFormat = function (format) {
  10306. var internalFormat = this._gl.RGBA;
  10307. switch (format) {
  10308. case Engine.TEXTUREFORMAT_ALPHA:
  10309. internalFormat = this._gl.ALPHA;
  10310. break;
  10311. case Engine.TEXTUREFORMAT_LUMINANCE:
  10312. internalFormat = this._gl.LUMINANCE;
  10313. break;
  10314. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10315. internalFormat = this._gl.LUMINANCE_ALPHA;
  10316. break;
  10317. case Engine.TEXTUREFORMAT_RGB:
  10318. internalFormat = this._gl.RGB;
  10319. break;
  10320. case Engine.TEXTUREFORMAT_RGBA:
  10321. internalFormat = this._gl.RGBA;
  10322. break;
  10323. }
  10324. return internalFormat;
  10325. };
  10326. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10327. if (compression === void 0) { compression = null; }
  10328. if (!texture) {
  10329. return;
  10330. }
  10331. var internalFormat = this._getInternalFormat(format);
  10332. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10333. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10334. if (!this._doNotHandleContextLost) {
  10335. texture._bufferView = data;
  10336. texture.format = format;
  10337. texture.invertY = invertY;
  10338. texture._compression = compression;
  10339. }
  10340. if (texture.width % 4 !== 0) {
  10341. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10342. }
  10343. if (compression && data) {
  10344. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10345. }
  10346. else {
  10347. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10348. }
  10349. if (texture.generateMipMaps) {
  10350. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10351. }
  10352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10353. this.resetTextureCache();
  10354. texture.isReady = true;
  10355. };
  10356. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10357. if (compression === void 0) { compression = null; }
  10358. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10359. texture.baseWidth = width;
  10360. texture.baseHeight = height;
  10361. texture.width = width;
  10362. texture.height = height;
  10363. texture.format = format;
  10364. texture.generateMipMaps = generateMipMaps;
  10365. texture.samplingMode = samplingMode;
  10366. texture.invertY = invertY;
  10367. texture._compression = compression;
  10368. if (!this._doNotHandleContextLost) {
  10369. texture._bufferView = data;
  10370. }
  10371. this.updateRawTexture(texture, data, format, invertY, compression);
  10372. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10373. // Filters
  10374. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10375. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10376. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10377. if (generateMipMaps) {
  10378. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10379. }
  10380. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10381. this._internalTexturesCache.push(texture);
  10382. return texture;
  10383. };
  10384. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10385. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10386. texture.baseWidth = width;
  10387. texture.baseHeight = height;
  10388. if (generateMipMaps) {
  10389. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10390. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10391. }
  10392. this.resetTextureCache();
  10393. texture.width = width;
  10394. texture.height = height;
  10395. texture.isReady = false;
  10396. texture.generateMipMaps = generateMipMaps;
  10397. texture.samplingMode = samplingMode;
  10398. this.updateTextureSamplingMode(samplingMode, texture);
  10399. this._internalTexturesCache.push(texture);
  10400. return texture;
  10401. };
  10402. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10403. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10404. if (texture.isCube) {
  10405. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10406. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10407. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10408. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10409. }
  10410. else if (texture.is3D) {
  10411. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10412. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10413. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10414. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10415. }
  10416. else {
  10417. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10418. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10420. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10421. }
  10422. texture.samplingMode = samplingMode;
  10423. };
  10424. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10425. if (premulAlpha === void 0) { premulAlpha = false; }
  10426. if (!texture) {
  10427. return;
  10428. }
  10429. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10431. if (premulAlpha) {
  10432. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10433. }
  10434. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10435. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10436. if (texture.generateMipMaps) {
  10437. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10438. }
  10439. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10440. if (premulAlpha) {
  10441. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10442. }
  10443. this.resetTextureCache();
  10444. texture.isReady = true;
  10445. };
  10446. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10447. if (!texture || texture._isDisabled) {
  10448. return;
  10449. }
  10450. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10451. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10452. try {
  10453. // Testing video texture support
  10454. if (this._videoTextureSupported === undefined) {
  10455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10456. if (this._gl.getError() !== 0) {
  10457. this._videoTextureSupported = false;
  10458. }
  10459. else {
  10460. this._videoTextureSupported = true;
  10461. }
  10462. }
  10463. // Copy video through the current working canvas if video texture is not supported
  10464. if (!this._videoTextureSupported) {
  10465. if (!texture._workingCanvas) {
  10466. texture._workingCanvas = document.createElement("canvas");
  10467. var context = texture._workingCanvas.getContext("2d");
  10468. if (!context) {
  10469. throw new Error("Unable to get 2d context");
  10470. }
  10471. texture._workingContext = context;
  10472. texture._workingCanvas.width = texture.width;
  10473. texture._workingCanvas.height = texture.height;
  10474. }
  10475. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10476. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10477. }
  10478. else {
  10479. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10480. }
  10481. if (texture.generateMipMaps) {
  10482. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10483. }
  10484. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10485. this.resetTextureCache();
  10486. texture.isReady = true;
  10487. }
  10488. catch (ex) {
  10489. // Something unexpected
  10490. // Let's disable the texture
  10491. texture._isDisabled = true;
  10492. }
  10493. };
  10494. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10495. var fullOptions = new RenderTargetCreationOptions();
  10496. if (options !== undefined && typeof options === "object") {
  10497. fullOptions.generateMipMaps = options.generateMipMaps;
  10498. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10499. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10500. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10501. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10502. }
  10503. else {
  10504. fullOptions.generateMipMaps = options;
  10505. fullOptions.generateDepthBuffer = true;
  10506. fullOptions.generateStencilBuffer = false;
  10507. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10508. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10509. }
  10510. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10511. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10512. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10513. }
  10514. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10515. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10516. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10517. }
  10518. var gl = this._gl;
  10519. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10520. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10521. var width = size.width || size;
  10522. var height = size.height || size;
  10523. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10524. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10525. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10526. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10527. }
  10528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10532. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10533. // Create the framebuffer
  10534. var framebuffer = gl.createFramebuffer();
  10535. this.bindUnboundFramebuffer(framebuffer);
  10536. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10537. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10538. if (fullOptions.generateMipMaps) {
  10539. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10540. }
  10541. // Unbind
  10542. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10543. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10544. this.bindUnboundFramebuffer(null);
  10545. texture._framebuffer = framebuffer;
  10546. texture.baseWidth = width;
  10547. texture.baseHeight = height;
  10548. texture.width = width;
  10549. texture.height = height;
  10550. texture.isReady = true;
  10551. texture.samples = 1;
  10552. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10553. texture.samplingMode = fullOptions.samplingMode;
  10554. texture.type = fullOptions.type;
  10555. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10556. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10557. this.resetTextureCache();
  10558. this._internalTexturesCache.push(texture);
  10559. return texture;
  10560. };
  10561. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10562. var generateMipMaps = false;
  10563. var generateDepthBuffer = true;
  10564. var generateStencilBuffer = false;
  10565. var generateDepthTexture = false;
  10566. var textureCount = 1;
  10567. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10568. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10569. var types = [], samplingModes = [];
  10570. if (options !== undefined) {
  10571. generateMipMaps = options.generateMipMaps;
  10572. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10573. generateStencilBuffer = options.generateStencilBuffer;
  10574. generateDepthTexture = options.generateDepthTexture;
  10575. textureCount = options.textureCount || 1;
  10576. if (options.types) {
  10577. types = options.types;
  10578. }
  10579. if (options.samplingModes) {
  10580. samplingModes = options.samplingModes;
  10581. }
  10582. }
  10583. var gl = this._gl;
  10584. // Create the framebuffer
  10585. var framebuffer = gl.createFramebuffer();
  10586. this.bindUnboundFramebuffer(framebuffer);
  10587. var width = size.width || size;
  10588. var height = size.height || size;
  10589. var textures = [];
  10590. var attachments = [];
  10591. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10592. for (var i = 0; i < textureCount; i++) {
  10593. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10594. var type = types[i] || defaultType;
  10595. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10596. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10597. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10598. }
  10599. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10600. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10601. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10602. }
  10603. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10604. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10605. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10606. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10607. }
  10608. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10609. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10610. textures.push(texture);
  10611. attachments.push(attachment);
  10612. gl.activeTexture(gl["TEXTURE" + i]);
  10613. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10614. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10615. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10616. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10617. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10618. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10619. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10620. if (generateMipMaps) {
  10621. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10622. }
  10623. // Unbind
  10624. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10625. texture._framebuffer = framebuffer;
  10626. texture._depthStencilBuffer = depthStencilBuffer;
  10627. texture.baseWidth = width;
  10628. texture.baseHeight = height;
  10629. texture.width = width;
  10630. texture.height = height;
  10631. texture.isReady = true;
  10632. texture.samples = 1;
  10633. texture.generateMipMaps = generateMipMaps;
  10634. texture.samplingMode = samplingMode;
  10635. texture.type = type;
  10636. texture._generateDepthBuffer = generateDepthBuffer;
  10637. texture._generateStencilBuffer = generateStencilBuffer;
  10638. this._internalTexturesCache.push(texture);
  10639. }
  10640. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10641. // Depth texture
  10642. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10643. gl.activeTexture(gl.TEXTURE0);
  10644. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10649. 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);
  10650. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10651. depthTexture._framebuffer = framebuffer;
  10652. depthTexture.baseWidth = width;
  10653. depthTexture.baseHeight = height;
  10654. depthTexture.width = width;
  10655. depthTexture.height = height;
  10656. depthTexture.isReady = true;
  10657. depthTexture.samples = 1;
  10658. depthTexture.generateMipMaps = generateMipMaps;
  10659. depthTexture.samplingMode = gl.NEAREST;
  10660. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10661. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10662. textures.push(depthTexture);
  10663. this._internalTexturesCache.push(depthTexture);
  10664. }
  10665. gl.drawBuffers(attachments);
  10666. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10667. this.bindUnboundFramebuffer(null);
  10668. this.resetTextureCache();
  10669. return textures;
  10670. };
  10671. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10672. if (samples === void 0) { samples = 1; }
  10673. var depthStencilBuffer = null;
  10674. var gl = this._gl;
  10675. // Create the depth/stencil buffer
  10676. if (generateStencilBuffer) {
  10677. depthStencilBuffer = gl.createRenderbuffer();
  10678. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10679. if (samples > 1) {
  10680. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10681. }
  10682. else {
  10683. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10684. }
  10685. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10686. }
  10687. else if (generateDepthBuffer) {
  10688. depthStencilBuffer = gl.createRenderbuffer();
  10689. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10690. if (samples > 1) {
  10691. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10692. }
  10693. else {
  10694. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10695. }
  10696. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10697. }
  10698. return depthStencilBuffer;
  10699. };
  10700. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10701. if (this.webGLVersion < 2 || !texture) {
  10702. return 1;
  10703. }
  10704. if (texture.samples === samples) {
  10705. return samples;
  10706. }
  10707. var gl = this._gl;
  10708. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10709. // Dispose previous render buffers
  10710. if (texture._depthStencilBuffer) {
  10711. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10712. }
  10713. if (texture._MSAAFramebuffer) {
  10714. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10715. }
  10716. if (texture._MSAARenderBuffer) {
  10717. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10718. }
  10719. if (samples > 1) {
  10720. var framebuffer = gl.createFramebuffer();
  10721. if (!framebuffer) {
  10722. throw new Error("Unable to create multi sampled framebuffer");
  10723. }
  10724. texture._MSAAFramebuffer = framebuffer;
  10725. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10726. var colorRenderbuffer = gl.createRenderbuffer();
  10727. if (!colorRenderbuffer) {
  10728. throw new Error("Unable to create multi sampled framebuffer");
  10729. }
  10730. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10731. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10732. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10733. texture._MSAARenderBuffer = colorRenderbuffer;
  10734. }
  10735. else {
  10736. this.bindUnboundFramebuffer(texture._framebuffer);
  10737. }
  10738. texture.samples = samples;
  10739. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10740. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10741. this.bindUnboundFramebuffer(null);
  10742. return samples;
  10743. };
  10744. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10745. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10746. };
  10747. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10748. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10749. };
  10750. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10751. var gl = this._gl;
  10752. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10753. var generateMipMaps = true;
  10754. var generateDepthBuffer = true;
  10755. var generateStencilBuffer = false;
  10756. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10757. if (options !== undefined) {
  10758. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10759. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10760. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10761. if (options.samplingMode !== undefined) {
  10762. samplingMode = options.samplingMode;
  10763. }
  10764. }
  10765. texture.isCube = true;
  10766. texture.generateMipMaps = generateMipMaps;
  10767. texture.samples = 1;
  10768. texture.samplingMode = samplingMode;
  10769. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10770. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10771. for (var face = 0; face < 6; face++) {
  10772. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10773. }
  10774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10778. // Create the framebuffer
  10779. var framebuffer = gl.createFramebuffer();
  10780. this.bindUnboundFramebuffer(framebuffer);
  10781. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10782. // Mipmaps
  10783. if (texture.generateMipMaps) {
  10784. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10786. }
  10787. // Unbind
  10788. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10790. this.bindUnboundFramebuffer(null);
  10791. texture._framebuffer = framebuffer;
  10792. texture.width = size;
  10793. texture.height = size;
  10794. texture.isReady = true;
  10795. this.resetTextureCache();
  10796. this._internalTexturesCache.push(texture);
  10797. return texture;
  10798. };
  10799. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10800. var _this = this;
  10801. if (onLoad === void 0) { onLoad = null; }
  10802. if (onError === void 0) { onError = null; }
  10803. if (forcedExtension === void 0) { forcedExtension = null; }
  10804. var callback = function (loadData) {
  10805. if (!loadData) {
  10806. if (onLoad) {
  10807. onLoad(null);
  10808. }
  10809. return;
  10810. }
  10811. var texture = loadData.texture;
  10812. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10813. texture._lodGenerationScale = scale;
  10814. texture._lodGenerationOffset = offset;
  10815. if (_this._caps.textureLOD) {
  10816. // Do not add extra process if texture lod is supported.
  10817. if (onLoad) {
  10818. onLoad(texture);
  10819. }
  10820. return;
  10821. }
  10822. var mipSlices = 3;
  10823. var gl = _this._gl;
  10824. var width = loadData.width;
  10825. if (!width) {
  10826. return;
  10827. }
  10828. var textures = [];
  10829. for (var i = 0; i < mipSlices; i++) {
  10830. //compute LOD from even spacing in smoothness (matching shader calculation)
  10831. var smoothness = i / (mipSlices - 1);
  10832. var roughness = 1 - smoothness;
  10833. var minLODIndex = offset; // roughness = 0
  10834. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10835. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10836. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10837. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10838. glTextureFromLod.isCube = true;
  10839. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10844. if (loadData.isDDS) {
  10845. var info = loadData.info;
  10846. var data = loadData.data;
  10847. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10848. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10849. }
  10850. else {
  10851. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10852. }
  10853. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10854. // Wrap in a base texture for easy binding.
  10855. var lodTexture = new BABYLON.BaseTexture(scene);
  10856. lodTexture.isCube = true;
  10857. lodTexture._texture = glTextureFromLod;
  10858. glTextureFromLod.isReady = true;
  10859. textures.push(lodTexture);
  10860. }
  10861. texture._lodTextureHigh = textures[2];
  10862. texture._lodTextureMid = textures[1];
  10863. texture._lodTextureLow = textures[0];
  10864. if (onLoad) {
  10865. onLoad(texture);
  10866. }
  10867. };
  10868. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10869. };
  10870. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10871. var _this = this;
  10872. if (onLoad === void 0) { onLoad = null; }
  10873. if (onError === void 0) { onError = null; }
  10874. if (forcedExtension === void 0) { forcedExtension = null; }
  10875. var gl = this._gl;
  10876. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10877. texture.isCube = true;
  10878. texture.url = rootUrl;
  10879. texture.generateMipMaps = !noMipmap;
  10880. if (!this._doNotHandleContextLost) {
  10881. texture._extension = forcedExtension;
  10882. texture._files = files;
  10883. }
  10884. var isKTX = false;
  10885. var isDDS = false;
  10886. var lastDot = rootUrl.lastIndexOf('.');
  10887. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10888. if (this._textureFormatInUse) {
  10889. extension = this._textureFormatInUse;
  10890. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10891. isKTX = true;
  10892. }
  10893. else {
  10894. isDDS = (extension === ".dds");
  10895. }
  10896. var onerror = function (request, exception) {
  10897. if (onError) {
  10898. onError(request.status + " " + request.statusText, exception);
  10899. }
  10900. };
  10901. if (isKTX) {
  10902. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10903. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10904. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10907. ktx.uploadLevels(_this._gl, !noMipmap);
  10908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10912. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10913. _this.resetTextureCache();
  10914. texture.width = ktx.pixelWidth;
  10915. texture.height = ktx.pixelHeight;
  10916. texture.isReady = true;
  10917. }, undefined, undefined, true, onerror);
  10918. }
  10919. else if (isDDS) {
  10920. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10921. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10922. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10923. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10924. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10925. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10926. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10927. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10928. }
  10929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10933. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10934. _this.resetTextureCache();
  10935. texture.width = info.width;
  10936. texture.height = info.height;
  10937. texture.isReady = true;
  10938. texture.type = info.textureType;
  10939. if (onLoad) {
  10940. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10941. }
  10942. }, undefined, undefined, true, onerror);
  10943. }
  10944. else {
  10945. if (!files) {
  10946. throw new Error("Cannot load cubemap because files were not defined");
  10947. }
  10948. cascadeLoad(rootUrl, scene, function (imgs) {
  10949. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10950. var height = width;
  10951. _this._prepareWorkingCanvas();
  10952. if (!_this._workingCanvas || !_this._workingContext) {
  10953. return;
  10954. }
  10955. _this._workingCanvas.width = width;
  10956. _this._workingCanvas.height = height;
  10957. var faces = [
  10958. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10959. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10960. ];
  10961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10963. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10964. for (var index = 0; index < faces.length; index++) {
  10965. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10966. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10967. }
  10968. if (!noMipmap) {
  10969. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10970. }
  10971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10975. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10976. _this.resetTextureCache();
  10977. texture.width = width;
  10978. texture.height = height;
  10979. texture.isReady = true;
  10980. if (format) {
  10981. texture.format = format;
  10982. }
  10983. texture.onLoadedObservable.notifyObservers(texture);
  10984. texture.onLoadedObservable.clear();
  10985. if (onLoad) {
  10986. onLoad();
  10987. }
  10988. }, files, onError);
  10989. }
  10990. this._internalTexturesCache.push(texture);
  10991. return texture;
  10992. };
  10993. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10994. if (compression === void 0) { compression = null; }
  10995. if (level === void 0) { level = 0; }
  10996. texture._bufferViewArray = data;
  10997. texture.format = format;
  10998. texture.type = type;
  10999. texture.invertY = invertY;
  11000. texture._compression = compression;
  11001. var gl = this._gl;
  11002. var textureType = this._getWebGLTextureType(type);
  11003. var internalFormat = this._getInternalFormat(format);
  11004. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11005. var needConversion = false;
  11006. if (internalFormat === gl.RGB) {
  11007. internalFormat = gl.RGBA;
  11008. needConversion = true;
  11009. }
  11010. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11011. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11012. if (texture.width % 4 !== 0) {
  11013. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11014. }
  11015. // Data are known to be in +X +Y +Z -X -Y -Z
  11016. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11017. var faceData = data[faceIndex];
  11018. if (compression) {
  11019. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11020. }
  11021. else {
  11022. if (needConversion) {
  11023. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11024. }
  11025. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11026. }
  11027. }
  11028. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11029. if (isPot && texture.generateMipMaps && level === 0) {
  11030. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11031. }
  11032. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11033. this.resetTextureCache();
  11034. texture.isReady = true;
  11035. };
  11036. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11037. if (compression === void 0) { compression = null; }
  11038. var gl = this._gl;
  11039. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11040. texture.isCube = true;
  11041. texture.generateMipMaps = generateMipMaps;
  11042. texture.format = format;
  11043. texture.type = type;
  11044. if (!this._doNotHandleContextLost) {
  11045. texture._bufferViewArray = data;
  11046. }
  11047. var textureType = this._getWebGLTextureType(type);
  11048. var internalFormat = this._getInternalFormat(format);
  11049. var needConversion = false;
  11050. if (internalFormat === gl.RGB) {
  11051. internalFormat = gl.RGBA;
  11052. needConversion = true;
  11053. }
  11054. var width = size;
  11055. var height = width;
  11056. texture.width = width;
  11057. texture.height = height;
  11058. // Double check on POT to generate Mips.
  11059. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11060. if (!isPot) {
  11061. generateMipMaps = false;
  11062. }
  11063. // Upload data if needed. The texture won't be ready until then.
  11064. if (data) {
  11065. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11066. }
  11067. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11068. // Filters
  11069. if (data && generateMipMaps) {
  11070. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11071. }
  11072. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11075. }
  11076. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11079. }
  11080. else {
  11081. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11084. }
  11085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11087. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11088. return texture;
  11089. };
  11090. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11091. var _this = this;
  11092. if (onLoad === void 0) { onLoad = null; }
  11093. if (onError === void 0) { onError = null; }
  11094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11095. if (invertY === void 0) { invertY = false; }
  11096. var gl = this._gl;
  11097. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11098. scene._addPendingData(texture);
  11099. texture.url = url;
  11100. this._internalTexturesCache.push(texture);
  11101. var onerror = function (request, exception) {
  11102. scene._removePendingData(texture);
  11103. if (onError) {
  11104. onError(request.status + " " + request.statusText, exception);
  11105. }
  11106. };
  11107. var internalCallback = function (data) {
  11108. var width = texture.width;
  11109. var faceDataArrays = callback(data);
  11110. if (!faceDataArrays) {
  11111. return;
  11112. }
  11113. if (mipmmapGenerator) {
  11114. var textureType = _this._getWebGLTextureType(type);
  11115. var internalFormat = _this._getInternalFormat(format);
  11116. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11117. var needConversion = false;
  11118. if (internalFormat === gl.RGB) {
  11119. internalFormat = gl.RGBA;
  11120. needConversion = true;
  11121. }
  11122. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11123. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11124. var mipData = mipmmapGenerator(faceDataArrays);
  11125. for (var level = 0; level < mipData.length; level++) {
  11126. var mipSize = width >> level;
  11127. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11128. var mipFaceData = mipData[level][faceIndex];
  11129. if (needConversion) {
  11130. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11131. }
  11132. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11133. }
  11134. }
  11135. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11136. }
  11137. else {
  11138. texture.generateMipMaps = !noMipmap;
  11139. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11140. }
  11141. texture.isReady = true;
  11142. _this.resetTextureCache();
  11143. scene._removePendingData(texture);
  11144. if (onLoad) {
  11145. onLoad();
  11146. }
  11147. };
  11148. BABYLON.Tools.LoadFile(url, function (data) {
  11149. internalCallback(data);
  11150. }, undefined, scene.database, true, onerror);
  11151. return texture;
  11152. };
  11153. ;
  11154. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11155. if (compression === void 0) { compression = null; }
  11156. var internalFormat = this._getInternalFormat(format);
  11157. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11158. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11159. if (!this._doNotHandleContextLost) {
  11160. texture._bufferView = data;
  11161. texture.format = format;
  11162. texture.invertY = invertY;
  11163. texture._compression = compression;
  11164. }
  11165. if (texture.width % 4 !== 0) {
  11166. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11167. }
  11168. if (compression && data) {
  11169. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11170. }
  11171. else {
  11172. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11173. }
  11174. if (texture.generateMipMaps) {
  11175. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11176. }
  11177. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11178. this.resetTextureCache();
  11179. texture.isReady = true;
  11180. };
  11181. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11182. if (compression === void 0) { compression = null; }
  11183. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11184. texture.baseWidth = width;
  11185. texture.baseHeight = height;
  11186. texture.baseDepth = depth;
  11187. texture.width = width;
  11188. texture.height = height;
  11189. texture.depth = depth;
  11190. texture.format = format;
  11191. texture.generateMipMaps = generateMipMaps;
  11192. texture.samplingMode = samplingMode;
  11193. texture.is3D = true;
  11194. if (!this._doNotHandleContextLost) {
  11195. texture._bufferView = data;
  11196. }
  11197. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11198. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11199. // Filters
  11200. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11201. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11203. if (generateMipMaps) {
  11204. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11205. }
  11206. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11207. this._internalTexturesCache.push(texture);
  11208. return texture;
  11209. };
  11210. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11211. var gl = this._gl;
  11212. if (!gl) {
  11213. return;
  11214. }
  11215. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11218. if (!noMipmap && !isCompressed) {
  11219. gl.generateMipmap(gl.TEXTURE_2D);
  11220. }
  11221. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11222. this.resetTextureCache();
  11223. if (scene) {
  11224. scene._removePendingData(texture);
  11225. }
  11226. texture.onLoadedObservable.notifyObservers(texture);
  11227. texture.onLoadedObservable.clear();
  11228. };
  11229. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11230. var _this = this;
  11231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11232. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11233. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11234. var gl = this._gl;
  11235. if (!gl) {
  11236. return;
  11237. }
  11238. if (!texture._webGLTexture) {
  11239. this.resetTextureCache();
  11240. if (scene) {
  11241. scene._removePendingData(texture);
  11242. }
  11243. return;
  11244. }
  11245. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11246. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11247. texture.baseWidth = width;
  11248. texture.baseHeight = height;
  11249. texture.width = potWidth;
  11250. texture.height = potHeight;
  11251. texture.isReady = true;
  11252. if (processFunction(potWidth, potHeight, function () {
  11253. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11254. })) {
  11255. // Returning as texture needs extra async steps
  11256. return;
  11257. }
  11258. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11259. };
  11260. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11261. // Create new RGBA data container.
  11262. var rgbaData;
  11263. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11264. rgbaData = new Float32Array(width * height * 4);
  11265. }
  11266. else {
  11267. rgbaData = new Uint32Array(width * height * 4);
  11268. }
  11269. // Convert each pixel.
  11270. for (var x = 0; x < width; x++) {
  11271. for (var y = 0; y < height; y++) {
  11272. var index = (y * width + x) * 3;
  11273. var newIndex = (y * width + x) * 4;
  11274. // Map Old Value to new value.
  11275. rgbaData[newIndex + 0] = rgbData[index + 0];
  11276. rgbaData[newIndex + 1] = rgbData[index + 1];
  11277. rgbaData[newIndex + 2] = rgbData[index + 2];
  11278. // Add fully opaque alpha channel.
  11279. rgbaData[newIndex + 3] = 1;
  11280. }
  11281. }
  11282. return rgbaData;
  11283. };
  11284. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11285. var gl = this._gl;
  11286. if (texture._framebuffer) {
  11287. gl.deleteFramebuffer(texture._framebuffer);
  11288. texture._framebuffer = null;
  11289. }
  11290. if (texture._depthStencilBuffer) {
  11291. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11292. texture._depthStencilBuffer = null;
  11293. }
  11294. if (texture._MSAAFramebuffer) {
  11295. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11296. texture._MSAAFramebuffer = null;
  11297. }
  11298. if (texture._MSAARenderBuffer) {
  11299. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11300. texture._MSAARenderBuffer = null;
  11301. }
  11302. };
  11303. Engine.prototype._releaseTexture = function (texture) {
  11304. var gl = this._gl;
  11305. this._releaseFramebufferObjects(texture);
  11306. gl.deleteTexture(texture._webGLTexture);
  11307. // Unbind channels
  11308. this.unbindAllTextures();
  11309. var index = this._internalTexturesCache.indexOf(texture);
  11310. if (index !== -1) {
  11311. this._internalTexturesCache.splice(index, 1);
  11312. }
  11313. // Integrated fixed lod samplers.
  11314. if (texture._lodTextureHigh) {
  11315. texture._lodTextureHigh.dispose();
  11316. }
  11317. if (texture._lodTextureMid) {
  11318. texture._lodTextureMid.dispose();
  11319. }
  11320. if (texture._lodTextureLow) {
  11321. texture._lodTextureLow.dispose();
  11322. }
  11323. };
  11324. Engine.prototype.setProgram = function (program) {
  11325. if (this._currentProgram !== program) {
  11326. this._gl.useProgram(program);
  11327. this._currentProgram = program;
  11328. }
  11329. };
  11330. Engine.prototype.bindSamplers = function (effect) {
  11331. this.setProgram(effect.getProgram());
  11332. var samplers = effect.getSamplers();
  11333. for (var index = 0; index < samplers.length; index++) {
  11334. var uniform = effect.getUniform(samplers[index]);
  11335. this._gl.uniform1i(uniform, index);
  11336. }
  11337. this._currentEffect = null;
  11338. };
  11339. Engine.prototype.activateTexture = function (texture) {
  11340. if (this._activeTexture !== texture) {
  11341. this._gl.activeTexture(texture);
  11342. this._activeTexture = texture;
  11343. }
  11344. };
  11345. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11346. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11347. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11348. this._activeTexturesCache[this._activeTexture] = texture;
  11349. }
  11350. };
  11351. Engine.prototype._bindTexture = function (channel, texture) {
  11352. if (channel < 0) {
  11353. return;
  11354. }
  11355. this.activateTexture(this._gl.TEXTURE0 + channel);
  11356. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11357. };
  11358. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11359. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11360. };
  11361. Engine.prototype.unbindAllTextures = function () {
  11362. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11363. this.activateTexture(this._gl["TEXTURE" + channel]);
  11364. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11365. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11366. if (this.webGLVersion > 1) {
  11367. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11368. }
  11369. }
  11370. };
  11371. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11372. if (channel < 0) {
  11373. return;
  11374. }
  11375. this._gl.uniform1i(uniform, channel);
  11376. this._setTexture(channel, texture);
  11377. };
  11378. Engine.prototype._setTexture = function (channel, texture) {
  11379. // Not ready?
  11380. if (!texture) {
  11381. if (this._activeTexturesCache[channel] != null) {
  11382. this.activateTexture(this._gl["TEXTURE" + channel]);
  11383. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11384. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11385. if (this.webGLVersion > 1) {
  11386. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11387. }
  11388. }
  11389. return;
  11390. }
  11391. // Video
  11392. var alreadyActivated = false;
  11393. if (texture.video) {
  11394. this.activateTexture(this._gl["TEXTURE" + channel]);
  11395. alreadyActivated = true;
  11396. texture.update();
  11397. }
  11398. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11399. texture.delayLoad();
  11400. return;
  11401. }
  11402. var internalTexture;
  11403. if (texture.isReady()) {
  11404. internalTexture = texture.getInternalTexture();
  11405. }
  11406. else if (texture.isCube) {
  11407. internalTexture = this.emptyCubeTexture;
  11408. }
  11409. else if (texture.is3D) {
  11410. internalTexture = this.emptyTexture3D;
  11411. }
  11412. else {
  11413. internalTexture = this.emptyTexture;
  11414. }
  11415. if (this._activeTexturesCache[channel] === internalTexture) {
  11416. return;
  11417. }
  11418. if (!alreadyActivated) {
  11419. this.activateTexture(this._gl["TEXTURE" + channel]);
  11420. }
  11421. if (internalTexture && internalTexture.is3D) {
  11422. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11423. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11424. internalTexture._cachedWrapU = texture.wrapU;
  11425. switch (texture.wrapU) {
  11426. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11427. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11428. break;
  11429. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11430. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11431. break;
  11432. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11433. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11434. break;
  11435. }
  11436. }
  11437. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11438. internalTexture._cachedWrapV = texture.wrapV;
  11439. switch (texture.wrapV) {
  11440. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11441. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11442. break;
  11443. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11444. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11445. break;
  11446. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11447. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11448. break;
  11449. }
  11450. }
  11451. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11452. internalTexture._cachedWrapR = texture.wrapR;
  11453. switch (texture.wrapV) {
  11454. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11455. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11456. break;
  11457. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11458. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11459. break;
  11460. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11461. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11462. break;
  11463. }
  11464. }
  11465. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11466. }
  11467. else if (internalTexture && internalTexture.isCube) {
  11468. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11469. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11470. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11471. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11472. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11473. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11474. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11475. }
  11476. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11477. }
  11478. else {
  11479. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11480. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11481. internalTexture._cachedWrapU = texture.wrapU;
  11482. switch (texture.wrapU) {
  11483. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11484. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11485. break;
  11486. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11488. break;
  11489. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11490. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11491. break;
  11492. }
  11493. }
  11494. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11495. internalTexture._cachedWrapV = texture.wrapV;
  11496. switch (texture.wrapV) {
  11497. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11498. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11499. break;
  11500. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11501. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11502. break;
  11503. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11504. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11505. break;
  11506. }
  11507. }
  11508. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11509. }
  11510. };
  11511. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11512. if (channel < 0 || !uniform) {
  11513. return;
  11514. }
  11515. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11516. this._textureUnits = new Int32Array(textures.length);
  11517. }
  11518. for (var i = 0; i < textures.length; i++) {
  11519. this._textureUnits[i] = channel + i;
  11520. }
  11521. this._gl.uniform1iv(uniform, this._textureUnits);
  11522. for (var index = 0; index < textures.length; index++) {
  11523. this._setTexture(channel + index, textures[index]);
  11524. }
  11525. };
  11526. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11527. var internalTexture = texture.getInternalTexture();
  11528. if (!internalTexture) {
  11529. return;
  11530. }
  11531. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11532. var value = texture.anisotropicFilteringLevel;
  11533. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11534. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11535. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11536. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11537. }
  11538. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11539. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11540. internalTexture._cachedAnisotropicFilteringLevel = value;
  11541. }
  11542. };
  11543. Engine.prototype.readPixels = function (x, y, width, height) {
  11544. var data = new Uint8Array(height * width * 4);
  11545. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11546. return data;
  11547. };
  11548. /**
  11549. * Add an externaly attached data from its key.
  11550. * This method call will fail and return false, if such key already exists.
  11551. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11552. * @param key the unique key that identifies the data
  11553. * @param data the data object to associate to the key for this Engine instance
  11554. * @return true if no such key were already present and the data was added successfully, false otherwise
  11555. */
  11556. Engine.prototype.addExternalData = function (key, data) {
  11557. if (!this._externalData) {
  11558. this._externalData = new BABYLON.StringDictionary();
  11559. }
  11560. return this._externalData.add(key, data);
  11561. };
  11562. /**
  11563. * Get an externaly attached data from its key
  11564. * @param key the unique key that identifies the data
  11565. * @return the associated data, if present (can be null), or undefined if not present
  11566. */
  11567. Engine.prototype.getExternalData = function (key) {
  11568. if (!this._externalData) {
  11569. this._externalData = new BABYLON.StringDictionary();
  11570. }
  11571. return this._externalData.get(key);
  11572. };
  11573. /**
  11574. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11575. * @param key the unique key that identifies the data
  11576. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11577. * @return the associated data, can be null if the factory returned null.
  11578. */
  11579. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11580. if (!this._externalData) {
  11581. this._externalData = new BABYLON.StringDictionary();
  11582. }
  11583. return this._externalData.getOrAddWithFactory(key, factory);
  11584. };
  11585. /**
  11586. * Remove an externaly attached data from the Engine instance
  11587. * @param key the unique key that identifies the data
  11588. * @return true if the data was successfully removed, false if it doesn't exist
  11589. */
  11590. Engine.prototype.removeExternalData = function (key) {
  11591. if (!this._externalData) {
  11592. this._externalData = new BABYLON.StringDictionary();
  11593. }
  11594. return this._externalData.remove(key);
  11595. };
  11596. Engine.prototype.unbindAllAttributes = function () {
  11597. if (this._mustWipeVertexAttributes) {
  11598. this._mustWipeVertexAttributes = false;
  11599. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11600. this._gl.disableVertexAttribArray(i);
  11601. this._vertexAttribArraysEnabled[i] = false;
  11602. this._currentBufferPointers[i].active = false;
  11603. }
  11604. return;
  11605. }
  11606. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11607. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11608. continue;
  11609. }
  11610. this._gl.disableVertexAttribArray(i);
  11611. this._vertexAttribArraysEnabled[i] = false;
  11612. this._currentBufferPointers[i].active = false;
  11613. }
  11614. };
  11615. Engine.prototype.releaseEffects = function () {
  11616. for (var name in this._compiledEffects) {
  11617. this._deleteProgram(this._compiledEffects[name]._program);
  11618. }
  11619. this._compiledEffects = {};
  11620. };
  11621. // Dispose
  11622. Engine.prototype.dispose = function () {
  11623. this.hideLoadingUI();
  11624. this.stopRenderLoop();
  11625. // Release postProcesses
  11626. while (this.postProcesses.length) {
  11627. this.postProcesses[0].dispose();
  11628. }
  11629. // Empty texture
  11630. if (this._emptyTexture) {
  11631. this._releaseTexture(this._emptyTexture);
  11632. this._emptyTexture = null;
  11633. }
  11634. if (this._emptyCubeTexture) {
  11635. this._releaseTexture(this._emptyCubeTexture);
  11636. this._emptyCubeTexture = null;
  11637. }
  11638. // Rescale PP
  11639. if (this._rescalePostProcess) {
  11640. this._rescalePostProcess.dispose();
  11641. }
  11642. // Release scenes
  11643. while (this.scenes.length) {
  11644. this.scenes[0].dispose();
  11645. }
  11646. // Release audio engine
  11647. if (Engine.audioEngine) {
  11648. Engine.audioEngine.dispose();
  11649. }
  11650. // Release effects
  11651. this.releaseEffects();
  11652. // Unbind
  11653. this.unbindAllAttributes();
  11654. if (this._dummyFramebuffer) {
  11655. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11656. }
  11657. //WebVR
  11658. this.disableVR();
  11659. // Events
  11660. window.removeEventListener("blur", this._onBlur);
  11661. window.removeEventListener("focus", this._onFocus);
  11662. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11663. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11664. if (this._renderingCanvas) {
  11665. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11666. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11667. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11668. if (!this._doNotHandleContextLost) {
  11669. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11670. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11671. }
  11672. }
  11673. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11674. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11675. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11676. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11677. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11678. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11679. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11680. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11681. if (this._onVrDisplayConnect) {
  11682. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11683. if (this._onVrDisplayDisconnect) {
  11684. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11685. }
  11686. if (this._onVrDisplayPresentChange) {
  11687. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11688. }
  11689. this._onVrDisplayConnect = null;
  11690. this._onVrDisplayDisconnect = null;
  11691. }
  11692. // Remove from Instances
  11693. var index = Engine.Instances.indexOf(this);
  11694. if (index >= 0) {
  11695. Engine.Instances.splice(index, 1);
  11696. }
  11697. this._workingCanvas = null;
  11698. this._workingContext = null;
  11699. this._currentBufferPointers = [];
  11700. this._renderingCanvas = null;
  11701. this._currentProgram = null;
  11702. this.onResizeObservable.clear();
  11703. this.onCanvasBlurObservable.clear();
  11704. this.onCanvasFocusObservable.clear();
  11705. this.onCanvasPointerOutObservable.clear();
  11706. this.onBeginFrameObservable.clear();
  11707. this.onEndFrameObservable.clear();
  11708. BABYLON.Effect.ResetCache();
  11709. };
  11710. // Loading screen
  11711. Engine.prototype.displayLoadingUI = function () {
  11712. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11713. return;
  11714. }
  11715. var loadingScreen = this.loadingScreen;
  11716. if (loadingScreen) {
  11717. loadingScreen.displayLoadingUI();
  11718. }
  11719. };
  11720. Engine.prototype.hideLoadingUI = function () {
  11721. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11722. return;
  11723. }
  11724. var loadingScreen = this.loadingScreen;
  11725. if (loadingScreen) {
  11726. loadingScreen.hideLoadingUI();
  11727. }
  11728. };
  11729. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11730. get: function () {
  11731. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11732. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11733. return this._loadingScreen;
  11734. },
  11735. set: function (loadingScreen) {
  11736. this._loadingScreen = loadingScreen;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11742. set: function (text) {
  11743. this.loadingScreen.loadingUIText = text;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11749. set: function (color) {
  11750. this.loadingScreen.loadingUIBackgroundColor = color;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Engine.prototype.attachContextLostEvent = function (callback) {
  11756. if (this._renderingCanvas) {
  11757. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11758. }
  11759. };
  11760. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11761. if (this._renderingCanvas) {
  11762. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11763. }
  11764. };
  11765. Engine.prototype.getVertexShaderSource = function (program) {
  11766. var shaders = this._gl.getAttachedShaders(program);
  11767. if (!shaders) {
  11768. return null;
  11769. }
  11770. return this._gl.getShaderSource(shaders[0]);
  11771. };
  11772. Engine.prototype.getFragmentShaderSource = function (program) {
  11773. var shaders = this._gl.getAttachedShaders(program);
  11774. if (!shaders) {
  11775. return null;
  11776. }
  11777. return this._gl.getShaderSource(shaders[1]);
  11778. };
  11779. Engine.prototype.getError = function () {
  11780. return this._gl.getError();
  11781. };
  11782. // FPS
  11783. Engine.prototype.getFps = function () {
  11784. return this._fps;
  11785. };
  11786. Engine.prototype.getDeltaTime = function () {
  11787. return this._deltaTime;
  11788. };
  11789. Engine.prototype._measureFps = function () {
  11790. this._performanceMonitor.sampleFrame();
  11791. this._fps = this._performanceMonitor.averageFPS;
  11792. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11793. };
  11794. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11795. if (faceIndex === void 0) { faceIndex = -1; }
  11796. var gl = this._gl;
  11797. if (!this._dummyFramebuffer) {
  11798. var dummy = gl.createFramebuffer();
  11799. if (!dummy) {
  11800. throw new Error("Unable to create dummy framebuffer");
  11801. }
  11802. this._dummyFramebuffer = dummy;
  11803. }
  11804. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11805. if (faceIndex > -1) {
  11806. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11807. }
  11808. else {
  11809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11810. }
  11811. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11812. var buffer;
  11813. switch (readType) {
  11814. case gl.UNSIGNED_BYTE:
  11815. buffer = new Uint8Array(4 * width * height);
  11816. readType = gl.UNSIGNED_BYTE;
  11817. break;
  11818. default:
  11819. buffer = new Float32Array(4 * width * height);
  11820. readType = gl.FLOAT;
  11821. break;
  11822. }
  11823. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11824. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11825. return buffer;
  11826. };
  11827. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11828. if (this._webGLVersion > 1) {
  11829. return this._caps.colorBufferFloat;
  11830. }
  11831. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11832. };
  11833. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11834. if (this._webGLVersion > 1) {
  11835. return this._caps.colorBufferFloat;
  11836. }
  11837. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11838. };
  11839. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11840. Engine.prototype._canRenderToFramebuffer = function (type) {
  11841. var gl = this._gl;
  11842. //clear existing errors
  11843. while (gl.getError() !== gl.NO_ERROR) { }
  11844. var successful = true;
  11845. var texture = gl.createTexture();
  11846. gl.bindTexture(gl.TEXTURE_2D, texture);
  11847. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11850. var fb = gl.createFramebuffer();
  11851. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11853. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11854. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11855. successful = successful && (gl.getError() === gl.NO_ERROR);
  11856. //try render by clearing frame buffer's color buffer
  11857. if (successful) {
  11858. gl.clear(gl.COLOR_BUFFER_BIT);
  11859. successful = successful && (gl.getError() === gl.NO_ERROR);
  11860. }
  11861. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11862. if (successful) {
  11863. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11864. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11865. var readFormat = gl.RGBA;
  11866. var readType = gl.UNSIGNED_BYTE;
  11867. var buffer = new Uint8Array(4);
  11868. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11869. successful = successful && (gl.getError() === gl.NO_ERROR);
  11870. }
  11871. //clean up
  11872. gl.deleteTexture(texture);
  11873. gl.deleteFramebuffer(fb);
  11874. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11875. //clear accumulated errors
  11876. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11877. return successful;
  11878. };
  11879. Engine.prototype._getWebGLTextureType = function (type) {
  11880. if (type === Engine.TEXTURETYPE_FLOAT) {
  11881. return this._gl.FLOAT;
  11882. }
  11883. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11884. // Add Half Float Constant.
  11885. return this._gl.HALF_FLOAT_OES;
  11886. }
  11887. return this._gl.UNSIGNED_BYTE;
  11888. };
  11889. ;
  11890. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11891. if (this._webGLVersion === 1) {
  11892. return this._gl.RGBA;
  11893. }
  11894. if (type === Engine.TEXTURETYPE_FLOAT) {
  11895. return this._gl.RGBA32F;
  11896. }
  11897. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11898. return this._gl.RGBA16F;
  11899. }
  11900. return this._gl.RGBA;
  11901. };
  11902. ;
  11903. Engine.prototype.createQuery = function () {
  11904. return this._gl.createQuery();
  11905. };
  11906. Engine.prototype.deleteQuery = function (query) {
  11907. this._gl.deleteQuery(query);
  11908. return this;
  11909. };
  11910. Engine.prototype.isQueryResultAvailable = function (query) {
  11911. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11912. };
  11913. Engine.prototype.getQueryResult = function (query) {
  11914. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11915. };
  11916. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11917. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11918. this._gl.beginQuery(glAlgorithm, query);
  11919. return this;
  11920. };
  11921. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11922. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11923. this._gl.endQuery(glAlgorithm);
  11924. return this;
  11925. };
  11926. /* Time queries */
  11927. Engine.prototype._createTimeQuery = function () {
  11928. var timerQuery = this._caps.timerQuery;
  11929. if (timerQuery.createQueryEXT) {
  11930. return timerQuery.createQueryEXT();
  11931. }
  11932. return this.createQuery();
  11933. };
  11934. Engine.prototype._deleteTimeQuery = function (query) {
  11935. var timerQuery = this._caps.timerQuery;
  11936. if (timerQuery.deleteQueryEXT) {
  11937. timerQuery.deleteQueryEXT(query);
  11938. return;
  11939. }
  11940. this.deleteQuery(query);
  11941. };
  11942. Engine.prototype._getTimeQueryResult = function (query) {
  11943. var timerQuery = this._caps.timerQuery;
  11944. if (timerQuery.getQueryObjectEXT) {
  11945. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11946. }
  11947. return this.getQueryResult(query);
  11948. };
  11949. Engine.prototype._getTimeQueryAvailability = function (query) {
  11950. var timerQuery = this._caps.timerQuery;
  11951. if (timerQuery.getQueryObjectEXT) {
  11952. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11953. }
  11954. return this.isQueryResultAvailable(query);
  11955. };
  11956. Engine.prototype.startTimeQuery = function () {
  11957. var timerQuery = this._caps.timerQuery;
  11958. if (!timerQuery) {
  11959. return null;
  11960. }
  11961. var token = new BABYLON._TimeToken();
  11962. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11963. if (this._caps.canUseTimestampForTimerQuery) {
  11964. token._startTimeQuery = this._createTimeQuery();
  11965. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11966. }
  11967. else {
  11968. if (this._currentNonTimestampToken) {
  11969. return this._currentNonTimestampToken;
  11970. }
  11971. token._timeElapsedQuery = this._createTimeQuery();
  11972. if (timerQuery.beginQueryEXT) {
  11973. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11974. }
  11975. else {
  11976. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11977. }
  11978. this._currentNonTimestampToken = token;
  11979. }
  11980. return token;
  11981. };
  11982. Engine.prototype.endTimeQuery = function (token) {
  11983. var timerQuery = this._caps.timerQuery;
  11984. if (!timerQuery || !token) {
  11985. return -1;
  11986. }
  11987. if (this._caps.canUseTimestampForTimerQuery) {
  11988. if (!token._startTimeQuery) {
  11989. return -1;
  11990. }
  11991. if (!token._endTimeQuery) {
  11992. token._endTimeQuery = this._createTimeQuery();
  11993. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  11994. }
  11995. }
  11996. else if (!token._timeElapsedQueryEnded) {
  11997. if (!token._timeElapsedQuery) {
  11998. return -1;
  11999. }
  12000. if (timerQuery.endQueryEXT) {
  12001. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12002. }
  12003. else {
  12004. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12005. }
  12006. token._timeElapsedQueryEnded = true;
  12007. }
  12008. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12009. var available = false;
  12010. if (token._endTimeQuery) {
  12011. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12012. }
  12013. else if (token._timeElapsedQuery) {
  12014. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12015. }
  12016. if (available && !disjoint) {
  12017. var result = 0;
  12018. if (this._caps.canUseTimestampForTimerQuery) {
  12019. if (!token._startTimeQuery || !token._endTimeQuery) {
  12020. return -1;
  12021. }
  12022. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12023. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12024. result = timeEnd - timeStart;
  12025. this._deleteTimeQuery(token._startTimeQuery);
  12026. this._deleteTimeQuery(token._endTimeQuery);
  12027. token._startTimeQuery = null;
  12028. token._endTimeQuery = null;
  12029. }
  12030. else {
  12031. if (!token._timeElapsedQuery) {
  12032. return -1;
  12033. }
  12034. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12035. this._deleteTimeQuery(token._timeElapsedQuery);
  12036. token._timeElapsedQuery = null;
  12037. token._timeElapsedQueryEnded = false;
  12038. this._currentNonTimestampToken = null;
  12039. }
  12040. return result;
  12041. }
  12042. return -1;
  12043. };
  12044. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12045. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12046. };
  12047. // Statics
  12048. Engine.isSupported = function () {
  12049. try {
  12050. var tempcanvas = document.createElement("canvas");
  12051. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12052. return gl != null && !!window.WebGLRenderingContext;
  12053. }
  12054. catch (e) {
  12055. return false;
  12056. }
  12057. };
  12058. Engine.Instances = new Array();
  12059. // Const statics
  12060. Engine._ALPHA_DISABLE = 0;
  12061. Engine._ALPHA_ADD = 1;
  12062. Engine._ALPHA_COMBINE = 2;
  12063. Engine._ALPHA_SUBTRACT = 3;
  12064. Engine._ALPHA_MULTIPLY = 4;
  12065. Engine._ALPHA_MAXIMIZED = 5;
  12066. Engine._ALPHA_ONEONE = 6;
  12067. Engine._ALPHA_PREMULTIPLIED = 7;
  12068. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12069. Engine._ALPHA_INTERPOLATE = 9;
  12070. Engine._ALPHA_SCREENMODE = 10;
  12071. Engine._DELAYLOADSTATE_NONE = 0;
  12072. Engine._DELAYLOADSTATE_LOADED = 1;
  12073. Engine._DELAYLOADSTATE_LOADING = 2;
  12074. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12075. Engine._TEXTUREFORMAT_ALPHA = 0;
  12076. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12077. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12078. Engine._TEXTUREFORMAT_RGB = 4;
  12079. Engine._TEXTUREFORMAT_RGBA = 5;
  12080. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12081. Engine._TEXTURETYPE_FLOAT = 1;
  12082. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12083. // Depht or Stencil test Constants.
  12084. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12085. 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.
  12086. 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.
  12087. 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.
  12088. 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.
  12089. 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.
  12090. 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.
  12091. 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.
  12092. // Stencil Actions Constants.
  12093. Engine._KEEP = 0x1E00;
  12094. Engine._REPLACE = 0x1E01;
  12095. Engine._INCR = 0x1E02;
  12096. Engine._DECR = 0x1E03;
  12097. Engine._INVERT = 0x150A;
  12098. Engine._INCR_WRAP = 0x8507;
  12099. Engine._DECR_WRAP = 0x8508;
  12100. // Texture rescaling mode
  12101. Engine._SCALEMODE_FLOOR = 1;
  12102. Engine._SCALEMODE_NEAREST = 2;
  12103. Engine._SCALEMODE_CEILING = 3;
  12104. // Updatable statics so stick with vars here
  12105. Engine.CollisionsEpsilon = 0.001;
  12106. Engine.CodeRepository = "src/";
  12107. Engine.ShadersRepository = "src/Shaders/";
  12108. return Engine;
  12109. }());
  12110. BABYLON.Engine = Engine;
  12111. })(BABYLON || (BABYLON = {}));
  12112. //# sourceMappingURL=babylon.engine.js.map
  12113. var BABYLON;
  12114. (function (BABYLON) {
  12115. /**
  12116. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12117. */
  12118. var Node = /** @class */ (function () {
  12119. /**
  12120. * @constructor
  12121. * @param {string} name - the name and id to be given to this node
  12122. * @param {BABYLON.Scene} the scene this node will be added to
  12123. */
  12124. function Node(name, scene) {
  12125. if (scene === void 0) { scene = null; }
  12126. this.state = "";
  12127. this.metadata = null;
  12128. this.doNotSerialize = false;
  12129. this.animations = new Array();
  12130. this._ranges = {};
  12131. this._isEnabled = true;
  12132. this._isReady = true;
  12133. this._currentRenderId = -1;
  12134. this._parentRenderId = -1;
  12135. /**
  12136. * An event triggered when the mesh is disposed.
  12137. * @type {BABYLON.Observable}
  12138. */
  12139. this.onDisposeObservable = new BABYLON.Observable();
  12140. // Behaviors
  12141. this._behaviors = new Array();
  12142. this.name = name;
  12143. this.id = name;
  12144. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12145. this.uniqueId = this._scene.getUniqueId();
  12146. this._initCache();
  12147. }
  12148. Object.defineProperty(Node.prototype, "parent", {
  12149. get: function () {
  12150. return this._parentNode;
  12151. },
  12152. set: function (parent) {
  12153. if (this._parentNode === parent) {
  12154. return;
  12155. }
  12156. if (this._parentNode) {
  12157. var index = this._parentNode._children.indexOf(this);
  12158. if (index !== -1) {
  12159. this._parentNode._children.splice(index, 1);
  12160. }
  12161. }
  12162. this._parentNode = parent;
  12163. if (this._parentNode) {
  12164. if (!this._parentNode._children) {
  12165. this._parentNode._children = new Array();
  12166. }
  12167. this._parentNode._children.push(this);
  12168. }
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. Node.prototype.getClassName = function () {
  12174. return "Node";
  12175. };
  12176. Object.defineProperty(Node.prototype, "onDispose", {
  12177. set: function (callback) {
  12178. if (this._onDisposeObserver) {
  12179. this.onDisposeObservable.remove(this._onDisposeObserver);
  12180. }
  12181. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12182. },
  12183. enumerable: true,
  12184. configurable: true
  12185. });
  12186. Node.prototype.getScene = function () {
  12187. return this._scene;
  12188. };
  12189. Node.prototype.getEngine = function () {
  12190. return this._scene.getEngine();
  12191. };
  12192. Node.prototype.addBehavior = function (behavior) {
  12193. var index = this._behaviors.indexOf(behavior);
  12194. if (index !== -1) {
  12195. return this;
  12196. }
  12197. behavior.attach(this);
  12198. this._behaviors.push(behavior);
  12199. return this;
  12200. };
  12201. Node.prototype.removeBehavior = function (behavior) {
  12202. var index = this._behaviors.indexOf(behavior);
  12203. if (index === -1) {
  12204. return this;
  12205. }
  12206. this._behaviors[index].detach();
  12207. this._behaviors.splice(index, 1);
  12208. return this;
  12209. };
  12210. Object.defineProperty(Node.prototype, "behaviors", {
  12211. get: function () {
  12212. return this._behaviors;
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Node.prototype.getBehaviorByName = function (name) {
  12218. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12219. var behavior = _a[_i];
  12220. if (behavior.name === name) {
  12221. return behavior;
  12222. }
  12223. }
  12224. return null;
  12225. };
  12226. // override it in derived class
  12227. Node.prototype.getWorldMatrix = function () {
  12228. return BABYLON.Matrix.Identity();
  12229. };
  12230. // override it in derived class if you add new variables to the cache
  12231. // and call the parent class method
  12232. Node.prototype._initCache = function () {
  12233. this._cache = {};
  12234. this._cache.parent = undefined;
  12235. };
  12236. Node.prototype.updateCache = function (force) {
  12237. if (!force && this.isSynchronized())
  12238. return;
  12239. this._cache.parent = this.parent;
  12240. this._updateCache();
  12241. };
  12242. // override it in derived class if you add new variables to the cache
  12243. // and call the parent class method if !ignoreParentClass
  12244. Node.prototype._updateCache = function (ignoreParentClass) {
  12245. };
  12246. // override it in derived class if you add new variables to the cache
  12247. Node.prototype._isSynchronized = function () {
  12248. return true;
  12249. };
  12250. Node.prototype._markSyncedWithParent = function () {
  12251. if (this.parent) {
  12252. this._parentRenderId = this.parent._currentRenderId;
  12253. }
  12254. };
  12255. Node.prototype.isSynchronizedWithParent = function () {
  12256. if (!this.parent) {
  12257. return true;
  12258. }
  12259. if (this._parentRenderId !== this.parent._currentRenderId) {
  12260. return false;
  12261. }
  12262. return this.parent.isSynchronized();
  12263. };
  12264. Node.prototype.isSynchronized = function (updateCache) {
  12265. var check = this.hasNewParent();
  12266. check = check || !this.isSynchronizedWithParent();
  12267. check = check || !this._isSynchronized();
  12268. if (updateCache)
  12269. this.updateCache(true);
  12270. return !check;
  12271. };
  12272. Node.prototype.hasNewParent = function (update) {
  12273. if (this._cache.parent === this.parent)
  12274. return false;
  12275. if (update)
  12276. this._cache.parent = this.parent;
  12277. return true;
  12278. };
  12279. /**
  12280. * Is this node ready to be used/rendered
  12281. * @return {boolean} is it ready
  12282. */
  12283. Node.prototype.isReady = function () {
  12284. return this._isReady;
  12285. };
  12286. /**
  12287. * Is this node enabled.
  12288. * If the node has a parent and is enabled, the parent will be inspected as well.
  12289. * @return {boolean} whether this node (and its parent) is enabled.
  12290. * @see setEnabled
  12291. */
  12292. Node.prototype.isEnabled = function () {
  12293. if (!this._isEnabled) {
  12294. return false;
  12295. }
  12296. if (this.parent) {
  12297. return this.parent.isEnabled();
  12298. }
  12299. return true;
  12300. };
  12301. /**
  12302. * Set the enabled state of this node.
  12303. * @param {boolean} value - the new enabled state
  12304. * @see isEnabled
  12305. */
  12306. Node.prototype.setEnabled = function (value) {
  12307. this._isEnabled = value;
  12308. };
  12309. /**
  12310. * Is this node a descendant of the given node.
  12311. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12312. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12313. * @see parent
  12314. */
  12315. Node.prototype.isDescendantOf = function (ancestor) {
  12316. if (this.parent) {
  12317. if (this.parent === ancestor) {
  12318. return true;
  12319. }
  12320. return this.parent.isDescendantOf(ancestor);
  12321. }
  12322. return false;
  12323. };
  12324. /**
  12325. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12326. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12327. * @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.
  12328. * @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.
  12329. */
  12330. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12331. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12332. if (!this._children) {
  12333. return;
  12334. }
  12335. for (var index = 0; index < this._children.length; index++) {
  12336. var item = this._children[index];
  12337. if (!predicate || predicate(item)) {
  12338. results.push(item);
  12339. }
  12340. if (!directDescendantsOnly) {
  12341. item._getDescendants(results, false, predicate);
  12342. }
  12343. }
  12344. };
  12345. /**
  12346. * Will return all nodes that have this node as ascendant.
  12347. * @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.
  12348. * @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.
  12349. * @return {BABYLON.Node[]} all children nodes of all types.
  12350. */
  12351. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12352. var results = new Array();
  12353. this._getDescendants(results, directDescendantsOnly, predicate);
  12354. return results;
  12355. };
  12356. /**
  12357. * Get all child-meshes of this node.
  12358. */
  12359. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12360. var results = [];
  12361. this._getDescendants(results, directDecendantsOnly, function (node) {
  12362. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12363. });
  12364. return results;
  12365. };
  12366. /**
  12367. * Get all direct children of this node.
  12368. */
  12369. Node.prototype.getChildren = function (predicate) {
  12370. return this.getDescendants(true, predicate);
  12371. };
  12372. Node.prototype._setReady = function (state) {
  12373. if (state === this._isReady) {
  12374. return;
  12375. }
  12376. if (!state) {
  12377. this._isReady = false;
  12378. return;
  12379. }
  12380. this._isReady = true;
  12381. if (this.onReady) {
  12382. this.onReady(this);
  12383. }
  12384. };
  12385. Node.prototype.getAnimationByName = function (name) {
  12386. for (var i = 0; i < this.animations.length; i++) {
  12387. var animation = this.animations[i];
  12388. if (animation.name === name) {
  12389. return animation;
  12390. }
  12391. }
  12392. return null;
  12393. };
  12394. Node.prototype.createAnimationRange = function (name, from, to) {
  12395. // check name not already in use
  12396. if (!this._ranges[name]) {
  12397. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12398. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12399. if (this.animations[i]) {
  12400. this.animations[i].createRange(name, from, to);
  12401. }
  12402. }
  12403. }
  12404. };
  12405. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12406. if (deleteFrames === void 0) { deleteFrames = true; }
  12407. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12408. if (this.animations[i]) {
  12409. this.animations[i].deleteRange(name, deleteFrames);
  12410. }
  12411. }
  12412. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12413. };
  12414. Node.prototype.getAnimationRange = function (name) {
  12415. return this._ranges[name];
  12416. };
  12417. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12418. var range = this.getAnimationRange(name);
  12419. if (!range) {
  12420. return;
  12421. }
  12422. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12423. };
  12424. Node.prototype.serializeAnimationRanges = function () {
  12425. var serializationRanges = [];
  12426. for (var name in this._ranges) {
  12427. var localRange = this._ranges[name];
  12428. if (!localRange) {
  12429. continue;
  12430. }
  12431. var range = {};
  12432. range.name = name;
  12433. range.from = localRange.from;
  12434. range.to = localRange.to;
  12435. serializationRanges.push(range);
  12436. }
  12437. return serializationRanges;
  12438. };
  12439. Node.prototype.dispose = function () {
  12440. this.parent = null;
  12441. // Callback
  12442. this.onDisposeObservable.notifyObservers(this);
  12443. this.onDisposeObservable.clear();
  12444. // Behaviors
  12445. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12446. var behavior = _a[_i];
  12447. behavior.detach();
  12448. }
  12449. this._behaviors = [];
  12450. };
  12451. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12452. if (parsedNode.ranges) {
  12453. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12454. var data = parsedNode.ranges[index];
  12455. node.createAnimationRange(data.name, data.from, data.to);
  12456. }
  12457. }
  12458. };
  12459. __decorate([
  12460. BABYLON.serialize()
  12461. ], Node.prototype, "name", void 0);
  12462. __decorate([
  12463. BABYLON.serialize()
  12464. ], Node.prototype, "id", void 0);
  12465. __decorate([
  12466. BABYLON.serialize()
  12467. ], Node.prototype, "uniqueId", void 0);
  12468. __decorate([
  12469. BABYLON.serialize()
  12470. ], Node.prototype, "state", void 0);
  12471. __decorate([
  12472. BABYLON.serialize()
  12473. ], Node.prototype, "metadata", void 0);
  12474. return Node;
  12475. }());
  12476. BABYLON.Node = Node;
  12477. })(BABYLON || (BABYLON = {}));
  12478. //# sourceMappingURL=babylon.node.js.map
  12479. var BABYLON;
  12480. (function (BABYLON) {
  12481. var BoundingSphere = /** @class */ (function () {
  12482. function BoundingSphere(minimum, maximum) {
  12483. this.minimum = minimum;
  12484. this.maximum = maximum;
  12485. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12486. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12487. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12488. this.radius = distance * 0.5;
  12489. this.centerWorld = BABYLON.Vector3.Zero();
  12490. this._update(BABYLON.Matrix.Identity());
  12491. }
  12492. // Methods
  12493. BoundingSphere.prototype._update = function (world) {
  12494. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12495. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12496. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12497. };
  12498. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12499. for (var i = 0; i < 6; i++) {
  12500. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12501. return false;
  12502. }
  12503. return true;
  12504. };
  12505. BoundingSphere.prototype.intersectsPoint = function (point) {
  12506. var x = this.centerWorld.x - point.x;
  12507. var y = this.centerWorld.y - point.y;
  12508. var z = this.centerWorld.z - point.z;
  12509. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12510. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12511. return false;
  12512. return true;
  12513. };
  12514. // Statics
  12515. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12516. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12517. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12518. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12519. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12520. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12521. return false;
  12522. return true;
  12523. };
  12524. return BoundingSphere;
  12525. }());
  12526. BABYLON.BoundingSphere = BoundingSphere;
  12527. })(BABYLON || (BABYLON = {}));
  12528. //# sourceMappingURL=babylon.boundingSphere.js.map
  12529. var BABYLON;
  12530. (function (BABYLON) {
  12531. var BoundingBox = /** @class */ (function () {
  12532. function BoundingBox(minimum, maximum) {
  12533. this.minimum = minimum;
  12534. this.maximum = maximum;
  12535. this.vectors = new Array();
  12536. this.vectorsWorld = new Array();
  12537. // Bounding vectors
  12538. this.vectors.push(this.minimum.clone());
  12539. this.vectors.push(this.maximum.clone());
  12540. this.vectors.push(this.minimum.clone());
  12541. this.vectors[2].x = this.maximum.x;
  12542. this.vectors.push(this.minimum.clone());
  12543. this.vectors[3].y = this.maximum.y;
  12544. this.vectors.push(this.minimum.clone());
  12545. this.vectors[4].z = this.maximum.z;
  12546. this.vectors.push(this.maximum.clone());
  12547. this.vectors[5].z = this.minimum.z;
  12548. this.vectors.push(this.maximum.clone());
  12549. this.vectors[6].x = this.minimum.x;
  12550. this.vectors.push(this.maximum.clone());
  12551. this.vectors[7].y = this.minimum.y;
  12552. // OBB
  12553. this.center = this.maximum.add(this.minimum).scale(0.5);
  12554. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12555. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12556. // World
  12557. for (var index = 0; index < this.vectors.length; index++) {
  12558. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12559. }
  12560. this.minimumWorld = BABYLON.Vector3.Zero();
  12561. this.maximumWorld = BABYLON.Vector3.Zero();
  12562. this.centerWorld = BABYLON.Vector3.Zero();
  12563. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12564. this._update(BABYLON.Matrix.Identity());
  12565. }
  12566. // Methods
  12567. BoundingBox.prototype.getWorldMatrix = function () {
  12568. return this._worldMatrix;
  12569. };
  12570. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12571. this._worldMatrix.copyFrom(matrix);
  12572. return this;
  12573. };
  12574. BoundingBox.prototype._update = function (world) {
  12575. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12576. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12577. for (var index = 0; index < this.vectors.length; index++) {
  12578. var v = this.vectorsWorld[index];
  12579. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12580. if (v.x < this.minimumWorld.x)
  12581. this.minimumWorld.x = v.x;
  12582. if (v.y < this.minimumWorld.y)
  12583. this.minimumWorld.y = v.y;
  12584. if (v.z < this.minimumWorld.z)
  12585. this.minimumWorld.z = v.z;
  12586. if (v.x > this.maximumWorld.x)
  12587. this.maximumWorld.x = v.x;
  12588. if (v.y > this.maximumWorld.y)
  12589. this.maximumWorld.y = v.y;
  12590. if (v.z > this.maximumWorld.z)
  12591. this.maximumWorld.z = v.z;
  12592. }
  12593. // Extend
  12594. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12595. this.extendSizeWorld.scaleInPlace(0.5);
  12596. // OBB
  12597. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12598. this.centerWorld.scaleInPlace(0.5);
  12599. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12600. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12601. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12602. this._worldMatrix = world;
  12603. };
  12604. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12605. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12606. };
  12607. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12608. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12609. };
  12610. BoundingBox.prototype.intersectsPoint = function (point) {
  12611. var delta = -BABYLON.Epsilon;
  12612. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12613. return false;
  12614. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12615. return false;
  12616. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12617. return false;
  12618. return true;
  12619. };
  12620. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12621. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12622. };
  12623. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12624. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12625. return false;
  12626. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12627. return false;
  12628. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12629. return false;
  12630. return true;
  12631. };
  12632. // Statics
  12633. BoundingBox.Intersects = function (box0, box1) {
  12634. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12635. return false;
  12636. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12637. return false;
  12638. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12639. return false;
  12640. return true;
  12641. };
  12642. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12643. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12644. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12645. return (num <= (sphereRadius * sphereRadius));
  12646. };
  12647. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12648. for (var p = 0; p < 6; p++) {
  12649. for (var i = 0; i < 8; i++) {
  12650. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12651. return false;
  12652. }
  12653. }
  12654. }
  12655. return true;
  12656. };
  12657. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12658. for (var p = 0; p < 6; p++) {
  12659. var inCount = 8;
  12660. for (var i = 0; i < 8; i++) {
  12661. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12662. --inCount;
  12663. }
  12664. else {
  12665. break;
  12666. }
  12667. }
  12668. if (inCount === 0)
  12669. return false;
  12670. }
  12671. return true;
  12672. };
  12673. return BoundingBox;
  12674. }());
  12675. BABYLON.BoundingBox = BoundingBox;
  12676. })(BABYLON || (BABYLON = {}));
  12677. //# sourceMappingURL=babylon.boundingBox.js.map
  12678. var BABYLON;
  12679. (function (BABYLON) {
  12680. var computeBoxExtents = function (axis, box) {
  12681. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12682. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12683. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12684. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12685. var r = r0 + r1 + r2;
  12686. return {
  12687. min: p - r,
  12688. max: p + r
  12689. };
  12690. };
  12691. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12692. var axisOverlap = function (axis, box0, box1) {
  12693. var result0 = computeBoxExtents(axis, box0);
  12694. var result1 = computeBoxExtents(axis, box1);
  12695. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12696. };
  12697. var BoundingInfo = /** @class */ (function () {
  12698. function BoundingInfo(minimum, maximum) {
  12699. this.minimum = minimum;
  12700. this.maximum = maximum;
  12701. this._isLocked = false;
  12702. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12703. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12704. }
  12705. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12706. get: function () {
  12707. return this._isLocked;
  12708. },
  12709. set: function (value) {
  12710. this._isLocked = value;
  12711. },
  12712. enumerable: true,
  12713. configurable: true
  12714. });
  12715. // Methods
  12716. BoundingInfo.prototype.update = function (world) {
  12717. if (this._isLocked) {
  12718. return;
  12719. }
  12720. this.boundingBox._update(world);
  12721. this.boundingSphere._update(world);
  12722. };
  12723. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12724. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12725. return false;
  12726. return this.boundingBox.isInFrustum(frustumPlanes);
  12727. };
  12728. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12729. /**
  12730. * Gets the world distance between the min and max points of the bounding box
  12731. */
  12732. get: function () {
  12733. var boundingBox = this.boundingBox;
  12734. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12735. return size.length();
  12736. },
  12737. enumerable: true,
  12738. configurable: true
  12739. });
  12740. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12741. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12742. };
  12743. BoundingInfo.prototype._checkCollision = function (collider) {
  12744. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12745. };
  12746. BoundingInfo.prototype.intersectsPoint = function (point) {
  12747. if (!this.boundingSphere.centerWorld) {
  12748. return false;
  12749. }
  12750. if (!this.boundingSphere.intersectsPoint(point)) {
  12751. return false;
  12752. }
  12753. if (!this.boundingBox.intersectsPoint(point)) {
  12754. return false;
  12755. }
  12756. return true;
  12757. };
  12758. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12759. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12760. return false;
  12761. }
  12762. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12763. return false;
  12764. }
  12765. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12766. return false;
  12767. }
  12768. if (!precise) {
  12769. return true;
  12770. }
  12771. var box0 = this.boundingBox;
  12772. var box1 = boundingInfo.boundingBox;
  12773. if (!axisOverlap(box0.directions[0], box0, box1))
  12774. return false;
  12775. if (!axisOverlap(box0.directions[1], box0, box1))
  12776. return false;
  12777. if (!axisOverlap(box0.directions[2], box0, box1))
  12778. return false;
  12779. if (!axisOverlap(box1.directions[0], box0, box1))
  12780. return false;
  12781. if (!axisOverlap(box1.directions[1], box0, box1))
  12782. return false;
  12783. if (!axisOverlap(box1.directions[2], box0, box1))
  12784. return false;
  12785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12786. return false;
  12787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12788. return false;
  12789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12790. return false;
  12791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12792. return false;
  12793. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12794. return false;
  12795. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12796. return false;
  12797. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12798. return false;
  12799. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12800. return false;
  12801. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12802. return false;
  12803. return true;
  12804. };
  12805. return BoundingInfo;
  12806. }());
  12807. BABYLON.BoundingInfo = BoundingInfo;
  12808. })(BABYLON || (BABYLON = {}));
  12809. //# sourceMappingURL=babylon.boundingInfo.js.map
  12810. var BABYLON;
  12811. (function (BABYLON) {
  12812. var AbstractMesh = /** @class */ (function (_super) {
  12813. __extends(AbstractMesh, _super);
  12814. // Constructor
  12815. function AbstractMesh(name, scene) {
  12816. if (scene === void 0) { scene = null; }
  12817. var _this = _super.call(this, name, scene) || this;
  12818. _this._facetNb = 0; // facet number
  12819. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12820. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12821. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12822. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12823. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12824. _this._subDiv = {
  12825. max: 1,
  12826. X: 1,
  12827. Y: 1,
  12828. Z: 1
  12829. };
  12830. // Normal matrix
  12831. _this._nonUniformScaling = false;
  12832. // Events
  12833. /**
  12834. * An event triggered when this mesh collides with another one
  12835. * @type {BABYLON.Observable}
  12836. */
  12837. _this.onCollideObservable = new BABYLON.Observable();
  12838. /**
  12839. * An event triggered when the collision's position changes
  12840. * @type {BABYLON.Observable}
  12841. */
  12842. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12843. /**
  12844. * An event triggered after the world matrix is updated
  12845. * @type {BABYLON.Observable}
  12846. */
  12847. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12848. /**
  12849. * An event triggered when material is changed
  12850. * @type {BABYLON.Observable}
  12851. */
  12852. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12853. // Properties
  12854. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12855. _this.position = BABYLON.Vector3.Zero();
  12856. /**
  12857. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12858. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12859. * or
  12860. * 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.
  12861. * for more info check WebGl documentations
  12862. */
  12863. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12864. /**
  12865. * 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:
  12866. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12867. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12868. * 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.
  12869. */
  12870. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12871. /**
  12872. * 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.
  12873. * The default value is -1 which means don't break the query and wait till the result.
  12874. */
  12875. _this.occlusionRetryCount = -1;
  12876. _this._occlusionInternalRetryCounter = 0;
  12877. _this._isOccluded = false;
  12878. _this._isOcclusionQueryInProgress = false;
  12879. _this._rotation = BABYLON.Vector3.Zero();
  12880. _this._scaling = BABYLON.Vector3.One();
  12881. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12882. _this.visibility = 1.0;
  12883. _this.alphaIndex = Number.MAX_VALUE;
  12884. _this.infiniteDistance = false;
  12885. _this.isVisible = true;
  12886. _this.isPickable = true;
  12887. _this.showBoundingBox = false;
  12888. _this.showSubMeshesBoundingBox = false;
  12889. _this.isBlocker = false;
  12890. _this.enablePointerMoveEvents = false;
  12891. _this.renderingGroupId = 0;
  12892. _this._receiveShadows = false;
  12893. _this.renderOutline = false;
  12894. _this.outlineColor = BABYLON.Color3.Red();
  12895. _this.outlineWidth = 0.02;
  12896. _this.renderOverlay = false;
  12897. _this.overlayColor = BABYLON.Color3.Red();
  12898. _this.overlayAlpha = 0.5;
  12899. _this._hasVertexAlpha = false;
  12900. _this._useVertexColors = true;
  12901. _this._computeBonesUsingShaders = true;
  12902. _this._numBoneInfluencers = 4;
  12903. _this._applyFog = true;
  12904. _this.scalingDeterminant = 1;
  12905. _this.useOctreeForRenderingSelection = true;
  12906. _this.useOctreeForPicking = true;
  12907. _this.useOctreeForCollisions = true;
  12908. _this._layerMask = 0x0FFFFFFF;
  12909. /**
  12910. * True if the mesh must be rendered in any case.
  12911. */
  12912. _this.alwaysSelectAsActiveMesh = false;
  12913. // Collisions
  12914. _this._checkCollisions = false;
  12915. _this._collisionMask = -1;
  12916. _this._collisionGroup = -1;
  12917. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12918. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12919. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12920. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12921. // Edges
  12922. _this.edgesWidth = 1;
  12923. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12924. // Cache
  12925. _this._localWorld = BABYLON.Matrix.Zero();
  12926. _this._worldMatrix = BABYLON.Matrix.Zero();
  12927. _this._absolutePosition = BABYLON.Vector3.Zero();
  12928. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12929. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12930. _this._isDirty = false;
  12931. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12932. _this._postMultiplyPivotMatrix = false;
  12933. _this._isDisposed = false;
  12934. _this._renderId = 0;
  12935. _this._intersectionsInProgress = new Array();
  12936. _this._isWorldMatrixFrozen = false;
  12937. _this._unIndexed = false;
  12938. _this._lightSources = new Array();
  12939. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12940. if (collidedMesh === void 0) { collidedMesh = null; }
  12941. //TODO move this to the collision coordinator!
  12942. if (_this.getScene().workerCollisions)
  12943. newPosition.multiplyInPlace(_this._collider.radius);
  12944. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12945. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12946. _this.position.addInPlace(_this._diffPositionForCollisions);
  12947. }
  12948. if (collidedMesh) {
  12949. _this.onCollideObservable.notifyObservers(collidedMesh);
  12950. }
  12951. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12952. };
  12953. _this.getScene().addMesh(_this);
  12954. _this._resyncLightSources();
  12955. return _this;
  12956. }
  12957. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12958. get: function () {
  12959. return AbstractMesh._BILLBOARDMODE_NONE;
  12960. },
  12961. enumerable: true,
  12962. configurable: true
  12963. });
  12964. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12965. get: function () {
  12966. return AbstractMesh._BILLBOARDMODE_X;
  12967. },
  12968. enumerable: true,
  12969. configurable: true
  12970. });
  12971. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12972. get: function () {
  12973. return AbstractMesh._BILLBOARDMODE_Y;
  12974. },
  12975. enumerable: true,
  12976. configurable: true
  12977. });
  12978. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12979. get: function () {
  12980. return AbstractMesh._BILLBOARDMODE_Z;
  12981. },
  12982. enumerable: true,
  12983. configurable: true
  12984. });
  12985. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12986. get: function () {
  12987. return AbstractMesh._BILLBOARDMODE_ALL;
  12988. },
  12989. enumerable: true,
  12990. configurable: true
  12991. });
  12992. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12993. /**
  12994. * Read-only : the number of facets in the mesh
  12995. */
  12996. get: function () {
  12997. return this._facetNb;
  12998. },
  12999. enumerable: true,
  13000. configurable: true
  13001. });
  13002. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13003. /**
  13004. * The number (integer) of subdivisions per axis in the partioning space
  13005. */
  13006. get: function () {
  13007. return this._partitioningSubdivisions;
  13008. },
  13009. set: function (nb) {
  13010. this._partitioningSubdivisions = nb;
  13011. },
  13012. enumerable: true,
  13013. configurable: true
  13014. });
  13015. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13016. /**
  13017. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13018. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13019. */
  13020. get: function () {
  13021. return this._partitioningBBoxRatio;
  13022. },
  13023. set: function (ratio) {
  13024. this._partitioningBBoxRatio = ratio;
  13025. },
  13026. enumerable: true,
  13027. configurable: true
  13028. });
  13029. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13030. /**
  13031. * Read-only boolean : is the feature facetData enabled ?
  13032. */
  13033. get: function () {
  13034. return this._facetDataEnabled;
  13035. },
  13036. enumerable: true,
  13037. configurable: true
  13038. });
  13039. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13040. get: function () {
  13041. return this._nonUniformScaling;
  13042. },
  13043. set: function (value) {
  13044. if (this._nonUniformScaling === value) {
  13045. return;
  13046. }
  13047. this._nonUniformScaling = true;
  13048. this._markSubMeshesAsMiscDirty();
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13054. set: function (callback) {
  13055. if (this._onCollideObserver) {
  13056. this.onCollideObservable.remove(this._onCollideObserver);
  13057. }
  13058. this._onCollideObserver = this.onCollideObservable.add(callback);
  13059. },
  13060. enumerable: true,
  13061. configurable: true
  13062. });
  13063. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13064. set: function (callback) {
  13065. if (this._onCollisionPositionChangeObserver) {
  13066. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13067. }
  13068. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13074. /**
  13075. * 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.
  13076. */
  13077. get: function () {
  13078. return this._isOccluded;
  13079. },
  13080. set: function (value) {
  13081. this._isOccluded = value;
  13082. },
  13083. enumerable: true,
  13084. configurable: true
  13085. });
  13086. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13087. /**
  13088. * Flag to check the progress status of the query
  13089. */
  13090. get: function () {
  13091. return this._isOcclusionQueryInProgress;
  13092. },
  13093. enumerable: true,
  13094. configurable: true
  13095. });
  13096. Object.defineProperty(AbstractMesh.prototype, "material", {
  13097. get: function () {
  13098. return this._material;
  13099. },
  13100. set: function (value) {
  13101. if (this._material === value) {
  13102. return;
  13103. }
  13104. this._material = value;
  13105. if (this.onMaterialChangedObservable.hasObservers) {
  13106. this.onMaterialChangedObservable.notifyObservers(this);
  13107. }
  13108. if (!this.subMeshes) {
  13109. return;
  13110. }
  13111. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13112. var subMesh = _a[_i];
  13113. subMesh.setEffect(null);
  13114. }
  13115. },
  13116. enumerable: true,
  13117. configurable: true
  13118. });
  13119. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13120. get: function () {
  13121. return this._receiveShadows;
  13122. },
  13123. set: function (value) {
  13124. if (this._receiveShadows === value) {
  13125. return;
  13126. }
  13127. this._receiveShadows = value;
  13128. this._markSubMeshesAsLightDirty();
  13129. },
  13130. enumerable: true,
  13131. configurable: true
  13132. });
  13133. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13134. get: function () {
  13135. return this._hasVertexAlpha;
  13136. },
  13137. set: function (value) {
  13138. if (this._hasVertexAlpha === value) {
  13139. return;
  13140. }
  13141. this._hasVertexAlpha = value;
  13142. this._markSubMeshesAsAttributesDirty();
  13143. },
  13144. enumerable: true,
  13145. configurable: true
  13146. });
  13147. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13148. get: function () {
  13149. return this._useVertexColors;
  13150. },
  13151. set: function (value) {
  13152. if (this._useVertexColors === value) {
  13153. return;
  13154. }
  13155. this._useVertexColors = value;
  13156. this._markSubMeshesAsAttributesDirty();
  13157. },
  13158. enumerable: true,
  13159. configurable: true
  13160. });
  13161. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13162. get: function () {
  13163. return this._computeBonesUsingShaders;
  13164. },
  13165. set: function (value) {
  13166. if (this._computeBonesUsingShaders === value) {
  13167. return;
  13168. }
  13169. this._computeBonesUsingShaders = value;
  13170. this._markSubMeshesAsAttributesDirty();
  13171. },
  13172. enumerable: true,
  13173. configurable: true
  13174. });
  13175. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13176. get: function () {
  13177. return this._numBoneInfluencers;
  13178. },
  13179. set: function (value) {
  13180. if (this._numBoneInfluencers === value) {
  13181. return;
  13182. }
  13183. this._numBoneInfluencers = value;
  13184. this._markSubMeshesAsAttributesDirty();
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13190. get: function () {
  13191. return this._applyFog;
  13192. },
  13193. set: function (value) {
  13194. if (this._applyFog === value) {
  13195. return;
  13196. }
  13197. this._applyFog = value;
  13198. this._markSubMeshesAsMiscDirty();
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13204. get: function () {
  13205. return this._layerMask;
  13206. },
  13207. set: function (value) {
  13208. if (value === this._layerMask) {
  13209. return;
  13210. }
  13211. this._layerMask = value;
  13212. this._resyncLightSources();
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13218. get: function () {
  13219. return this._collisionMask;
  13220. },
  13221. set: function (mask) {
  13222. this._collisionMask = !isNaN(mask) ? mask : -1;
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13228. get: function () {
  13229. return this._collisionGroup;
  13230. },
  13231. set: function (mask) {
  13232. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13238. get: function () {
  13239. return null;
  13240. },
  13241. enumerable: true,
  13242. configurable: true
  13243. });
  13244. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13245. get: function () {
  13246. return this._skeleton;
  13247. },
  13248. set: function (value) {
  13249. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13250. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13251. }
  13252. if (value && value.needInitialSkinMatrix) {
  13253. value._registerMeshWithPoseMatrix(this);
  13254. }
  13255. this._skeleton = value;
  13256. if (!this._skeleton) {
  13257. this._bonesTransformMatrices = null;
  13258. }
  13259. this._markSubMeshesAsAttributesDirty();
  13260. },
  13261. enumerable: true,
  13262. configurable: true
  13263. });
  13264. /**
  13265. * Boolean : true if the mesh has been disposed.
  13266. */
  13267. AbstractMesh.prototype.isDisposed = function () {
  13268. return this._isDisposed;
  13269. };
  13270. /**
  13271. * Returns the string "AbstractMesh"
  13272. */
  13273. AbstractMesh.prototype.getClassName = function () {
  13274. return "AbstractMesh";
  13275. };
  13276. /**
  13277. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13278. */
  13279. AbstractMesh.prototype.toString = function (fullDetails) {
  13280. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13281. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13282. if (this._skeleton) {
  13283. ret += ", skeleton: " + this._skeleton.name;
  13284. }
  13285. if (fullDetails) {
  13286. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13287. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13288. }
  13289. return ret;
  13290. };
  13291. AbstractMesh.prototype._rebuild = function () {
  13292. if (this._occlusionQuery) {
  13293. this._occlusionQuery = null;
  13294. }
  13295. if (this._edgesRenderer) {
  13296. this._edgesRenderer._rebuild();
  13297. }
  13298. if (!this.subMeshes) {
  13299. return;
  13300. }
  13301. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13302. var subMesh = _a[_i];
  13303. subMesh._rebuild();
  13304. }
  13305. };
  13306. AbstractMesh.prototype._resyncLightSources = function () {
  13307. this._lightSources.length = 0;
  13308. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13309. var light = _a[_i];
  13310. if (!light.isEnabled()) {
  13311. continue;
  13312. }
  13313. if (light.canAffectMesh(this)) {
  13314. this._lightSources.push(light);
  13315. }
  13316. }
  13317. this._markSubMeshesAsLightDirty();
  13318. };
  13319. AbstractMesh.prototype._resyncLighSource = function (light) {
  13320. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13321. var index = this._lightSources.indexOf(light);
  13322. if (index === -1) {
  13323. if (!isIn) {
  13324. return;
  13325. }
  13326. this._lightSources.push(light);
  13327. }
  13328. else {
  13329. if (isIn) {
  13330. return;
  13331. }
  13332. this._lightSources.splice(index, 1);
  13333. }
  13334. this._markSubMeshesAsLightDirty();
  13335. };
  13336. AbstractMesh.prototype._removeLightSource = function (light) {
  13337. var index = this._lightSources.indexOf(light);
  13338. if (index === -1) {
  13339. return;
  13340. }
  13341. this._lightSources.splice(index, 1);
  13342. };
  13343. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13344. if (!this.subMeshes) {
  13345. return;
  13346. }
  13347. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13348. var subMesh = _a[_i];
  13349. if (subMesh._materialDefines) {
  13350. func(subMesh._materialDefines);
  13351. }
  13352. }
  13353. };
  13354. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13355. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13356. };
  13357. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13358. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13359. };
  13360. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13361. if (!this.subMeshes) {
  13362. return;
  13363. }
  13364. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13365. var subMesh = _a[_i];
  13366. var material = subMesh.getMaterial();
  13367. if (material) {
  13368. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13369. }
  13370. }
  13371. };
  13372. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13373. /**
  13374. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13375. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13376. * Default : (0.0, 0.0, 0.0)
  13377. */
  13378. get: function () {
  13379. return this._rotation;
  13380. },
  13381. set: function (newRotation) {
  13382. this._rotation = newRotation;
  13383. },
  13384. enumerable: true,
  13385. configurable: true
  13386. });
  13387. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13388. /**
  13389. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13390. * Default : (1.0, 1.0, 1.0)
  13391. */
  13392. get: function () {
  13393. return this._scaling;
  13394. },
  13395. set: function (newScaling) {
  13396. this._scaling = newScaling;
  13397. if (this.physicsImpostor) {
  13398. this.physicsImpostor.forceUpdate();
  13399. }
  13400. },
  13401. enumerable: true,
  13402. configurable: true
  13403. });
  13404. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13405. /**
  13406. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13407. * It's null by default.
  13408. * 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)
  13409. */
  13410. get: function () {
  13411. return this._rotationQuaternion;
  13412. },
  13413. set: function (quaternion) {
  13414. this._rotationQuaternion = quaternion;
  13415. //reset the rotation vector.
  13416. if (quaternion && this.rotation.length()) {
  13417. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13418. }
  13419. },
  13420. enumerable: true,
  13421. configurable: true
  13422. });
  13423. // Methods
  13424. /**
  13425. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13426. * Returns the AbstractMesh.
  13427. */
  13428. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13429. this._poseMatrix.copyFrom(matrix);
  13430. return this;
  13431. };
  13432. /**
  13433. * Returns the mesh Pose matrix.
  13434. * Returned object : Matrix
  13435. */
  13436. AbstractMesh.prototype.getPoseMatrix = function () {
  13437. return this._poseMatrix;
  13438. };
  13439. /**
  13440. * Disables the mesh edger rendering mode.
  13441. * Returns the AbstractMesh.
  13442. */
  13443. AbstractMesh.prototype.disableEdgesRendering = function () {
  13444. if (this._edgesRenderer) {
  13445. this._edgesRenderer.dispose();
  13446. this._edgesRenderer = null;
  13447. }
  13448. return this;
  13449. };
  13450. /**
  13451. * Enables the edge rendering mode on the mesh.
  13452. * This mode makes the mesh edges visible.
  13453. * Returns the AbstractMesh.
  13454. */
  13455. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13456. if (epsilon === void 0) { epsilon = 0.95; }
  13457. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13458. this.disableEdgesRendering();
  13459. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13460. return this;
  13461. };
  13462. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13463. /**
  13464. * Returns true if the mesh is blocked. Used by the class Mesh.
  13465. * Returns the boolean `false` by default.
  13466. */
  13467. get: function () {
  13468. return false;
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. /**
  13474. * Returns the mesh itself by default, used by the class Mesh.
  13475. * Returned type : AbstractMesh
  13476. */
  13477. AbstractMesh.prototype.getLOD = function (camera) {
  13478. return this;
  13479. };
  13480. /**
  13481. * Returns 0 by default, used by the class Mesh.
  13482. * Returns an integer.
  13483. */
  13484. AbstractMesh.prototype.getTotalVertices = function () {
  13485. return 0;
  13486. };
  13487. /**
  13488. * Returns null by default, used by the class Mesh.
  13489. * Returned type : integer array
  13490. */
  13491. AbstractMesh.prototype.getIndices = function () {
  13492. return null;
  13493. };
  13494. /**
  13495. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13496. * Returned type : float array or Float32Array
  13497. */
  13498. AbstractMesh.prototype.getVerticesData = function (kind) {
  13499. return null;
  13500. };
  13501. /**
  13502. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13503. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13504. * The `data` are either a numeric array either a Float32Array.
  13505. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13506. * 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).
  13507. * Note that a new underlying VertexBuffer object is created each call.
  13508. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13509. *
  13510. * Possible `kind` values :
  13511. * - BABYLON.VertexBuffer.PositionKind
  13512. * - BABYLON.VertexBuffer.UVKind
  13513. * - BABYLON.VertexBuffer.UV2Kind
  13514. * - BABYLON.VertexBuffer.UV3Kind
  13515. * - BABYLON.VertexBuffer.UV4Kind
  13516. * - BABYLON.VertexBuffer.UV5Kind
  13517. * - BABYLON.VertexBuffer.UV6Kind
  13518. * - BABYLON.VertexBuffer.ColorKind
  13519. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13520. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13521. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13522. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13523. *
  13524. * Returns the Mesh.
  13525. */
  13526. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13527. return this;
  13528. };
  13529. /**
  13530. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13531. * If the mesh has no geometry, it is simply returned as it is.
  13532. * The `data` are either a numeric array either a Float32Array.
  13533. * No new underlying VertexBuffer object is created.
  13534. * 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.
  13535. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13536. *
  13537. * Possible `kind` values :
  13538. * - BABYLON.VertexBuffer.PositionKind
  13539. * - BABYLON.VertexBuffer.UVKind
  13540. * - BABYLON.VertexBuffer.UV2Kind
  13541. * - BABYLON.VertexBuffer.UV3Kind
  13542. * - BABYLON.VertexBuffer.UV4Kind
  13543. * - BABYLON.VertexBuffer.UV5Kind
  13544. * - BABYLON.VertexBuffer.UV6Kind
  13545. * - BABYLON.VertexBuffer.ColorKind
  13546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13550. *
  13551. * Returns the Mesh.
  13552. */
  13553. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13554. return this;
  13555. };
  13556. /**
  13557. * Sets the mesh indices.
  13558. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13559. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13560. * This method creates a new index buffer each call.
  13561. * Returns the Mesh.
  13562. */
  13563. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13564. return this;
  13565. };
  13566. /** Returns false by default, used by the class Mesh.
  13567. * Returns a boolean
  13568. */
  13569. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13570. return false;
  13571. };
  13572. /**
  13573. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13574. * Returns a BoundingInfo
  13575. */
  13576. AbstractMesh.prototype.getBoundingInfo = function () {
  13577. if (this._masterMesh) {
  13578. return this._masterMesh.getBoundingInfo();
  13579. }
  13580. if (!this._boundingInfo) {
  13581. this._updateBoundingInfo();
  13582. }
  13583. return this._boundingInfo;
  13584. };
  13585. /**
  13586. * Sets a mesh new object BoundingInfo.
  13587. * Returns the AbstractMesh.
  13588. */
  13589. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13590. this._boundingInfo = boundingInfo;
  13591. return this;
  13592. };
  13593. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13594. get: function () {
  13595. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13596. },
  13597. enumerable: true,
  13598. configurable: true
  13599. });
  13600. AbstractMesh.prototype._preActivate = function () {
  13601. };
  13602. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13603. };
  13604. AbstractMesh.prototype._activate = function (renderId) {
  13605. this._renderId = renderId;
  13606. };
  13607. /**
  13608. * Returns the last update of the World matrix
  13609. * Returns a Matrix.
  13610. */
  13611. AbstractMesh.prototype.getWorldMatrix = function () {
  13612. if (this._masterMesh) {
  13613. return this._masterMesh.getWorldMatrix();
  13614. }
  13615. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13616. this.computeWorldMatrix();
  13617. }
  13618. return this._worldMatrix;
  13619. };
  13620. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13621. /**
  13622. * Returns directly the last state of the mesh World matrix.
  13623. * A Matrix is returned.
  13624. */
  13625. get: function () {
  13626. return this._worldMatrix;
  13627. },
  13628. enumerable: true,
  13629. configurable: true
  13630. });
  13631. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13632. /**
  13633. * Returns the current mesh absolute position.
  13634. * Retuns a Vector3.
  13635. */
  13636. get: function () {
  13637. return this._absolutePosition;
  13638. },
  13639. enumerable: true,
  13640. configurable: true
  13641. });
  13642. /**
  13643. * Prevents the World matrix to be computed any longer.
  13644. * Returns the AbstractMesh.
  13645. */
  13646. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13647. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13648. this.computeWorldMatrix(true);
  13649. this._isWorldMatrixFrozen = true;
  13650. return this;
  13651. };
  13652. /**
  13653. * Allows back the World matrix computation.
  13654. * Returns the AbstractMesh.
  13655. */
  13656. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13657. this._isWorldMatrixFrozen = false;
  13658. this.computeWorldMatrix(true);
  13659. return this;
  13660. };
  13661. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13662. /**
  13663. * True if the World matrix has been frozen.
  13664. * Returns a boolean.
  13665. */
  13666. get: function () {
  13667. return this._isWorldMatrixFrozen;
  13668. },
  13669. enumerable: true,
  13670. configurable: true
  13671. });
  13672. /**
  13673. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13674. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13675. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13676. * The passed axis is also normalized.
  13677. * Returns the AbstractMesh.
  13678. */
  13679. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13680. axis.normalize();
  13681. if (!this.rotationQuaternion) {
  13682. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13683. this.rotation = BABYLON.Vector3.Zero();
  13684. }
  13685. var rotationQuaternion;
  13686. if (!space || space === BABYLON.Space.LOCAL) {
  13687. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13688. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13689. }
  13690. else {
  13691. if (this.parent) {
  13692. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13693. invertParentWorldMatrix.invert();
  13694. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13695. }
  13696. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13697. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13698. }
  13699. return this;
  13700. };
  13701. /**
  13702. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13703. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13704. * The passed axis is also normalized.
  13705. * Returns the AbstractMesh.
  13706. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13707. */
  13708. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13709. axis.normalize();
  13710. if (!this.rotationQuaternion) {
  13711. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13712. this.rotation.copyFromFloats(0, 0, 0);
  13713. }
  13714. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13715. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13716. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13717. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13718. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13719. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13720. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13721. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13722. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13723. return this;
  13724. };
  13725. /**
  13726. * Translates the mesh along the axis vector for the passed distance in the given space.
  13727. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13728. * Returns the AbstractMesh.
  13729. */
  13730. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13731. var displacementVector = axis.scale(distance);
  13732. if (!space || space === BABYLON.Space.LOCAL) {
  13733. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13734. this.setPositionWithLocalVector(tempV3);
  13735. }
  13736. else {
  13737. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13738. }
  13739. return this;
  13740. };
  13741. /**
  13742. * Adds a rotation step to the mesh current rotation.
  13743. * x, y, z are Euler angles expressed in radians.
  13744. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13745. * This means this rotation is made in the mesh local space only.
  13746. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13747. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13748. * ```javascript
  13749. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13750. * ```
  13751. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13752. * 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.
  13753. * Returns the AbstractMesh.
  13754. */
  13755. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13756. var rotationQuaternion;
  13757. if (this.rotationQuaternion) {
  13758. rotationQuaternion = this.rotationQuaternion;
  13759. }
  13760. else {
  13761. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13762. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13763. }
  13764. var accumulation = BABYLON.Tmp.Quaternion[0];
  13765. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13766. rotationQuaternion.multiplyInPlace(accumulation);
  13767. if (!this.rotationQuaternion) {
  13768. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13769. }
  13770. return this;
  13771. };
  13772. /**
  13773. * Retuns the mesh absolute position in the World.
  13774. * Returns a Vector3.
  13775. */
  13776. AbstractMesh.prototype.getAbsolutePosition = function () {
  13777. this.computeWorldMatrix();
  13778. return this._absolutePosition;
  13779. };
  13780. /**
  13781. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13782. * Returns the AbstractMesh.
  13783. */
  13784. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13785. if (!absolutePosition) {
  13786. return this;
  13787. }
  13788. var absolutePositionX;
  13789. var absolutePositionY;
  13790. var absolutePositionZ;
  13791. if (absolutePosition.x === undefined) {
  13792. if (arguments.length < 3) {
  13793. return this;
  13794. }
  13795. absolutePositionX = arguments[0];
  13796. absolutePositionY = arguments[1];
  13797. absolutePositionZ = arguments[2];
  13798. }
  13799. else {
  13800. absolutePositionX = absolutePosition.x;
  13801. absolutePositionY = absolutePosition.y;
  13802. absolutePositionZ = absolutePosition.z;
  13803. }
  13804. if (this.parent) {
  13805. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13806. invertParentWorldMatrix.invert();
  13807. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13808. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13809. }
  13810. else {
  13811. this.position.x = absolutePositionX;
  13812. this.position.y = absolutePositionY;
  13813. this.position.z = absolutePositionZ;
  13814. }
  13815. return this;
  13816. };
  13817. // ================================== Point of View Movement =================================
  13818. /**
  13819. * Perform relative position change from the point of view of behind the front of the mesh.
  13820. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13821. * Supports definition of mesh facing forward or backward.
  13822. * @param {number} amountRight
  13823. * @param {number} amountUp
  13824. * @param {number} amountForward
  13825. *
  13826. * Returns the AbstractMesh.
  13827. */
  13828. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13829. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13830. return this;
  13831. };
  13832. /**
  13833. * Calculate relative position change from the point of view of behind the front of the mesh.
  13834. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13835. * Supports definition of mesh facing forward or backward.
  13836. * @param {number} amountRight
  13837. * @param {number} amountUp
  13838. * @param {number} amountForward
  13839. *
  13840. * Returns a new Vector3.
  13841. */
  13842. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13843. var rotMatrix = new BABYLON.Matrix();
  13844. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13845. rotQuaternion.toRotationMatrix(rotMatrix);
  13846. var translationDelta = BABYLON.Vector3.Zero();
  13847. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13848. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13849. return translationDelta;
  13850. };
  13851. // ================================== Point of View Rotation =================================
  13852. /**
  13853. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13854. * Supports definition of mesh facing forward or backward.
  13855. * @param {number} flipBack
  13856. * @param {number} twirlClockwise
  13857. * @param {number} tiltRight
  13858. *
  13859. * Returns the AbstractMesh.
  13860. */
  13861. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13862. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13863. return this;
  13864. };
  13865. /**
  13866. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13867. * Supports definition of mesh facing forward or backward.
  13868. * @param {number} flipBack
  13869. * @param {number} twirlClockwise
  13870. * @param {number} tiltRight
  13871. *
  13872. * Returns a new Vector3.
  13873. */
  13874. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13875. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13876. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13877. };
  13878. /**
  13879. * Sets a new pivot matrix to the mesh.
  13880. * Returns the AbstractMesh.
  13881. */
  13882. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13883. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13884. this._pivotMatrix = matrix.clone();
  13885. this._cache.pivotMatrixUpdated = true;
  13886. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13887. if (this._postMultiplyPivotMatrix) {
  13888. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13889. }
  13890. return this;
  13891. };
  13892. /**
  13893. * Returns the mesh pivot matrix.
  13894. * Default : Identity.
  13895. * A Matrix is returned.
  13896. */
  13897. AbstractMesh.prototype.getPivotMatrix = function () {
  13898. return this._pivotMatrix;
  13899. };
  13900. AbstractMesh.prototype._isSynchronized = function () {
  13901. if (this._isDirty) {
  13902. return false;
  13903. }
  13904. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13905. return false;
  13906. if (this._cache.pivotMatrixUpdated) {
  13907. return false;
  13908. }
  13909. if (this.infiniteDistance) {
  13910. return false;
  13911. }
  13912. if (!this._cache.position.equals(this.position))
  13913. return false;
  13914. if (this.rotationQuaternion) {
  13915. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13916. return false;
  13917. }
  13918. if (!this._cache.rotation.equals(this.rotation))
  13919. return false;
  13920. if (!this._cache.scaling.equals(this.scaling))
  13921. return false;
  13922. return true;
  13923. };
  13924. AbstractMesh.prototype._initCache = function () {
  13925. _super.prototype._initCache.call(this);
  13926. this._cache.localMatrixUpdated = false;
  13927. this._cache.position = BABYLON.Vector3.Zero();
  13928. this._cache.scaling = BABYLON.Vector3.Zero();
  13929. this._cache.rotation = BABYLON.Vector3.Zero();
  13930. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13931. this._cache.billboardMode = -1;
  13932. };
  13933. AbstractMesh.prototype.markAsDirty = function (property) {
  13934. if (property === "rotation") {
  13935. this.rotationQuaternion = null;
  13936. }
  13937. this._currentRenderId = Number.MAX_VALUE;
  13938. this._isDirty = true;
  13939. return this;
  13940. };
  13941. /**
  13942. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13943. */
  13944. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13945. this.computeWorldMatrix(true);
  13946. var min;
  13947. var max;
  13948. var boundingInfo = this.getBoundingInfo();
  13949. if (!this.subMeshes || !boundingInfo) {
  13950. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13951. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13952. }
  13953. else {
  13954. min = boundingInfo.boundingBox.minimumWorld;
  13955. max = boundingInfo.boundingBox.maximumWorld;
  13956. }
  13957. var descendants = this.getDescendants(false);
  13958. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13959. var descendant = descendants_1[_i];
  13960. var childMesh = descendant;
  13961. childMesh.computeWorldMatrix(true);
  13962. var childBoundingInfo = childMesh.getBoundingInfo();
  13963. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13964. continue;
  13965. }
  13966. var boundingBox = childBoundingInfo.boundingBox;
  13967. var minBox = boundingBox.minimumWorld;
  13968. var maxBox = boundingBox.maximumWorld;
  13969. BABYLON.Tools.CheckExtends(minBox, min, max);
  13970. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13971. }
  13972. return {
  13973. min: min,
  13974. max: max
  13975. };
  13976. };
  13977. /**
  13978. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13979. * Returns the AbstractMesh.
  13980. */
  13981. AbstractMesh.prototype._updateBoundingInfo = function () {
  13982. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13983. this._boundingInfo.update(this.worldMatrixFromCache);
  13984. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13985. return this;
  13986. };
  13987. /**
  13988. * Update a mesh's children BoundingInfo objects only.
  13989. * Returns the AbstractMesh.
  13990. */
  13991. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13992. if (!this.subMeshes) {
  13993. return this;
  13994. }
  13995. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13996. var subMesh = this.subMeshes[subIndex];
  13997. if (!subMesh.IsGlobal) {
  13998. subMesh.updateBoundingInfo(matrix);
  13999. }
  14000. }
  14001. return this;
  14002. };
  14003. /**
  14004. * Computes the mesh World matrix and returns it.
  14005. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14006. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14007. * If the parameter `force`is set to `true`, the actual computation is done.
  14008. * Returns the mesh World Matrix.
  14009. */
  14010. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14011. if (this._isWorldMatrixFrozen) {
  14012. return this._worldMatrix;
  14013. }
  14014. if (!force && this.isSynchronized(true)) {
  14015. this._currentRenderId = this.getScene().getRenderId();
  14016. return this._worldMatrix;
  14017. }
  14018. this._cache.position.copyFrom(this.position);
  14019. this._cache.scaling.copyFrom(this.scaling);
  14020. this._cache.pivotMatrixUpdated = false;
  14021. this._cache.billboardMode = this.billboardMode;
  14022. this._currentRenderId = this.getScene().getRenderId();
  14023. this._isDirty = false;
  14024. // Scaling
  14025. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14026. // Rotation
  14027. //rotate, if quaternion is set and rotation was used
  14028. if (this.rotationQuaternion) {
  14029. var len = this.rotation.length();
  14030. if (len) {
  14031. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14032. this.rotation.copyFromFloats(0, 0, 0);
  14033. }
  14034. }
  14035. if (this.rotationQuaternion) {
  14036. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14037. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14038. }
  14039. else {
  14040. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14041. this._cache.rotation.copyFrom(this.rotation);
  14042. }
  14043. // Translation
  14044. var camera = this.getScene().activeCamera;
  14045. if (this.infiniteDistance && !this.parent && camera) {
  14046. var cameraWorldMatrix = camera.getWorldMatrix();
  14047. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14048. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14049. }
  14050. else {
  14051. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14052. }
  14053. // Composing transformations
  14054. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14055. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14056. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14057. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14058. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14059. // Need to decompose each rotation here
  14060. var currentPosition = BABYLON.Tmp.Vector3[3];
  14061. if (this.parent && this.parent.getWorldMatrix) {
  14062. if (this._meshToBoneReferal) {
  14063. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14064. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14065. }
  14066. else {
  14067. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14068. }
  14069. }
  14070. else {
  14071. currentPosition.copyFrom(this.position);
  14072. }
  14073. currentPosition.subtractInPlace(camera.globalPosition);
  14074. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14075. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14076. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14077. }
  14078. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14079. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14080. }
  14081. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14082. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14083. }
  14084. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14085. }
  14086. else {
  14087. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14088. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14089. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14090. }
  14091. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14092. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14093. }
  14094. // Local world
  14095. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14096. // Parent
  14097. if (this.parent && this.parent.getWorldMatrix) {
  14098. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14099. if (this._meshToBoneReferal) {
  14100. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14101. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14102. }
  14103. else {
  14104. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14105. }
  14106. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14107. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14108. this._worldMatrix.copyFrom(this._localWorld);
  14109. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14110. }
  14111. else {
  14112. if (this._meshToBoneReferal) {
  14113. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14114. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14115. }
  14116. else {
  14117. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14118. }
  14119. }
  14120. this._markSyncedWithParent();
  14121. }
  14122. else {
  14123. this._worldMatrix.copyFrom(this._localWorld);
  14124. }
  14125. // Post multiply inverse of pivotMatrix
  14126. if (this._postMultiplyPivotMatrix) {
  14127. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14128. }
  14129. // Normal matrix
  14130. if (this.scaling.isNonUniform) {
  14131. this.nonUniformScaling = true;
  14132. }
  14133. else if (this.parent && this.parent._nonUniformScaling) {
  14134. this.nonUniformScaling = this.parent._nonUniformScaling;
  14135. }
  14136. else {
  14137. this.nonUniformScaling = false;
  14138. }
  14139. // Bounding info
  14140. this._updateBoundingInfo();
  14141. // Absolute position
  14142. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14143. // Callbacks
  14144. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14145. if (!this._poseMatrix) {
  14146. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14147. }
  14148. return this._worldMatrix;
  14149. };
  14150. /**
  14151. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14152. * @param func: callback function to add
  14153. *
  14154. * Returns the AbstractMesh.
  14155. */
  14156. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14157. this.onAfterWorldMatrixUpdateObservable.add(func);
  14158. return this;
  14159. };
  14160. /**
  14161. * Removes a registered callback function.
  14162. * Returns the AbstractMesh.
  14163. */
  14164. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14165. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14166. return this;
  14167. };
  14168. /**
  14169. * Sets the mesh position in its local space.
  14170. * Returns the AbstractMesh.
  14171. */
  14172. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14173. this.computeWorldMatrix();
  14174. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14175. return this;
  14176. };
  14177. /**
  14178. * Returns the mesh position in the local space from the current World matrix values.
  14179. * Returns a new Vector3.
  14180. */
  14181. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14182. this.computeWorldMatrix();
  14183. var invLocalWorldMatrix = this._localWorld.clone();
  14184. invLocalWorldMatrix.invert();
  14185. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14186. };
  14187. /**
  14188. * Translates the mesh along the passed Vector3 in its local space.
  14189. * Returns the AbstractMesh.
  14190. */
  14191. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14192. this.computeWorldMatrix(true);
  14193. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14194. return this;
  14195. };
  14196. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14197. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14198. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14199. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14200. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14201. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14202. /// <returns>Mesh oriented towards targetMesh</returns>
  14203. if (yawCor === void 0) { yawCor = 0; }
  14204. if (pitchCor === void 0) { pitchCor = 0; }
  14205. if (rollCor === void 0) { rollCor = 0; }
  14206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14207. var dv = AbstractMesh._lookAtVectorCache;
  14208. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14209. targetPoint.subtractToRef(pos, dv);
  14210. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14211. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14212. var pitch = Math.atan2(dv.y, len);
  14213. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14214. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14215. return this;
  14216. };
  14217. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14218. this._meshToBoneReferal = affectedMesh;
  14219. this.parent = bone;
  14220. if (bone.getWorldMatrix().determinant() < 0) {
  14221. this.scalingDeterminant *= -1;
  14222. }
  14223. return this;
  14224. };
  14225. AbstractMesh.prototype.detachFromBone = function () {
  14226. if (!this.parent) {
  14227. return this;
  14228. }
  14229. if (this.parent.getWorldMatrix().determinant() < 0) {
  14230. this.scalingDeterminant *= -1;
  14231. }
  14232. this._meshToBoneReferal = null;
  14233. this.parent = null;
  14234. return this;
  14235. };
  14236. /**
  14237. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14238. * A mesh is in the frustum if its bounding box intersects the frustum.
  14239. * Boolean returned.
  14240. */
  14241. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14242. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14243. };
  14244. /**
  14245. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14246. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14247. * Boolean returned.
  14248. */
  14249. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14250. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14251. ;
  14252. };
  14253. /**
  14254. * True if the mesh intersects another mesh or a SolidParticle object.
  14255. * 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)
  14256. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14257. * Returns a boolean.
  14258. */
  14259. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14260. if (precise === void 0) { precise = false; }
  14261. if (!this._boundingInfo || !mesh._boundingInfo) {
  14262. return false;
  14263. }
  14264. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14265. return true;
  14266. }
  14267. if (includeDescendants) {
  14268. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14269. var child = _a[_i];
  14270. if (child.intersectsMesh(mesh, precise, true)) {
  14271. return true;
  14272. }
  14273. }
  14274. }
  14275. return false;
  14276. };
  14277. /**
  14278. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14279. * Returns a boolean.
  14280. */
  14281. AbstractMesh.prototype.intersectsPoint = function (point) {
  14282. if (!this._boundingInfo) {
  14283. return false;
  14284. }
  14285. return this._boundingInfo.intersectsPoint(point);
  14286. };
  14287. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14288. return this.physicsImpostor;
  14289. };
  14290. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14291. if (camera === void 0) { camera = null; }
  14292. if (!camera) {
  14293. camera = this.getScene().activeCamera;
  14294. }
  14295. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14296. };
  14297. /**
  14298. * Returns the distance from the mesh to the active camera.
  14299. * Returns a float.
  14300. */
  14301. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14302. if (camera === void 0) { camera = null; }
  14303. if (!camera) {
  14304. camera = this.getScene().activeCamera;
  14305. }
  14306. return this.absolutePosition.subtract(camera.position).length();
  14307. };
  14308. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14309. if (!this.physicsImpostor) {
  14310. return this;
  14311. }
  14312. this.physicsImpostor.applyImpulse(force, contactPoint);
  14313. return this;
  14314. };
  14315. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14316. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14317. return this;
  14318. }
  14319. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14320. mainPivot: pivot1,
  14321. connectedPivot: pivot2,
  14322. nativeParams: options
  14323. });
  14324. return this;
  14325. };
  14326. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14327. // Collisions
  14328. /**
  14329. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14330. * Default `false`.
  14331. */
  14332. get: function () {
  14333. return this._checkCollisions;
  14334. },
  14335. set: function (collisionEnabled) {
  14336. this._checkCollisions = collisionEnabled;
  14337. if (this.getScene().workerCollisions) {
  14338. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14339. }
  14340. },
  14341. enumerable: true,
  14342. configurable: true
  14343. });
  14344. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14345. var globalPosition = this.getAbsolutePosition();
  14346. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14347. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14348. if (!this._collider) {
  14349. this._collider = new BABYLON.Collider();
  14350. }
  14351. this._collider.radius = this.ellipsoid;
  14352. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14353. return this;
  14354. };
  14355. // Submeshes octree
  14356. /**
  14357. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14358. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14359. * Returns an Octree of submeshes.
  14360. */
  14361. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14362. if (maxCapacity === void 0) { maxCapacity = 64; }
  14363. if (maxDepth === void 0) { maxDepth = 2; }
  14364. if (!this._submeshesOctree) {
  14365. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14366. }
  14367. this.computeWorldMatrix(true);
  14368. var boundingInfo = this.getBoundingInfo();
  14369. // Update octree
  14370. if (boundingInfo) {
  14371. var bbox = boundingInfo.boundingBox;
  14372. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14373. }
  14374. return this._submeshesOctree;
  14375. };
  14376. // Collisions
  14377. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14378. this._generatePointsArray();
  14379. if (!this._positions) {
  14380. return this;
  14381. }
  14382. // Transformation
  14383. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14384. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14385. subMesh._lastColliderWorldVertices = [];
  14386. subMesh._trianglePlanes = [];
  14387. var start = subMesh.verticesStart;
  14388. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14389. for (var i = start; i < end; i++) {
  14390. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14391. }
  14392. }
  14393. // Collide
  14394. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14395. if (collider.collisionFound) {
  14396. collider.collidedMesh = this;
  14397. }
  14398. return this;
  14399. };
  14400. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14401. var subMeshes;
  14402. var len;
  14403. // Octrees
  14404. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14405. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14406. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14407. len = intersections.length;
  14408. subMeshes = intersections.data;
  14409. }
  14410. else {
  14411. subMeshes = this.subMeshes;
  14412. len = subMeshes.length;
  14413. }
  14414. for (var index = 0; index < len; index++) {
  14415. var subMesh = subMeshes[index];
  14416. // Bounding test
  14417. if (len > 1 && !subMesh._checkCollision(collider))
  14418. continue;
  14419. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14420. }
  14421. return this;
  14422. };
  14423. AbstractMesh.prototype._checkCollision = function (collider) {
  14424. // Bounding box test
  14425. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14426. return this;
  14427. // Transformation matrix
  14428. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14429. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14430. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14431. return this;
  14432. };
  14433. // Picking
  14434. AbstractMesh.prototype._generatePointsArray = function () {
  14435. return false;
  14436. };
  14437. /**
  14438. * Checks if the passed Ray intersects with the mesh.
  14439. * Returns an object PickingInfo.
  14440. */
  14441. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14442. var pickingInfo = new BABYLON.PickingInfo();
  14443. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14444. return pickingInfo;
  14445. }
  14446. if (!this._generatePointsArray()) {
  14447. return pickingInfo;
  14448. }
  14449. var intersectInfo = null;
  14450. // Octrees
  14451. var subMeshes;
  14452. var len;
  14453. if (this._submeshesOctree && this.useOctreeForPicking) {
  14454. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14455. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14456. len = intersections.length;
  14457. subMeshes = intersections.data;
  14458. }
  14459. else {
  14460. subMeshes = this.subMeshes;
  14461. len = subMeshes.length;
  14462. }
  14463. for (var index = 0; index < len; index++) {
  14464. var subMesh = subMeshes[index];
  14465. // Bounding test
  14466. if (len > 1 && !subMesh.canIntersects(ray))
  14467. continue;
  14468. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14469. if (currentIntersectInfo) {
  14470. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14471. intersectInfo = currentIntersectInfo;
  14472. intersectInfo.subMeshId = index;
  14473. if (fastCheck) {
  14474. break;
  14475. }
  14476. }
  14477. }
  14478. }
  14479. if (intersectInfo) {
  14480. // Get picked point
  14481. var world = this.getWorldMatrix();
  14482. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14483. var direction = ray.direction.clone();
  14484. direction = direction.scale(intersectInfo.distance);
  14485. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14486. var pickedPoint = worldOrigin.add(worldDirection);
  14487. // Return result
  14488. pickingInfo.hit = true;
  14489. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14490. pickingInfo.pickedPoint = pickedPoint;
  14491. pickingInfo.pickedMesh = this;
  14492. pickingInfo.bu = intersectInfo.bu || 0;
  14493. pickingInfo.bv = intersectInfo.bv || 0;
  14494. pickingInfo.faceId = intersectInfo.faceId;
  14495. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14496. return pickingInfo;
  14497. }
  14498. return pickingInfo;
  14499. };
  14500. /**
  14501. * Clones the mesh, used by the class Mesh.
  14502. * Just returns `null` for an AbstractMesh.
  14503. */
  14504. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14505. return null;
  14506. };
  14507. /**
  14508. * Disposes all the mesh submeshes.
  14509. * Returns the AbstractMesh.
  14510. */
  14511. AbstractMesh.prototype.releaseSubMeshes = function () {
  14512. if (this.subMeshes) {
  14513. while (this.subMeshes.length) {
  14514. this.subMeshes[0].dispose();
  14515. }
  14516. }
  14517. else {
  14518. this.subMeshes = new Array();
  14519. }
  14520. return this;
  14521. };
  14522. /**
  14523. * Disposes the AbstractMesh.
  14524. * Some internal references are kept for further use.
  14525. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14526. * Returns nothing.
  14527. */
  14528. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14529. var _this = this;
  14530. var index;
  14531. // Action manager
  14532. if (this.actionManager) {
  14533. this.actionManager.dispose();
  14534. this.actionManager = null;
  14535. }
  14536. // Skeleton
  14537. this.skeleton = null;
  14538. // Animations
  14539. this.getScene().stopAnimation(this);
  14540. // Physics
  14541. if (this.physicsImpostor) {
  14542. this.physicsImpostor.dispose();
  14543. }
  14544. // Intersections in progress
  14545. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14546. var other = this._intersectionsInProgress[index];
  14547. var pos = other._intersectionsInProgress.indexOf(this);
  14548. other._intersectionsInProgress.splice(pos, 1);
  14549. }
  14550. this._intersectionsInProgress = [];
  14551. // Lights
  14552. var lights = this.getScene().lights;
  14553. lights.forEach(function (light) {
  14554. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14555. if (meshIndex !== -1) {
  14556. light.includedOnlyMeshes.splice(meshIndex, 1);
  14557. }
  14558. meshIndex = light.excludedMeshes.indexOf(_this);
  14559. if (meshIndex !== -1) {
  14560. light.excludedMeshes.splice(meshIndex, 1);
  14561. }
  14562. // Shadow generators
  14563. var generator = light.getShadowGenerator();
  14564. if (generator) {
  14565. var shadowMap = generator.getShadowMap();
  14566. if (shadowMap && shadowMap.renderList) {
  14567. meshIndex = shadowMap.renderList.indexOf(_this);
  14568. if (meshIndex !== -1) {
  14569. shadowMap.renderList.splice(meshIndex, 1);
  14570. }
  14571. }
  14572. }
  14573. });
  14574. // Edges
  14575. if (this._edgesRenderer) {
  14576. this._edgesRenderer.dispose();
  14577. this._edgesRenderer = null;
  14578. }
  14579. // SubMeshes
  14580. if (this.getClassName() !== "InstancedMesh") {
  14581. this.releaseSubMeshes();
  14582. }
  14583. // Octree
  14584. var sceneOctree = this.getScene().selectionOctree;
  14585. if (sceneOctree) {
  14586. var index = sceneOctree.dynamicContent.indexOf(this);
  14587. if (index !== -1) {
  14588. sceneOctree.dynamicContent.splice(index, 1);
  14589. }
  14590. }
  14591. // Query
  14592. var engine = this.getScene().getEngine();
  14593. if (this._occlusionQuery) {
  14594. this._isOcclusionQueryInProgress = false;
  14595. engine.deleteQuery(this._occlusionQuery);
  14596. this._occlusionQuery = null;
  14597. }
  14598. // Engine
  14599. engine.wipeCaches();
  14600. // Remove from scene
  14601. this.getScene().removeMesh(this);
  14602. if (!doNotRecurse) {
  14603. // Particles
  14604. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14605. if (this.getScene().particleSystems[index].emitter === this) {
  14606. this.getScene().particleSystems[index].dispose();
  14607. index--;
  14608. }
  14609. }
  14610. // Children
  14611. var objects = this.getDescendants(true);
  14612. for (index = 0; index < objects.length; index++) {
  14613. objects[index].dispose();
  14614. }
  14615. }
  14616. else {
  14617. var childMeshes = this.getChildMeshes(true);
  14618. for (index = 0; index < childMeshes.length; index++) {
  14619. var child = childMeshes[index];
  14620. child.parent = null;
  14621. child.computeWorldMatrix(true);
  14622. }
  14623. }
  14624. // facet data
  14625. if (this._facetDataEnabled) {
  14626. this.disableFacetData();
  14627. }
  14628. this.onAfterWorldMatrixUpdateObservable.clear();
  14629. this.onCollideObservable.clear();
  14630. this.onCollisionPositionChangeObservable.clear();
  14631. this._isDisposed = true;
  14632. _super.prototype.dispose.call(this);
  14633. };
  14634. /**
  14635. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14636. * This Vector3 is expressed in the World space.
  14637. */
  14638. AbstractMesh.prototype.getDirection = function (localAxis) {
  14639. var result = BABYLON.Vector3.Zero();
  14640. this.getDirectionToRef(localAxis, result);
  14641. return result;
  14642. };
  14643. /**
  14644. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14645. * localAxis is expressed in the mesh local space.
  14646. * result is computed in the Wordl space from the mesh World matrix.
  14647. * Returns the AbstractMesh.
  14648. */
  14649. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14650. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14651. return this;
  14652. };
  14653. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14655. if (this.getScene().getRenderId() == 0) {
  14656. this.computeWorldMatrix(true);
  14657. }
  14658. var wm = this.getWorldMatrix();
  14659. if (space == BABYLON.Space.WORLD) {
  14660. var tmat = BABYLON.Tmp.Matrix[0];
  14661. wm.invertToRef(tmat);
  14662. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14663. }
  14664. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14665. this._pivotMatrix.m[12] = -point.x;
  14666. this._pivotMatrix.m[13] = -point.y;
  14667. this._pivotMatrix.m[14] = -point.z;
  14668. this._cache.pivotMatrixUpdated = true;
  14669. return this;
  14670. };
  14671. /**
  14672. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14673. */
  14674. AbstractMesh.prototype.getPivotPoint = function () {
  14675. var point = BABYLON.Vector3.Zero();
  14676. this.getPivotPointToRef(point);
  14677. return point;
  14678. };
  14679. /**
  14680. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14681. * Returns the AbstractMesh.
  14682. */
  14683. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14684. result.x = -this._pivotMatrix.m[12];
  14685. result.y = -this._pivotMatrix.m[13];
  14686. result.z = -this._pivotMatrix.m[14];
  14687. return this;
  14688. };
  14689. /**
  14690. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14691. */
  14692. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14693. var point = BABYLON.Vector3.Zero();
  14694. this.getAbsolutePivotPointToRef(point);
  14695. return point;
  14696. };
  14697. /**
  14698. * Defines the passed mesh as the parent of the current mesh.
  14699. * Returns the AbstractMesh.
  14700. */
  14701. AbstractMesh.prototype.setParent = function (mesh) {
  14702. var parent = mesh;
  14703. if (mesh == null) {
  14704. var rotation = BABYLON.Tmp.Quaternion[0];
  14705. var position = BABYLON.Tmp.Vector3[0];
  14706. var scale = BABYLON.Tmp.Vector3[1];
  14707. this.getWorldMatrix().decompose(scale, rotation, position);
  14708. if (this.rotationQuaternion) {
  14709. this.rotationQuaternion.copyFrom(rotation);
  14710. }
  14711. else {
  14712. rotation.toEulerAnglesToRef(this.rotation);
  14713. }
  14714. this.position.x = position.x;
  14715. this.position.y = position.y;
  14716. this.position.z = position.z;
  14717. }
  14718. else {
  14719. var position = BABYLON.Tmp.Vector3[0];
  14720. var m1 = BABYLON.Tmp.Matrix[0];
  14721. parent.getWorldMatrix().invertToRef(m1);
  14722. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14723. this.position.copyFrom(position);
  14724. }
  14725. this.parent = parent;
  14726. return this;
  14727. };
  14728. /**
  14729. * Adds the passed mesh as a child to the current mesh.
  14730. * Returns the AbstractMesh.
  14731. */
  14732. AbstractMesh.prototype.addChild = function (mesh) {
  14733. mesh.setParent(this);
  14734. return this;
  14735. };
  14736. /**
  14737. * Removes the passed mesh from the current mesh children list.
  14738. * Returns the AbstractMesh.
  14739. */
  14740. AbstractMesh.prototype.removeChild = function (mesh) {
  14741. mesh.setParent(null);
  14742. return this;
  14743. };
  14744. /**
  14745. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14746. * Returns the AbstractMesh.
  14747. */
  14748. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14749. result.x = this._pivotMatrix.m[12];
  14750. result.y = this._pivotMatrix.m[13];
  14751. result.z = this._pivotMatrix.m[14];
  14752. this.getPivotPointToRef(result);
  14753. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14754. return this;
  14755. };
  14756. // Facet data
  14757. /**
  14758. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14759. * Returns the AbstractMesh.
  14760. */
  14761. AbstractMesh.prototype._initFacetData = function () {
  14762. if (!this._facetNormals) {
  14763. this._facetNormals = new Array();
  14764. }
  14765. if (!this._facetPositions) {
  14766. this._facetPositions = new Array();
  14767. }
  14768. if (!this._facetPartitioning) {
  14769. this._facetPartitioning = new Array();
  14770. }
  14771. this._facetNb = this.getIndices().length / 3;
  14772. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14773. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14774. for (var f = 0; f < this._facetNb; f++) {
  14775. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14776. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14777. }
  14778. this._facetDataEnabled = true;
  14779. return this;
  14780. };
  14781. /**
  14782. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14783. * This method can be called within the render loop.
  14784. * 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.
  14785. * Returns the AbstractMesh.
  14786. */
  14787. AbstractMesh.prototype.updateFacetData = function () {
  14788. if (!this._facetDataEnabled) {
  14789. this._initFacetData();
  14790. }
  14791. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14792. var indices = this.getIndices();
  14793. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14794. var bInfo = this.getBoundingInfo();
  14795. if (!bInfo) {
  14796. return this;
  14797. }
  14798. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14799. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14800. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14801. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14802. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14803. this._subDiv.max = this._partitioningSubdivisions;
  14804. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14805. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14806. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14807. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14808. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14809. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14810. // set the parameters for ComputeNormals()
  14811. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14812. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14813. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14814. this._facetParameters.bInfo = bInfo;
  14815. this._facetParameters.bbSize = this._bbSize;
  14816. this._facetParameters.subDiv = this._subDiv;
  14817. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14818. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14819. return this;
  14820. };
  14821. /**
  14822. * Returns the facetLocalNormals array.
  14823. * The normals are expressed in the mesh local space.
  14824. */
  14825. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14826. if (!this._facetNormals) {
  14827. this.updateFacetData();
  14828. }
  14829. return this._facetNormals;
  14830. };
  14831. /**
  14832. * Returns the facetLocalPositions array.
  14833. * The facet positions are expressed in the mesh local space.
  14834. */
  14835. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14836. if (!this._facetPositions) {
  14837. this.updateFacetData();
  14838. }
  14839. return this._facetPositions;
  14840. };
  14841. /**
  14842. * Returns the facetLocalPartioning array.
  14843. */
  14844. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14845. if (!this._facetPartitioning) {
  14846. this.updateFacetData();
  14847. }
  14848. return this._facetPartitioning;
  14849. };
  14850. /**
  14851. * Returns the i-th facet position in the world system.
  14852. * This method allocates a new Vector3 per call.
  14853. */
  14854. AbstractMesh.prototype.getFacetPosition = function (i) {
  14855. var pos = BABYLON.Vector3.Zero();
  14856. this.getFacetPositionToRef(i, pos);
  14857. return pos;
  14858. };
  14859. /**
  14860. * Sets the reference Vector3 with the i-th facet position in the world system.
  14861. * Returns the AbstractMesh.
  14862. */
  14863. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14864. var localPos = (this.getFacetLocalPositions())[i];
  14865. var world = this.getWorldMatrix();
  14866. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14867. return this;
  14868. };
  14869. /**
  14870. * Returns the i-th facet normal in the world system.
  14871. * This method allocates a new Vector3 per call.
  14872. */
  14873. AbstractMesh.prototype.getFacetNormal = function (i) {
  14874. var norm = BABYLON.Vector3.Zero();
  14875. this.getFacetNormalToRef(i, norm);
  14876. return norm;
  14877. };
  14878. /**
  14879. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14880. * Returns the AbstractMesh.
  14881. */
  14882. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14883. var localNorm = (this.getFacetLocalNormals())[i];
  14884. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14885. return this;
  14886. };
  14887. /**
  14888. * 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).
  14889. */
  14890. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14891. var bInfo = this.getBoundingInfo();
  14892. if (!bInfo) {
  14893. return null;
  14894. }
  14895. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14896. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14897. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14898. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14899. return null;
  14900. }
  14901. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14902. };
  14903. /**
  14904. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14905. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14906. * 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.
  14907. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14908. * 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.
  14909. */
  14910. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14911. if (checkFace === void 0) { checkFace = false; }
  14912. if (facing === void 0) { facing = true; }
  14913. var world = this.getWorldMatrix();
  14914. var invMat = BABYLON.Tmp.Matrix[5];
  14915. world.invertToRef(invMat);
  14916. var invVect = BABYLON.Tmp.Vector3[8];
  14917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14918. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14919. if (projected) {
  14920. // tranform the local computed projected vector to world coordinates
  14921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14922. }
  14923. return closest;
  14924. };
  14925. /**
  14926. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14927. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14928. * 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.
  14929. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14930. * 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.
  14931. */
  14932. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14933. if (checkFace === void 0) { checkFace = false; }
  14934. if (facing === void 0) { facing = true; }
  14935. var closest = null;
  14936. var tmpx = 0.0;
  14937. var tmpy = 0.0;
  14938. var tmpz = 0.0;
  14939. var d = 0.0; // tmp dot facet normal * facet position
  14940. var t0 = 0.0;
  14941. var projx = 0.0;
  14942. var projy = 0.0;
  14943. var projz = 0.0;
  14944. // Get all the facets in the same partitioning block than (x, y, z)
  14945. var facetPositions = this.getFacetLocalPositions();
  14946. var facetNormals = this.getFacetLocalNormals();
  14947. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14948. if (!facetsInBlock) {
  14949. return null;
  14950. }
  14951. // Get the closest facet to (x, y, z)
  14952. var shortest = Number.MAX_VALUE; // init distance vars
  14953. var tmpDistance = shortest;
  14954. var fib; // current facet in the block
  14955. var norm; // current facet normal
  14956. var p0; // current facet barycenter position
  14957. // loop on all the facets in the current partitioning block
  14958. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14959. fib = facetsInBlock[idx];
  14960. norm = facetNormals[fib];
  14961. p0 = facetPositions[fib];
  14962. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14963. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14964. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14965. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14966. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14967. projx = x + norm.x * t0;
  14968. projy = y + norm.y * t0;
  14969. projz = z + norm.z * t0;
  14970. tmpx = projx - x;
  14971. tmpy = projy - y;
  14972. tmpz = projz - z;
  14973. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14974. if (tmpDistance < shortest) {
  14975. shortest = tmpDistance;
  14976. closest = fib;
  14977. if (projected) {
  14978. projected.x = projx;
  14979. projected.y = projy;
  14980. projected.z = projz;
  14981. }
  14982. }
  14983. }
  14984. }
  14985. return closest;
  14986. };
  14987. /**
  14988. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14989. */
  14990. AbstractMesh.prototype.getFacetDataParameters = function () {
  14991. return this._facetParameters;
  14992. };
  14993. /**
  14994. * Disables the feature FacetData and frees the related memory.
  14995. * Returns the AbstractMesh.
  14996. */
  14997. AbstractMesh.prototype.disableFacetData = function () {
  14998. if (this._facetDataEnabled) {
  14999. this._facetDataEnabled = false;
  15000. this._facetPositions = new Array();
  15001. ;
  15002. this._facetNormals = new Array();
  15003. ;
  15004. this._facetPartitioning = new Array();
  15005. ;
  15006. this._facetParameters = null;
  15007. }
  15008. return this;
  15009. };
  15010. /**
  15011. * Creates new normals data for the mesh.
  15012. * @param updatable.
  15013. */
  15014. AbstractMesh.prototype.createNormals = function (updatable) {
  15015. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15016. var indices = this.getIndices();
  15017. var normals;
  15018. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15019. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15020. }
  15021. else {
  15022. normals = [];
  15023. }
  15024. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15025. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15026. };
  15027. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15028. var engine = this.getEngine();
  15029. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15030. this._isOccluded = false;
  15031. return;
  15032. }
  15033. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15034. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15035. if (isOcclusionQueryAvailable) {
  15036. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15037. this._isOcclusionQueryInProgress = false;
  15038. this._occlusionInternalRetryCounter = 0;
  15039. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15040. }
  15041. else {
  15042. this._occlusionInternalRetryCounter++;
  15043. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15044. this._isOcclusionQueryInProgress = false;
  15045. this._occlusionInternalRetryCounter = 0;
  15046. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15047. // if strict continue the last state of the object.
  15048. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15049. }
  15050. else {
  15051. return;
  15052. }
  15053. }
  15054. }
  15055. var scene = this.getScene();
  15056. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15057. if (!this._occlusionQuery) {
  15058. this._occlusionQuery = engine.createQuery();
  15059. }
  15060. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15061. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15062. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15063. this._isOcclusionQueryInProgress = true;
  15064. };
  15065. // Statics
  15066. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15067. AbstractMesh._BILLBOARDMODE_X = 1;
  15068. AbstractMesh._BILLBOARDMODE_Y = 2;
  15069. AbstractMesh._BILLBOARDMODE_Z = 4;
  15070. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15071. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15072. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15073. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15074. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15075. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15076. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15077. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15078. return AbstractMesh;
  15079. }(BABYLON.Node));
  15080. BABYLON.AbstractMesh = AbstractMesh;
  15081. })(BABYLON || (BABYLON = {}));
  15082. //# sourceMappingURL=babylon.abstractMesh.js.map
  15083. var BABYLON;
  15084. (function (BABYLON) {
  15085. var Light = /** @class */ (function (_super) {
  15086. __extends(Light, _super);
  15087. /**
  15088. * Creates a Light object in the scene.
  15089. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15090. */
  15091. function Light(name, scene) {
  15092. var _this = _super.call(this, name, scene) || this;
  15093. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15094. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15095. _this.intensity = 1.0;
  15096. _this.range = Number.MAX_VALUE;
  15097. /**
  15098. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15099. * of light.
  15100. */
  15101. _this._photometricScale = 1.0;
  15102. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15103. _this._radius = 0.00001;
  15104. _this.renderPriority = 0;
  15105. /**
  15106. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15107. * the current shadow generator.
  15108. */
  15109. _this.shadowEnabled = true;
  15110. _this._excludeWithLayerMask = 0;
  15111. _this._includeOnlyWithLayerMask = 0;
  15112. _this._lightmapMode = 0;
  15113. _this._excludedMeshesIds = new Array();
  15114. _this._includedOnlyMeshesIds = new Array();
  15115. _this.getScene().addLight(_this);
  15116. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15117. _this._buildUniformLayout();
  15118. _this.includedOnlyMeshes = new Array();
  15119. _this.excludedMeshes = new Array();
  15120. _this._resyncMeshes();
  15121. return _this;
  15122. }
  15123. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15124. /**
  15125. * If every light affecting the material is in this lightmapMode,
  15126. * material.lightmapTexture adds or multiplies
  15127. * (depends on material.useLightmapAsShadowmap)
  15128. * after every other light calculations.
  15129. */
  15130. get: function () {
  15131. return Light._LIGHTMAP_DEFAULT;
  15132. },
  15133. enumerable: true,
  15134. configurable: true
  15135. });
  15136. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15137. /**
  15138. * material.lightmapTexture as only diffuse lighting from this light
  15139. * adds pnly specular lighting from this light
  15140. * adds dynamic shadows
  15141. */
  15142. get: function () {
  15143. return Light._LIGHTMAP_SPECULAR;
  15144. },
  15145. enumerable: true,
  15146. configurable: true
  15147. });
  15148. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15149. /**
  15150. * material.lightmapTexture as only lighting
  15151. * no light calculation from this light
  15152. * only adds dynamic shadows from this light
  15153. */
  15154. get: function () {
  15155. return Light._LIGHTMAP_SHADOWSONLY;
  15156. },
  15157. enumerable: true,
  15158. configurable: true
  15159. });
  15160. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15161. /**
  15162. * Each light type uses the default quantity according to its type:
  15163. * point/spot lights use luminous intensity
  15164. * directional lights use illuminance
  15165. */
  15166. get: function () {
  15167. return Light._INTENSITYMODE_AUTOMATIC;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15173. /**
  15174. * lumen (lm)
  15175. */
  15176. get: function () {
  15177. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15178. },
  15179. enumerable: true,
  15180. configurable: true
  15181. });
  15182. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15183. /**
  15184. * candela (lm/sr)
  15185. */
  15186. get: function () {
  15187. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15193. /**
  15194. * lux (lm/m^2)
  15195. */
  15196. get: function () {
  15197. return Light._INTENSITYMODE_ILLUMINANCE;
  15198. },
  15199. enumerable: true,
  15200. configurable: true
  15201. });
  15202. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15203. /**
  15204. * nit (cd/m^2)
  15205. */
  15206. get: function () {
  15207. return Light._INTENSITYMODE_LUMINANCE;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15213. /**
  15214. * Light type const id of the point light.
  15215. */
  15216. get: function () {
  15217. return Light._LIGHTTYPEID_POINTLIGHT;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15223. /**
  15224. * Light type const id of the directional light.
  15225. */
  15226. get: function () {
  15227. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15228. },
  15229. enumerable: true,
  15230. configurable: true
  15231. });
  15232. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15233. /**
  15234. * Light type const id of the spot light.
  15235. */
  15236. get: function () {
  15237. return Light._LIGHTTYPEID_SPOTLIGHT;
  15238. },
  15239. enumerable: true,
  15240. configurable: true
  15241. });
  15242. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15243. /**
  15244. * Light type const id of the hemispheric light.
  15245. */
  15246. get: function () {
  15247. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15248. },
  15249. enumerable: true,
  15250. configurable: true
  15251. });
  15252. Object.defineProperty(Light.prototype, "intensityMode", {
  15253. /**
  15254. * Gets the photometric scale used to interpret the intensity.
  15255. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15256. */
  15257. get: function () {
  15258. return this._intensityMode;
  15259. },
  15260. /**
  15261. * Sets the photometric scale used to interpret the intensity.
  15262. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15263. */
  15264. set: function (value) {
  15265. this._intensityMode = value;
  15266. this._computePhotometricScale();
  15267. },
  15268. enumerable: true,
  15269. configurable: true
  15270. });
  15271. ;
  15272. ;
  15273. Object.defineProperty(Light.prototype, "radius", {
  15274. /**
  15275. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15276. */
  15277. get: function () {
  15278. return this._radius;
  15279. },
  15280. /**
  15281. * sets the light radius used by PBR Materials to simulate soft area lights.
  15282. */
  15283. set: function (value) {
  15284. this._radius = value;
  15285. this._computePhotometricScale();
  15286. },
  15287. enumerable: true,
  15288. configurable: true
  15289. });
  15290. ;
  15291. ;
  15292. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15293. get: function () {
  15294. return this._includedOnlyMeshes;
  15295. },
  15296. set: function (value) {
  15297. this._includedOnlyMeshes = value;
  15298. this._hookArrayForIncludedOnly(value);
  15299. },
  15300. enumerable: true,
  15301. configurable: true
  15302. });
  15303. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15304. get: function () {
  15305. return this._excludedMeshes;
  15306. },
  15307. set: function (value) {
  15308. this._excludedMeshes = value;
  15309. this._hookArrayForExcluded(value);
  15310. },
  15311. enumerable: true,
  15312. configurable: true
  15313. });
  15314. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15315. get: function () {
  15316. return this._excludeWithLayerMask;
  15317. },
  15318. set: function (value) {
  15319. this._excludeWithLayerMask = value;
  15320. this._resyncMeshes();
  15321. },
  15322. enumerable: true,
  15323. configurable: true
  15324. });
  15325. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15326. get: function () {
  15327. return this._includeOnlyWithLayerMask;
  15328. },
  15329. set: function (value) {
  15330. this._includeOnlyWithLayerMask = value;
  15331. this._resyncMeshes();
  15332. },
  15333. enumerable: true,
  15334. configurable: true
  15335. });
  15336. Object.defineProperty(Light.prototype, "lightmapMode", {
  15337. get: function () {
  15338. return this._lightmapMode;
  15339. },
  15340. set: function (value) {
  15341. if (this._lightmapMode === value) {
  15342. return;
  15343. }
  15344. this._lightmapMode = value;
  15345. this._markMeshesAsLightDirty();
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. Light.prototype._buildUniformLayout = function () {
  15351. // Overridden
  15352. };
  15353. /**
  15354. * Returns the string "Light".
  15355. */
  15356. Light.prototype.getClassName = function () {
  15357. return "Light";
  15358. };
  15359. /**
  15360. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15361. */
  15362. Light.prototype.toString = function (fullDetails) {
  15363. var ret = "Name: " + this.name;
  15364. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15365. if (this.animations) {
  15366. for (var i = 0; i < this.animations.length; i++) {
  15367. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15368. }
  15369. }
  15370. if (fullDetails) {
  15371. }
  15372. return ret;
  15373. };
  15374. /**
  15375. * Set the enabled state of this node.
  15376. * @param {boolean} value - the new enabled state
  15377. * @see isEnabled
  15378. */
  15379. Light.prototype.setEnabled = function (value) {
  15380. _super.prototype.setEnabled.call(this, value);
  15381. this._resyncMeshes();
  15382. };
  15383. /**
  15384. * Returns the Light associated shadow generator.
  15385. */
  15386. Light.prototype.getShadowGenerator = function () {
  15387. return this._shadowGenerator;
  15388. };
  15389. /**
  15390. * Returns a Vector3, the absolute light position in the World.
  15391. */
  15392. Light.prototype.getAbsolutePosition = function () {
  15393. return BABYLON.Vector3.Zero();
  15394. };
  15395. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15396. };
  15397. Light.prototype._getWorldMatrix = function () {
  15398. return BABYLON.Matrix.Identity();
  15399. };
  15400. /**
  15401. * Boolean : True if the light will affect the passed mesh.
  15402. */
  15403. Light.prototype.canAffectMesh = function (mesh) {
  15404. if (!mesh) {
  15405. return true;
  15406. }
  15407. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15408. return false;
  15409. }
  15410. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15411. return false;
  15412. }
  15413. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15414. return false;
  15415. }
  15416. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15417. return false;
  15418. }
  15419. return true;
  15420. };
  15421. /**
  15422. * Returns the light World matrix.
  15423. */
  15424. Light.prototype.getWorldMatrix = function () {
  15425. this._currentRenderId = this.getScene().getRenderId();
  15426. var worldMatrix = this._getWorldMatrix();
  15427. if (this.parent && this.parent.getWorldMatrix) {
  15428. if (!this._parentedWorldMatrix) {
  15429. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15430. }
  15431. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15432. this._markSyncedWithParent();
  15433. return this._parentedWorldMatrix;
  15434. }
  15435. return worldMatrix;
  15436. };
  15437. /**
  15438. * Sort function to order lights for rendering.
  15439. * @param a First Light object to compare to second.
  15440. * @param b Second Light object to compare first.
  15441. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15442. */
  15443. Light.compareLightsPriority = function (a, b) {
  15444. //shadow-casting lights have priority over non-shadow-casting lights
  15445. //the renderPrioirty is a secondary sort criterion
  15446. if (a.shadowEnabled !== b.shadowEnabled) {
  15447. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15448. }
  15449. return b.renderPriority - a.renderPriority;
  15450. };
  15451. /**
  15452. * Disposes the light.
  15453. */
  15454. Light.prototype.dispose = function () {
  15455. if (this._shadowGenerator) {
  15456. this._shadowGenerator.dispose();
  15457. this._shadowGenerator = null;
  15458. }
  15459. // Animations
  15460. this.getScene().stopAnimation(this);
  15461. // Remove from meshes
  15462. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15463. var mesh = _a[_i];
  15464. mesh._removeLightSource(this);
  15465. }
  15466. this._uniformBuffer.dispose();
  15467. // Remove from scene
  15468. this.getScene().removeLight(this);
  15469. _super.prototype.dispose.call(this);
  15470. };
  15471. /**
  15472. * Returns the light type ID (integer).
  15473. */
  15474. Light.prototype.getTypeID = function () {
  15475. return 0;
  15476. };
  15477. /**
  15478. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15479. */
  15480. Light.prototype.getScaledIntensity = function () {
  15481. return this._photometricScale * this.intensity;
  15482. };
  15483. /**
  15484. * Returns a new Light object, named "name", from the current one.
  15485. */
  15486. Light.prototype.clone = function (name) {
  15487. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15488. if (!constructor) {
  15489. return null;
  15490. }
  15491. return BABYLON.SerializationHelper.Clone(constructor, this);
  15492. };
  15493. /**
  15494. * Serializes the current light into a Serialization object.
  15495. * Returns the serialized object.
  15496. */
  15497. Light.prototype.serialize = function () {
  15498. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15499. // Type
  15500. serializationObject.type = this.getTypeID();
  15501. // Parent
  15502. if (this.parent) {
  15503. serializationObject.parentId = this.parent.id;
  15504. }
  15505. // Inclusion / exclusions
  15506. if (this.excludedMeshes.length > 0) {
  15507. serializationObject.excludedMeshesIds = [];
  15508. this.excludedMeshes.forEach(function (mesh) {
  15509. serializationObject.excludedMeshesIds.push(mesh.id);
  15510. });
  15511. }
  15512. if (this.includedOnlyMeshes.length > 0) {
  15513. serializationObject.includedOnlyMeshesIds = [];
  15514. this.includedOnlyMeshes.forEach(function (mesh) {
  15515. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15516. });
  15517. }
  15518. // Animations
  15519. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15520. serializationObject.ranges = this.serializeAnimationRanges();
  15521. return serializationObject;
  15522. };
  15523. /**
  15524. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15525. * This new light is named "name" and added to the passed scene.
  15526. */
  15527. Light.GetConstructorFromName = function (type, name, scene) {
  15528. switch (type) {
  15529. case 0:
  15530. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15531. case 1:
  15532. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15533. case 2:
  15534. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15535. case 3:
  15536. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15537. }
  15538. return null;
  15539. };
  15540. /**
  15541. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15542. */
  15543. Light.Parse = function (parsedLight, scene) {
  15544. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15545. if (!constructor) {
  15546. return null;
  15547. }
  15548. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15549. // Inclusion / exclusions
  15550. if (parsedLight.excludedMeshesIds) {
  15551. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15552. }
  15553. if (parsedLight.includedOnlyMeshesIds) {
  15554. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15555. }
  15556. // Parent
  15557. if (parsedLight.parentId) {
  15558. light._waitingParentId = parsedLight.parentId;
  15559. }
  15560. // Animations
  15561. if (parsedLight.animations) {
  15562. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15563. var parsedAnimation = parsedLight.animations[animationIndex];
  15564. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15565. }
  15566. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15567. }
  15568. if (parsedLight.autoAnimate) {
  15569. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15570. }
  15571. return light;
  15572. };
  15573. Light.prototype._hookArrayForExcluded = function (array) {
  15574. var _this = this;
  15575. var oldPush = array.push;
  15576. array.push = function () {
  15577. var items = [];
  15578. for (var _i = 0; _i < arguments.length; _i++) {
  15579. items[_i] = arguments[_i];
  15580. }
  15581. var result = oldPush.apply(array, items);
  15582. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15583. var item = items_1[_a];
  15584. item._resyncLighSource(_this);
  15585. }
  15586. return result;
  15587. };
  15588. var oldSplice = array.splice;
  15589. array.splice = function (index, deleteCount) {
  15590. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15591. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15592. var item = deleted_1[_i];
  15593. item._resyncLighSource(_this);
  15594. }
  15595. return deleted;
  15596. };
  15597. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15598. var item = array_1[_i];
  15599. item._resyncLighSource(this);
  15600. }
  15601. };
  15602. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15603. var _this = this;
  15604. var oldPush = array.push;
  15605. array.push = function () {
  15606. var items = [];
  15607. for (var _i = 0; _i < arguments.length; _i++) {
  15608. items[_i] = arguments[_i];
  15609. }
  15610. var result = oldPush.apply(array, items);
  15611. _this._resyncMeshes();
  15612. return result;
  15613. };
  15614. var oldSplice = array.splice;
  15615. array.splice = function (index, deleteCount) {
  15616. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15617. _this._resyncMeshes();
  15618. return deleted;
  15619. };
  15620. this._resyncMeshes();
  15621. };
  15622. Light.prototype._resyncMeshes = function () {
  15623. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15624. var mesh = _a[_i];
  15625. mesh._resyncLighSource(this);
  15626. }
  15627. };
  15628. Light.prototype._markMeshesAsLightDirty = function () {
  15629. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15630. var mesh = _a[_i];
  15631. if (mesh._lightSources.indexOf(this) !== -1) {
  15632. mesh._markSubMeshesAsLightDirty();
  15633. }
  15634. }
  15635. };
  15636. /**
  15637. * Recomputes the cached photometric scale if needed.
  15638. */
  15639. Light.prototype._computePhotometricScale = function () {
  15640. this._photometricScale = this._getPhotometricScale();
  15641. this.getScene().resetCachedMaterial();
  15642. };
  15643. /**
  15644. * Returns the Photometric Scale according to the light type and intensity mode.
  15645. */
  15646. Light.prototype._getPhotometricScale = function () {
  15647. var photometricScale = 0.0;
  15648. var lightTypeID = this.getTypeID();
  15649. //get photometric mode
  15650. var photometricMode = this.intensityMode;
  15651. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15652. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15653. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15654. }
  15655. else {
  15656. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15657. }
  15658. }
  15659. //compute photometric scale
  15660. switch (lightTypeID) {
  15661. case Light.LIGHTTYPEID_POINTLIGHT:
  15662. case Light.LIGHTTYPEID_SPOTLIGHT:
  15663. switch (photometricMode) {
  15664. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15665. photometricScale = 1.0 / (4.0 * Math.PI);
  15666. break;
  15667. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15668. photometricScale = 1.0;
  15669. break;
  15670. case Light.INTENSITYMODE_LUMINANCE:
  15671. photometricScale = this.radius * this.radius;
  15672. break;
  15673. }
  15674. break;
  15675. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15676. switch (photometricMode) {
  15677. case Light.INTENSITYMODE_ILLUMINANCE:
  15678. photometricScale = 1.0;
  15679. break;
  15680. case Light.INTENSITYMODE_LUMINANCE:
  15681. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15682. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15683. var apexAngleRadians = this.radius;
  15684. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15685. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15686. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15687. photometricScale = solidAngle;
  15688. break;
  15689. }
  15690. break;
  15691. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15692. // No fall off in hemisperic light.
  15693. photometricScale = 1.0;
  15694. break;
  15695. }
  15696. return photometricScale;
  15697. };
  15698. Light.prototype._reorderLightsInScene = function () {
  15699. var scene = this.getScene();
  15700. if (this._renderPriority != 0) {
  15701. scene.requireLightSorting = true;
  15702. }
  15703. this.getScene().sortLightsByPriority();
  15704. };
  15705. //lightmapMode Consts
  15706. Light._LIGHTMAP_DEFAULT = 0;
  15707. Light._LIGHTMAP_SPECULAR = 1;
  15708. Light._LIGHTMAP_SHADOWSONLY = 2;
  15709. // Intensity Mode Consts
  15710. Light._INTENSITYMODE_AUTOMATIC = 0;
  15711. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15712. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15713. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15714. Light._INTENSITYMODE_LUMINANCE = 4;
  15715. // Light types ids const.
  15716. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15717. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15718. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15719. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15720. __decorate([
  15721. BABYLON.serializeAsColor3()
  15722. ], Light.prototype, "diffuse", void 0);
  15723. __decorate([
  15724. BABYLON.serializeAsColor3()
  15725. ], Light.prototype, "specular", void 0);
  15726. __decorate([
  15727. BABYLON.serialize()
  15728. ], Light.prototype, "intensity", void 0);
  15729. __decorate([
  15730. BABYLON.serialize()
  15731. ], Light.prototype, "range", void 0);
  15732. __decorate([
  15733. BABYLON.serialize()
  15734. ], Light.prototype, "intensityMode", null);
  15735. __decorate([
  15736. BABYLON.serialize()
  15737. ], Light.prototype, "radius", null);
  15738. __decorate([
  15739. BABYLON.serialize()
  15740. ], Light.prototype, "_renderPriority", void 0);
  15741. __decorate([
  15742. BABYLON.expandToProperty("_reorderLightsInScene")
  15743. ], Light.prototype, "renderPriority", void 0);
  15744. __decorate([
  15745. BABYLON.serialize()
  15746. ], Light.prototype, "shadowEnabled", void 0);
  15747. __decorate([
  15748. BABYLON.serialize("excludeWithLayerMask")
  15749. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15750. __decorate([
  15751. BABYLON.serialize("includeOnlyWithLayerMask")
  15752. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15753. __decorate([
  15754. BABYLON.serialize("lightmapMode")
  15755. ], Light.prototype, "_lightmapMode", void 0);
  15756. return Light;
  15757. }(BABYLON.Node));
  15758. BABYLON.Light = Light;
  15759. })(BABYLON || (BABYLON = {}));
  15760. //# sourceMappingURL=babylon.light.js.map
  15761. var BABYLON;
  15762. (function (BABYLON) {
  15763. var Camera = /** @class */ (function (_super) {
  15764. __extends(Camera, _super);
  15765. function Camera(name, position, scene) {
  15766. var _this = _super.call(this, name, scene) || this;
  15767. _this.upVector = BABYLON.Vector3.Up();
  15768. _this.orthoLeft = null;
  15769. _this.orthoRight = null;
  15770. _this.orthoBottom = null;
  15771. _this.orthoTop = null;
  15772. _this.fov = 0.8;
  15773. _this.minZ = 1;
  15774. _this.maxZ = 10000.0;
  15775. _this.inertia = 0.9;
  15776. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15777. _this.isIntermediate = false;
  15778. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15779. _this.layerMask = 0x0FFFFFFF;
  15780. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15781. // Camera rig members
  15782. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15783. _this._rigCameras = new Array();
  15784. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15785. _this._skipRendering = false;
  15786. _this.customRenderTargets = new Array();
  15787. // Observables
  15788. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15789. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15790. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15791. _this.onRestoreStateObservable = new BABYLON.Observable();
  15792. // Cache
  15793. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15794. _this._projectionMatrix = new BABYLON.Matrix();
  15795. _this._doNotComputeProjectionMatrix = false;
  15796. _this._postProcesses = new Array();
  15797. _this._transformMatrix = BABYLON.Matrix.Zero();
  15798. _this._activeMeshes = new BABYLON.SmartArray(256);
  15799. _this._globalPosition = BABYLON.Vector3.Zero();
  15800. _this._refreshFrustumPlanes = true;
  15801. _this.getScene().addCamera(_this);
  15802. if (!_this.getScene().activeCamera) {
  15803. _this.getScene().activeCamera = _this;
  15804. }
  15805. _this.position = position;
  15806. return _this;
  15807. }
  15808. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15809. get: function () {
  15810. return Camera._PERSPECTIVE_CAMERA;
  15811. },
  15812. enumerable: true,
  15813. configurable: true
  15814. });
  15815. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15816. get: function () {
  15817. return Camera._ORTHOGRAPHIC_CAMERA;
  15818. },
  15819. enumerable: true,
  15820. configurable: true
  15821. });
  15822. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15823. get: function () {
  15824. return Camera._FOVMODE_VERTICAL_FIXED;
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15830. get: function () {
  15831. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15837. get: function () {
  15838. return Camera._RIG_MODE_NONE;
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15844. get: function () {
  15845. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15846. },
  15847. enumerable: true,
  15848. configurable: true
  15849. });
  15850. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15851. get: function () {
  15852. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15853. },
  15854. enumerable: true,
  15855. configurable: true
  15856. });
  15857. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15858. get: function () {
  15859. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15865. get: function () {
  15866. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15867. },
  15868. enumerable: true,
  15869. configurable: true
  15870. });
  15871. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15872. get: function () {
  15873. return Camera._RIG_MODE_VR;
  15874. },
  15875. enumerable: true,
  15876. configurable: true
  15877. });
  15878. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15879. get: function () {
  15880. return Camera._RIG_MODE_WEBVR;
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. /**
  15886. * Store current camera state (fov, position, etc..)
  15887. */
  15888. Camera.prototype.storeState = function () {
  15889. this._stateStored = true;
  15890. this._storedFov = this.fov;
  15891. return this;
  15892. };
  15893. /**
  15894. * Restores the camera state values if it has been stored. You must call storeState() first
  15895. */
  15896. Camera.prototype._restoreStateValues = function () {
  15897. if (!this._stateStored) {
  15898. return false;
  15899. }
  15900. this.fov = this._storedFov;
  15901. return true;
  15902. };
  15903. /**
  15904. * Restored camera state. You must call storeState() first
  15905. */
  15906. Camera.prototype.restoreState = function () {
  15907. if (this._restoreStateValues()) {
  15908. this.onRestoreStateObservable.notifyObservers(this);
  15909. return true;
  15910. }
  15911. return false;
  15912. };
  15913. Camera.prototype.getClassName = function () {
  15914. return "Camera";
  15915. };
  15916. /**
  15917. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15918. */
  15919. Camera.prototype.toString = function (fullDetails) {
  15920. var ret = "Name: " + this.name;
  15921. ret += ", type: " + this.getClassName();
  15922. if (this.animations) {
  15923. for (var i = 0; i < this.animations.length; i++) {
  15924. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15925. }
  15926. }
  15927. if (fullDetails) {
  15928. }
  15929. return ret;
  15930. };
  15931. Object.defineProperty(Camera.prototype, "globalPosition", {
  15932. get: function () {
  15933. return this._globalPosition;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. Camera.prototype.getActiveMeshes = function () {
  15939. return this._activeMeshes;
  15940. };
  15941. Camera.prototype.isActiveMesh = function (mesh) {
  15942. return (this._activeMeshes.indexOf(mesh) !== -1);
  15943. };
  15944. //Cache
  15945. Camera.prototype._initCache = function () {
  15946. _super.prototype._initCache.call(this);
  15947. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15948. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15949. this._cache.mode = undefined;
  15950. this._cache.minZ = undefined;
  15951. this._cache.maxZ = undefined;
  15952. this._cache.fov = undefined;
  15953. this._cache.fovMode = undefined;
  15954. this._cache.aspectRatio = undefined;
  15955. this._cache.orthoLeft = undefined;
  15956. this._cache.orthoRight = undefined;
  15957. this._cache.orthoBottom = undefined;
  15958. this._cache.orthoTop = undefined;
  15959. this._cache.renderWidth = undefined;
  15960. this._cache.renderHeight = undefined;
  15961. };
  15962. Camera.prototype._updateCache = function (ignoreParentClass) {
  15963. if (!ignoreParentClass) {
  15964. _super.prototype._updateCache.call(this);
  15965. }
  15966. this._cache.position.copyFrom(this.position);
  15967. this._cache.upVector.copyFrom(this.upVector);
  15968. };
  15969. // Synchronized
  15970. Camera.prototype._isSynchronized = function () {
  15971. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15972. };
  15973. Camera.prototype._isSynchronizedViewMatrix = function () {
  15974. if (!_super.prototype._isSynchronized.call(this))
  15975. return false;
  15976. return this._cache.position.equals(this.position)
  15977. && this._cache.upVector.equals(this.upVector)
  15978. && this.isSynchronizedWithParent();
  15979. };
  15980. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15981. var check = this._cache.mode === this.mode
  15982. && this._cache.minZ === this.minZ
  15983. && this._cache.maxZ === this.maxZ;
  15984. if (!check) {
  15985. return false;
  15986. }
  15987. var engine = this.getEngine();
  15988. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15989. check = this._cache.fov === this.fov
  15990. && this._cache.fovMode === this.fovMode
  15991. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15992. }
  15993. else {
  15994. check = this._cache.orthoLeft === this.orthoLeft
  15995. && this._cache.orthoRight === this.orthoRight
  15996. && this._cache.orthoBottom === this.orthoBottom
  15997. && this._cache.orthoTop === this.orthoTop
  15998. && this._cache.renderWidth === engine.getRenderWidth()
  15999. && this._cache.renderHeight === engine.getRenderHeight();
  16000. }
  16001. return check;
  16002. };
  16003. // Controls
  16004. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16005. };
  16006. Camera.prototype.detachControl = function (element) {
  16007. };
  16008. Camera.prototype.update = function () {
  16009. this._checkInputs();
  16010. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16011. this._updateRigCameras();
  16012. }
  16013. };
  16014. Camera.prototype._checkInputs = function () {
  16015. this.onAfterCheckInputsObservable.notifyObservers(this);
  16016. };
  16017. Object.defineProperty(Camera.prototype, "rigCameras", {
  16018. get: function () {
  16019. return this._rigCameras;
  16020. },
  16021. enumerable: true,
  16022. configurable: true
  16023. });
  16024. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16025. get: function () {
  16026. return this._rigPostProcess;
  16027. },
  16028. enumerable: true,
  16029. configurable: true
  16030. });
  16031. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16032. // invalidate framebuffer
  16033. if (this._postProcesses.length > 0) {
  16034. this._postProcesses[0].markTextureDirty();
  16035. }
  16036. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16037. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16038. var cam = this._rigCameras[i];
  16039. var rigPostProcess = cam._rigPostProcess;
  16040. // for VR rig, there does not have to be a post process
  16041. if (rigPostProcess) {
  16042. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16043. if (isPass) {
  16044. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16045. cam.isIntermediate = this._postProcesses.length === 0;
  16046. }
  16047. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16048. rigPostProcess.markTextureDirty();
  16049. }
  16050. else {
  16051. cam._postProcesses = this._postProcesses.slice(0);
  16052. }
  16053. }
  16054. };
  16055. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16056. if (insertAt === void 0) { insertAt = null; }
  16057. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16058. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16059. return 0;
  16060. }
  16061. if (insertAt == null || insertAt < 0) {
  16062. this._postProcesses.push(postProcess);
  16063. }
  16064. else {
  16065. this._postProcesses.splice(insertAt, 0, postProcess);
  16066. }
  16067. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16068. return this._postProcesses.indexOf(postProcess);
  16069. };
  16070. Camera.prototype.detachPostProcess = function (postProcess) {
  16071. var idx = this._postProcesses.indexOf(postProcess);
  16072. if (idx !== -1) {
  16073. this._postProcesses.splice(idx, 1);
  16074. }
  16075. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16076. };
  16077. Camera.prototype.getWorldMatrix = function () {
  16078. if (!this._worldMatrix) {
  16079. this._worldMatrix = BABYLON.Matrix.Identity();
  16080. }
  16081. var viewMatrix = this.getViewMatrix();
  16082. viewMatrix.invertToRef(this._worldMatrix);
  16083. return this._worldMatrix;
  16084. };
  16085. Camera.prototype._getViewMatrix = function () {
  16086. return BABYLON.Matrix.Identity();
  16087. };
  16088. Camera.prototype.getViewMatrix = function (force) {
  16089. if (!force && this._isSynchronizedViewMatrix()) {
  16090. return this._computedViewMatrix;
  16091. }
  16092. this.updateCache();
  16093. this._computedViewMatrix = this._getViewMatrix();
  16094. this._currentRenderId = this.getScene().getRenderId();
  16095. this._refreshFrustumPlanes = true;
  16096. if (!this.parent || !this.parent.getWorldMatrix) {
  16097. this._globalPosition.copyFrom(this.position);
  16098. }
  16099. else {
  16100. if (!this._worldMatrix) {
  16101. this._worldMatrix = BABYLON.Matrix.Identity();
  16102. }
  16103. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16104. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16105. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16106. this._computedViewMatrix.invert();
  16107. this._markSyncedWithParent();
  16108. }
  16109. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16110. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16111. }
  16112. this.onViewMatrixChangedObservable.notifyObservers(this);
  16113. return this._computedViewMatrix;
  16114. };
  16115. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16116. this._doNotComputeProjectionMatrix = true;
  16117. if (projection !== undefined) {
  16118. this._projectionMatrix = projection;
  16119. }
  16120. };
  16121. ;
  16122. Camera.prototype.unfreezeProjectionMatrix = function () {
  16123. this._doNotComputeProjectionMatrix = false;
  16124. };
  16125. ;
  16126. Camera.prototype.getProjectionMatrix = function (force) {
  16127. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16128. return this._projectionMatrix;
  16129. }
  16130. // Cache
  16131. this._cache.mode = this.mode;
  16132. this._cache.minZ = this.minZ;
  16133. this._cache.maxZ = this.maxZ;
  16134. // Matrix
  16135. this._refreshFrustumPlanes = true;
  16136. var engine = this.getEngine();
  16137. var scene = this.getScene();
  16138. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16139. this._cache.fov = this.fov;
  16140. this._cache.fovMode = this.fovMode;
  16141. this._cache.aspectRatio = engine.getAspectRatio(this);
  16142. if (this.minZ <= 0) {
  16143. this.minZ = 0.1;
  16144. }
  16145. if (scene.useRightHandedSystem) {
  16146. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16147. }
  16148. else {
  16149. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16150. }
  16151. }
  16152. else {
  16153. var halfWidth = engine.getRenderWidth() / 2.0;
  16154. var halfHeight = engine.getRenderHeight() / 2.0;
  16155. if (scene.useRightHandedSystem) {
  16156. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16157. }
  16158. else {
  16159. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16160. }
  16161. this._cache.orthoLeft = this.orthoLeft;
  16162. this._cache.orthoRight = this.orthoRight;
  16163. this._cache.orthoBottom = this.orthoBottom;
  16164. this._cache.orthoTop = this.orthoTop;
  16165. this._cache.renderWidth = engine.getRenderWidth();
  16166. this._cache.renderHeight = engine.getRenderHeight();
  16167. }
  16168. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16169. return this._projectionMatrix;
  16170. };
  16171. Camera.prototype.getTranformationMatrix = function () {
  16172. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16173. return this._transformMatrix;
  16174. };
  16175. Camera.prototype.updateFrustumPlanes = function () {
  16176. if (!this._refreshFrustumPlanes) {
  16177. return;
  16178. }
  16179. this.getTranformationMatrix();
  16180. if (!this._frustumPlanes) {
  16181. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16182. }
  16183. else {
  16184. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16185. }
  16186. this._refreshFrustumPlanes = false;
  16187. };
  16188. Camera.prototype.isInFrustum = function (target) {
  16189. this.updateFrustumPlanes();
  16190. return target.isInFrustum(this._frustumPlanes);
  16191. };
  16192. Camera.prototype.isCompletelyInFrustum = function (target) {
  16193. this.updateFrustumPlanes();
  16194. return target.isCompletelyInFrustum(this._frustumPlanes);
  16195. };
  16196. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16197. if (length === void 0) { length = 100; }
  16198. if (!transform) {
  16199. transform = this.getWorldMatrix();
  16200. }
  16201. if (!origin) {
  16202. origin = this.position;
  16203. }
  16204. var forward = new BABYLON.Vector3(0, 0, 1);
  16205. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16206. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16207. return new BABYLON.Ray(origin, direction, length);
  16208. };
  16209. Camera.prototype.dispose = function () {
  16210. // Observables
  16211. this.onViewMatrixChangedObservable.clear();
  16212. this.onProjectionMatrixChangedObservable.clear();
  16213. this.onAfterCheckInputsObservable.clear();
  16214. this.onRestoreStateObservable.clear();
  16215. // Inputs
  16216. if (this.inputs) {
  16217. this.inputs.clear();
  16218. }
  16219. // Animations
  16220. this.getScene().stopAnimation(this);
  16221. // Remove from scene
  16222. this.getScene().removeCamera(this);
  16223. while (this._rigCameras.length > 0) {
  16224. var camera = this._rigCameras.pop();
  16225. if (camera) {
  16226. camera.dispose();
  16227. }
  16228. }
  16229. // Postprocesses
  16230. if (this._rigPostProcess) {
  16231. this._rigPostProcess.dispose(this);
  16232. this._rigPostProcess = null;
  16233. this._postProcesses = [];
  16234. }
  16235. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16236. this._rigPostProcess = null;
  16237. this._postProcesses = [];
  16238. }
  16239. else {
  16240. var i = this._postProcesses.length;
  16241. while (--i >= 0) {
  16242. this._postProcesses[i].dispose(this);
  16243. }
  16244. }
  16245. // Render targets
  16246. var i = this.customRenderTargets.length;
  16247. while (--i >= 0) {
  16248. this.customRenderTargets[i].dispose();
  16249. }
  16250. this.customRenderTargets = [];
  16251. // Active Meshes
  16252. this._activeMeshes.dispose();
  16253. _super.prototype.dispose.call(this);
  16254. };
  16255. Object.defineProperty(Camera.prototype, "leftCamera", {
  16256. // ---- Camera rigs section ----
  16257. get: function () {
  16258. if (this._rigCameras.length < 1) {
  16259. return null;
  16260. }
  16261. return this._rigCameras[0];
  16262. },
  16263. enumerable: true,
  16264. configurable: true
  16265. });
  16266. Object.defineProperty(Camera.prototype, "rightCamera", {
  16267. get: function () {
  16268. if (this._rigCameras.length < 2) {
  16269. return null;
  16270. }
  16271. return this._rigCameras[1];
  16272. },
  16273. enumerable: true,
  16274. configurable: true
  16275. });
  16276. Camera.prototype.getLeftTarget = function () {
  16277. if (this._rigCameras.length < 1) {
  16278. return null;
  16279. }
  16280. return this._rigCameras[0].getTarget();
  16281. };
  16282. Camera.prototype.getRightTarget = function () {
  16283. if (this._rigCameras.length < 2) {
  16284. return null;
  16285. }
  16286. return this._rigCameras[1].getTarget();
  16287. };
  16288. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16289. if (this.cameraRigMode === mode) {
  16290. return;
  16291. }
  16292. while (this._rigCameras.length > 0) {
  16293. var camera = this._rigCameras.pop();
  16294. if (camera) {
  16295. camera.dispose();
  16296. }
  16297. }
  16298. this.cameraRigMode = mode;
  16299. this._cameraRigParams = {};
  16300. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16301. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16302. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16303. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16304. // create the rig cameras, unless none
  16305. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16306. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16307. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16308. if (leftCamera && rightCamera) {
  16309. this._rigCameras.push(leftCamera);
  16310. this._rigCameras.push(rightCamera);
  16311. }
  16312. }
  16313. switch (this.cameraRigMode) {
  16314. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16315. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16316. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16317. break;
  16318. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16319. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16320. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16321. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16322. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16323. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16324. break;
  16325. case Camera.RIG_MODE_VR:
  16326. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16327. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16328. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16329. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16330. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16331. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16332. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16333. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16334. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16335. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16336. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16337. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16338. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16339. if (metrics.compensateDistortion) {
  16340. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16341. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16342. }
  16343. break;
  16344. case Camera.RIG_MODE_WEBVR:
  16345. if (rigParams.vrDisplay) {
  16346. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16347. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16348. //Left eye
  16349. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16350. this._rigCameras[0].setCameraRigParameter("left", true);
  16351. //leaving this for future reference
  16352. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16353. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16354. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16355. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16356. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16357. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16358. this._rigCameras[0].parent = this;
  16359. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16360. //Right eye
  16361. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16362. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16363. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16364. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16365. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16366. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16367. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16368. this._rigCameras[1].parent = this;
  16369. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16370. if (Camera.UseAlternateWebVRRendering) {
  16371. this._rigCameras[1]._skipRendering = true;
  16372. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16373. }
  16374. }
  16375. break;
  16376. }
  16377. this._cascadePostProcessesToRigCams();
  16378. this.update();
  16379. };
  16380. Camera.prototype._getVRProjectionMatrix = function () {
  16381. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16382. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16383. return this._projectionMatrix;
  16384. };
  16385. Camera.prototype._updateCameraRotationMatrix = function () {
  16386. //Here for WebVR
  16387. };
  16388. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16389. //Here for WebVR
  16390. };
  16391. /**
  16392. * This function MUST be overwritten by the different WebVR cameras available.
  16393. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16394. */
  16395. Camera.prototype._getWebVRProjectionMatrix = function () {
  16396. return BABYLON.Matrix.Identity();
  16397. };
  16398. /**
  16399. * This function MUST be overwritten by the different WebVR cameras available.
  16400. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16401. */
  16402. Camera.prototype._getWebVRViewMatrix = function () {
  16403. return BABYLON.Matrix.Identity();
  16404. };
  16405. Camera.prototype.setCameraRigParameter = function (name, value) {
  16406. if (!this._cameraRigParams) {
  16407. this._cameraRigParams = {};
  16408. }
  16409. this._cameraRigParams[name] = value;
  16410. //provisionnally:
  16411. if (name === "interaxialDistance") {
  16412. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16413. }
  16414. };
  16415. /**
  16416. * needs to be overridden by children so sub has required properties to be copied
  16417. */
  16418. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16419. return null;
  16420. };
  16421. /**
  16422. * May need to be overridden by children
  16423. */
  16424. Camera.prototype._updateRigCameras = function () {
  16425. for (var i = 0; i < this._rigCameras.length; i++) {
  16426. this._rigCameras[i].minZ = this.minZ;
  16427. this._rigCameras[i].maxZ = this.maxZ;
  16428. this._rigCameras[i].fov = this.fov;
  16429. }
  16430. // only update viewport when ANAGLYPH
  16431. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16432. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16433. }
  16434. };
  16435. Camera.prototype._setupInputs = function () {
  16436. };
  16437. Camera.prototype.serialize = function () {
  16438. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16439. // Type
  16440. serializationObject.type = this.getClassName();
  16441. // Parent
  16442. if (this.parent) {
  16443. serializationObject.parentId = this.parent.id;
  16444. }
  16445. if (this.inputs) {
  16446. this.inputs.serialize(serializationObject);
  16447. }
  16448. // Animations
  16449. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16450. serializationObject.ranges = this.serializeAnimationRanges();
  16451. return serializationObject;
  16452. };
  16453. Camera.prototype.clone = function (name) {
  16454. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16455. };
  16456. Camera.prototype.getDirection = function (localAxis) {
  16457. var result = BABYLON.Vector3.Zero();
  16458. this.getDirectionToRef(localAxis, result);
  16459. return result;
  16460. };
  16461. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16462. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16463. };
  16464. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16465. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16466. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16467. switch (type) {
  16468. case "ArcRotateCamera":
  16469. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16470. case "DeviceOrientationCamera":
  16471. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16472. case "FollowCamera":
  16473. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16474. case "ArcFollowCamera":
  16475. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16476. case "GamepadCamera":
  16477. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16478. case "TouchCamera":
  16479. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16480. case "VirtualJoysticksCamera":
  16481. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16482. case "WebVRFreeCamera":
  16483. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16484. case "WebVRGamepadCamera":
  16485. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16486. case "VRDeviceOrientationFreeCamera":
  16487. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16488. case "VRDeviceOrientationGamepadCamera":
  16489. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16490. case "AnaglyphArcRotateCamera":
  16491. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16492. case "AnaglyphFreeCamera":
  16493. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16494. case "AnaglyphGamepadCamera":
  16495. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16496. case "AnaglyphUniversalCamera":
  16497. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16498. case "StereoscopicArcRotateCamera":
  16499. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16500. case "StereoscopicFreeCamera":
  16501. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16502. case "StereoscopicGamepadCamera":
  16503. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16504. case "StereoscopicUniversalCamera":
  16505. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16506. case "FreeCamera":// Forcing Universal here
  16507. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16508. default:// Universal Camera is the default value
  16509. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16510. }
  16511. };
  16512. Camera.Parse = function (parsedCamera, scene) {
  16513. var type = parsedCamera.type;
  16514. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16515. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16516. // Parent
  16517. if (parsedCamera.parentId) {
  16518. camera._waitingParentId = parsedCamera.parentId;
  16519. }
  16520. //If camera has an input manager, let it parse inputs settings
  16521. if (camera.inputs) {
  16522. camera.inputs.parse(parsedCamera);
  16523. camera._setupInputs();
  16524. }
  16525. if (camera.setPosition) {
  16526. camera.position.copyFromFloats(0, 0, 0);
  16527. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16528. }
  16529. // Target
  16530. if (parsedCamera.target) {
  16531. if (camera.setTarget) {
  16532. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16533. }
  16534. }
  16535. // Apply 3d rig, when found
  16536. if (parsedCamera.cameraRigMode) {
  16537. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16538. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16539. }
  16540. // Animations
  16541. if (parsedCamera.animations) {
  16542. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16543. var parsedAnimation = parsedCamera.animations[animationIndex];
  16544. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16545. }
  16546. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16547. }
  16548. if (parsedCamera.autoAnimate) {
  16549. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16550. }
  16551. return camera;
  16552. };
  16553. // Statics
  16554. Camera._PERSPECTIVE_CAMERA = 0;
  16555. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16556. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16557. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16558. Camera._RIG_MODE_NONE = 0;
  16559. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16560. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16561. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16562. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16563. Camera._RIG_MODE_VR = 20;
  16564. Camera._RIG_MODE_WEBVR = 21;
  16565. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16566. Camera.UseAlternateWebVRRendering = false;
  16567. __decorate([
  16568. BABYLON.serializeAsVector3()
  16569. ], Camera.prototype, "position", void 0);
  16570. __decorate([
  16571. BABYLON.serializeAsVector3()
  16572. ], Camera.prototype, "upVector", void 0);
  16573. __decorate([
  16574. BABYLON.serialize()
  16575. ], Camera.prototype, "orthoLeft", void 0);
  16576. __decorate([
  16577. BABYLON.serialize()
  16578. ], Camera.prototype, "orthoRight", void 0);
  16579. __decorate([
  16580. BABYLON.serialize()
  16581. ], Camera.prototype, "orthoBottom", void 0);
  16582. __decorate([
  16583. BABYLON.serialize()
  16584. ], Camera.prototype, "orthoTop", void 0);
  16585. __decorate([
  16586. BABYLON.serialize()
  16587. ], Camera.prototype, "fov", void 0);
  16588. __decorate([
  16589. BABYLON.serialize()
  16590. ], Camera.prototype, "minZ", void 0);
  16591. __decorate([
  16592. BABYLON.serialize()
  16593. ], Camera.prototype, "maxZ", void 0);
  16594. __decorate([
  16595. BABYLON.serialize()
  16596. ], Camera.prototype, "inertia", void 0);
  16597. __decorate([
  16598. BABYLON.serialize()
  16599. ], Camera.prototype, "mode", void 0);
  16600. __decorate([
  16601. BABYLON.serialize()
  16602. ], Camera.prototype, "layerMask", void 0);
  16603. __decorate([
  16604. BABYLON.serialize()
  16605. ], Camera.prototype, "fovMode", void 0);
  16606. __decorate([
  16607. BABYLON.serialize()
  16608. ], Camera.prototype, "cameraRigMode", void 0);
  16609. __decorate([
  16610. BABYLON.serialize()
  16611. ], Camera.prototype, "interaxialDistance", void 0);
  16612. __decorate([
  16613. BABYLON.serialize()
  16614. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16615. return Camera;
  16616. }(BABYLON.Node));
  16617. BABYLON.Camera = Camera;
  16618. })(BABYLON || (BABYLON = {}));
  16619. //# sourceMappingURL=babylon.camera.js.map
  16620. var BABYLON;
  16621. (function (BABYLON) {
  16622. var RenderingManager = /** @class */ (function () {
  16623. function RenderingManager(scene) {
  16624. this._renderingGroups = new Array();
  16625. this._autoClearDepthStencil = {};
  16626. this._customOpaqueSortCompareFn = {};
  16627. this._customAlphaTestSortCompareFn = {};
  16628. this._customTransparentSortCompareFn = {};
  16629. this._renderinGroupInfo = null;
  16630. this._scene = scene;
  16631. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16632. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16633. }
  16634. }
  16635. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16636. if (depth === void 0) { depth = true; }
  16637. if (stencil === void 0) { stencil = true; }
  16638. if (this._depthStencilBufferAlreadyCleaned) {
  16639. return;
  16640. }
  16641. this._scene.getEngine().clear(null, false, depth, stencil);
  16642. this._depthStencilBufferAlreadyCleaned = true;
  16643. };
  16644. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16645. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16646. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16647. var info = null;
  16648. if (observable) {
  16649. if (!this._renderinGroupInfo) {
  16650. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16651. }
  16652. info = this._renderinGroupInfo;
  16653. info.scene = this._scene;
  16654. info.camera = this._scene.activeCamera;
  16655. }
  16656. // Dispatch sprites
  16657. if (renderSprites) {
  16658. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16659. var manager = this._scene.spriteManagers[index];
  16660. this.dispatchSprites(manager);
  16661. }
  16662. }
  16663. // Render
  16664. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16665. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16666. var renderingGroup = this._renderingGroups[index];
  16667. if (!renderingGroup && !observable)
  16668. continue;
  16669. this._currentIndex = index;
  16670. var renderingGroupMask = 0;
  16671. // Fire PRECLEAR stage
  16672. if (observable && info) {
  16673. renderingGroupMask = Math.pow(2, index);
  16674. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16675. info.renderingGroupId = index;
  16676. observable.notifyObservers(info, renderingGroupMask);
  16677. }
  16678. // Clear depth/stencil if needed
  16679. if (RenderingManager.AUTOCLEAR) {
  16680. var autoClear = this._autoClearDepthStencil[index];
  16681. if (autoClear && autoClear.autoClear) {
  16682. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16683. }
  16684. }
  16685. if (observable && info) {
  16686. // Fire PREOPAQUE stage
  16687. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16688. observable.notifyObservers(info, renderingGroupMask);
  16689. // Fire PRETRANSPARENT stage
  16690. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16691. observable.notifyObservers(info, renderingGroupMask);
  16692. }
  16693. if (renderingGroup)
  16694. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16695. // Fire POSTTRANSPARENT stage
  16696. if (observable && info) {
  16697. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16698. observable.notifyObservers(info, renderingGroupMask);
  16699. }
  16700. }
  16701. };
  16702. RenderingManager.prototype.reset = function () {
  16703. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16704. var renderingGroup = this._renderingGroups[index];
  16705. if (renderingGroup) {
  16706. renderingGroup.prepare();
  16707. }
  16708. }
  16709. };
  16710. RenderingManager.prototype.dispose = function () {
  16711. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16712. var renderingGroup = this._renderingGroups[index];
  16713. if (renderingGroup) {
  16714. renderingGroup.dispose();
  16715. }
  16716. }
  16717. this._renderingGroups.length = 0;
  16718. };
  16719. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16720. if (!this._renderingGroups[renderingGroupId]) {
  16721. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16722. }
  16723. };
  16724. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16725. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16726. this._prepareRenderingGroup(renderingGroupId);
  16727. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16728. };
  16729. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16730. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16731. this._prepareRenderingGroup(renderingGroupId);
  16732. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16733. };
  16734. RenderingManager.prototype.dispatch = function (subMesh) {
  16735. var mesh = subMesh.getMesh();
  16736. var renderingGroupId = mesh.renderingGroupId || 0;
  16737. this._prepareRenderingGroup(renderingGroupId);
  16738. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16739. };
  16740. /**
  16741. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16742. * This allowed control for front to back rendering or reversly depending of the special needs.
  16743. *
  16744. * @param renderingGroupId The rendering group id corresponding to its index
  16745. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16746. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16747. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16748. */
  16749. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16750. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16751. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16752. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16753. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16754. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16755. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16756. if (this._renderingGroups[renderingGroupId]) {
  16757. var group = this._renderingGroups[renderingGroupId];
  16758. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16759. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16760. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16761. }
  16762. };
  16763. /**
  16764. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16765. *
  16766. * @param renderingGroupId The rendering group id corresponding to its index
  16767. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16768. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16769. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16770. */
  16771. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16772. if (depth === void 0) { depth = true; }
  16773. if (stencil === void 0) { stencil = true; }
  16774. this._autoClearDepthStencil[renderingGroupId] = {
  16775. autoClear: autoClearDepthStencil,
  16776. depth: depth,
  16777. stencil: stencil
  16778. };
  16779. };
  16780. /**
  16781. * The max id used for rendering groups (not included)
  16782. */
  16783. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16784. /**
  16785. * The min id used for rendering groups (included)
  16786. */
  16787. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16788. /**
  16789. * Used to globally prevent autoclearing scenes.
  16790. */
  16791. RenderingManager.AUTOCLEAR = true;
  16792. return RenderingManager;
  16793. }());
  16794. BABYLON.RenderingManager = RenderingManager;
  16795. })(BABYLON || (BABYLON = {}));
  16796. //# sourceMappingURL=babylon.renderingManager.js.map
  16797. var BABYLON;
  16798. (function (BABYLON) {
  16799. var RenderingGroup = /** @class */ (function () {
  16800. /**
  16801. * Creates a new rendering group.
  16802. * @param index The rendering group index
  16803. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16804. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16805. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16806. */
  16807. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16808. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16809. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16810. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16811. this.index = index;
  16812. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16813. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16814. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16815. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16816. this._particleSystems = new BABYLON.SmartArray(256);
  16817. this._spriteManagers = new BABYLON.SmartArray(256);
  16818. this._edgesRenderers = new BABYLON.SmartArray(16);
  16819. this._scene = scene;
  16820. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16821. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16822. this.transparentSortCompareFn = transparentSortCompareFn;
  16823. }
  16824. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16825. /**
  16826. * Set the opaque sort comparison function.
  16827. * If null the sub meshes will be render in the order they were created
  16828. */
  16829. set: function (value) {
  16830. this._opaqueSortCompareFn = value;
  16831. if (value) {
  16832. this._renderOpaque = this.renderOpaqueSorted;
  16833. }
  16834. else {
  16835. this._renderOpaque = RenderingGroup.renderUnsorted;
  16836. }
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16842. /**
  16843. * Set the alpha test sort comparison function.
  16844. * If null the sub meshes will be render in the order they were created
  16845. */
  16846. set: function (value) {
  16847. this._alphaTestSortCompareFn = value;
  16848. if (value) {
  16849. this._renderAlphaTest = this.renderAlphaTestSorted;
  16850. }
  16851. else {
  16852. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16853. }
  16854. },
  16855. enumerable: true,
  16856. configurable: true
  16857. });
  16858. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16859. /**
  16860. * Set the transparent sort comparison function.
  16861. * If null the sub meshes will be render in the order they were created
  16862. */
  16863. set: function (value) {
  16864. if (value) {
  16865. this._transparentSortCompareFn = value;
  16866. }
  16867. else {
  16868. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16869. }
  16870. this._renderTransparent = this.renderTransparentSorted;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. /**
  16876. * Render all the sub meshes contained in the group.
  16877. * @param customRenderFunction Used to override the default render behaviour of the group.
  16878. * @returns true if rendered some submeshes.
  16879. */
  16880. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16881. if (customRenderFunction) {
  16882. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16883. return;
  16884. }
  16885. var engine = this._scene.getEngine();
  16886. // Depth only
  16887. if (this._depthOnlySubMeshes.length !== 0) {
  16888. engine.setAlphaTesting(true);
  16889. engine.setColorWrite(false);
  16890. this._renderAlphaTest(this._depthOnlySubMeshes);
  16891. engine.setAlphaTesting(false);
  16892. engine.setColorWrite(true);
  16893. }
  16894. // Opaque
  16895. if (this._opaqueSubMeshes.length !== 0) {
  16896. this._renderOpaque(this._opaqueSubMeshes);
  16897. }
  16898. // Alpha test
  16899. if (this._alphaTestSubMeshes.length !== 0) {
  16900. engine.setAlphaTesting(true);
  16901. this._renderAlphaTest(this._alphaTestSubMeshes);
  16902. engine.setAlphaTesting(false);
  16903. }
  16904. var stencilState = engine.getStencilBuffer();
  16905. engine.setStencilBuffer(false);
  16906. // Sprites
  16907. if (renderSprites) {
  16908. this._renderSprites();
  16909. }
  16910. // Particles
  16911. if (renderParticles) {
  16912. this._renderParticles(activeMeshes);
  16913. }
  16914. if (this.onBeforeTransparentRendering) {
  16915. this.onBeforeTransparentRendering();
  16916. }
  16917. // Transparent
  16918. if (this._transparentSubMeshes.length !== 0) {
  16919. this._renderTransparent(this._transparentSubMeshes);
  16920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16921. }
  16922. // Set back stencil to false in case it changes before the edge renderer.
  16923. engine.setStencilBuffer(false);
  16924. // Edges
  16925. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16926. this._edgesRenderers.data[edgesRendererIndex].render();
  16927. }
  16928. // Restore Stencil state.
  16929. engine.setStencilBuffer(stencilState);
  16930. };
  16931. /**
  16932. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16933. * @param subMeshes The submeshes to render
  16934. */
  16935. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16936. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16937. };
  16938. /**
  16939. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16940. * @param subMeshes The submeshes to render
  16941. */
  16942. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16943. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16944. };
  16945. /**
  16946. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16947. * @param subMeshes The submeshes to render
  16948. */
  16949. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16950. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16951. };
  16952. /**
  16953. * Renders the submeshes in a specified order.
  16954. * @param subMeshes The submeshes to sort before render
  16955. * @param sortCompareFn The comparison function use to sort
  16956. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16957. * @param transparent Specifies to activate blending if true
  16958. */
  16959. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16960. var subIndex = 0;
  16961. var subMesh;
  16962. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16963. for (; subIndex < subMeshes.length; subIndex++) {
  16964. subMesh = subMeshes.data[subIndex];
  16965. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16966. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16967. }
  16968. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16969. if (sortCompareFn) {
  16970. sortedArray.sort(sortCompareFn);
  16971. }
  16972. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16973. subMesh = sortedArray[subIndex];
  16974. if (transparent) {
  16975. var material = subMesh.getMaterial();
  16976. if (material && material.needDepthPrePass) {
  16977. var engine = material.getScene().getEngine();
  16978. engine.setColorWrite(false);
  16979. engine.setAlphaTesting(true);
  16980. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16981. subMesh.render(false);
  16982. engine.setAlphaTesting(false);
  16983. engine.setColorWrite(true);
  16984. }
  16985. }
  16986. subMesh.render(transparent);
  16987. }
  16988. };
  16989. /**
  16990. * Renders the submeshes in the order they were dispatched (no sort applied).
  16991. * @param subMeshes The submeshes to render
  16992. */
  16993. RenderingGroup.renderUnsorted = function (subMeshes) {
  16994. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16995. var submesh = subMeshes.data[subIndex];
  16996. submesh.render(false);
  16997. }
  16998. };
  16999. /**
  17000. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17001. * are rendered back to front if in the same alpha index.
  17002. *
  17003. * @param a The first submesh
  17004. * @param b The second submesh
  17005. * @returns The result of the comparison
  17006. */
  17007. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17008. // Alpha index first
  17009. if (a._alphaIndex > b._alphaIndex) {
  17010. return 1;
  17011. }
  17012. if (a._alphaIndex < b._alphaIndex) {
  17013. return -1;
  17014. }
  17015. // Then distance to camera
  17016. return RenderingGroup.backToFrontSortCompare(a, b);
  17017. };
  17018. /**
  17019. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17020. * are rendered back to front.
  17021. *
  17022. * @param a The first submesh
  17023. * @param b The second submesh
  17024. * @returns The result of the comparison
  17025. */
  17026. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17027. // Then distance to camera
  17028. if (a._distanceToCamera < b._distanceToCamera) {
  17029. return 1;
  17030. }
  17031. if (a._distanceToCamera > b._distanceToCamera) {
  17032. return -1;
  17033. }
  17034. return 0;
  17035. };
  17036. /**
  17037. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17038. * are rendered front to back (prevent overdraw).
  17039. *
  17040. * @param a The first submesh
  17041. * @param b The second submesh
  17042. * @returns The result of the comparison
  17043. */
  17044. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17045. // Then distance to camera
  17046. if (a._distanceToCamera < b._distanceToCamera) {
  17047. return -1;
  17048. }
  17049. if (a._distanceToCamera > b._distanceToCamera) {
  17050. return 1;
  17051. }
  17052. return 0;
  17053. };
  17054. /**
  17055. * Resets the different lists of submeshes to prepare a new frame.
  17056. */
  17057. RenderingGroup.prototype.prepare = function () {
  17058. this._opaqueSubMeshes.reset();
  17059. this._transparentSubMeshes.reset();
  17060. this._alphaTestSubMeshes.reset();
  17061. this._depthOnlySubMeshes.reset();
  17062. this._particleSystems.reset();
  17063. this._spriteManagers.reset();
  17064. this._edgesRenderers.reset();
  17065. };
  17066. RenderingGroup.prototype.dispose = function () {
  17067. this._opaqueSubMeshes.dispose();
  17068. this._transparentSubMeshes.dispose();
  17069. this._alphaTestSubMeshes.dispose();
  17070. this._depthOnlySubMeshes.dispose();
  17071. this._particleSystems.dispose();
  17072. this._spriteManagers.dispose();
  17073. this._edgesRenderers.dispose();
  17074. };
  17075. /**
  17076. * Inserts the submesh in its correct queue depending on its material.
  17077. * @param subMesh The submesh to dispatch
  17078. */
  17079. RenderingGroup.prototype.dispatch = function (subMesh) {
  17080. var material = subMesh.getMaterial();
  17081. var mesh = subMesh.getMesh();
  17082. if (!material) {
  17083. return;
  17084. }
  17085. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17086. this._transparentSubMeshes.push(subMesh);
  17087. }
  17088. else if (material.needAlphaTesting()) {
  17089. if (material.needDepthPrePass) {
  17090. this._depthOnlySubMeshes.push(subMesh);
  17091. }
  17092. this._alphaTestSubMeshes.push(subMesh);
  17093. }
  17094. else {
  17095. if (material.needDepthPrePass) {
  17096. this._depthOnlySubMeshes.push(subMesh);
  17097. }
  17098. this._opaqueSubMeshes.push(subMesh); // Opaque
  17099. }
  17100. if (mesh._edgesRenderer) {
  17101. this._edgesRenderers.push(mesh._edgesRenderer);
  17102. }
  17103. };
  17104. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17105. this._spriteManagers.push(spriteManager);
  17106. };
  17107. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17108. this._particleSystems.push(particleSystem);
  17109. };
  17110. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17111. if (this._particleSystems.length === 0) {
  17112. return;
  17113. }
  17114. // Particles
  17115. var activeCamera = this._scene.activeCamera;
  17116. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17117. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17118. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17119. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17120. continue;
  17121. }
  17122. var emitter = particleSystem.emitter;
  17123. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17124. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17125. }
  17126. }
  17127. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17128. };
  17129. RenderingGroup.prototype._renderSprites = function () {
  17130. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17131. return;
  17132. }
  17133. // Sprites
  17134. var activeCamera = this._scene.activeCamera;
  17135. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17136. for (var id = 0; id < this._spriteManagers.length; id++) {
  17137. var spriteManager = this._spriteManagers.data[id];
  17138. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17139. spriteManager.render();
  17140. }
  17141. }
  17142. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17143. };
  17144. return RenderingGroup;
  17145. }());
  17146. BABYLON.RenderingGroup = RenderingGroup;
  17147. })(BABYLON || (BABYLON = {}));
  17148. //# sourceMappingURL=babylon.renderingGroup.js.map
  17149. var BABYLON;
  17150. (function (BABYLON) {
  17151. var ClickInfo = /** @class */ (function () {
  17152. function ClickInfo() {
  17153. this._singleClick = false;
  17154. this._doubleClick = false;
  17155. this._hasSwiped = false;
  17156. this._ignore = false;
  17157. }
  17158. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17159. get: function () {
  17160. return this._singleClick;
  17161. },
  17162. set: function (b) {
  17163. this._singleClick = b;
  17164. },
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17169. get: function () {
  17170. return this._doubleClick;
  17171. },
  17172. set: function (b) {
  17173. this._doubleClick = b;
  17174. },
  17175. enumerable: true,
  17176. configurable: true
  17177. });
  17178. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17179. get: function () {
  17180. return this._hasSwiped;
  17181. },
  17182. set: function (b) {
  17183. this._hasSwiped = b;
  17184. },
  17185. enumerable: true,
  17186. configurable: true
  17187. });
  17188. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17189. get: function () {
  17190. return this._ignore;
  17191. },
  17192. set: function (b) {
  17193. this._ignore = b;
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. return ClickInfo;
  17199. }());
  17200. /**
  17201. * This class is used by the onRenderingGroupObservable
  17202. */
  17203. var RenderingGroupInfo = /** @class */ (function () {
  17204. function RenderingGroupInfo() {
  17205. }
  17206. /**
  17207. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17208. * This stage will be fired no matter what
  17209. */
  17210. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17211. /**
  17212. * Called before opaque object are rendered.
  17213. * This stage will be fired only if there's 3D Opaque content to render
  17214. */
  17215. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17216. /**
  17217. * Called after the opaque objects are rendered and before the transparent ones
  17218. * This stage will be fired only if there's 3D transparent content to render
  17219. */
  17220. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17221. /**
  17222. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17223. * This stage will be fired no matter what
  17224. */
  17225. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17226. return RenderingGroupInfo;
  17227. }());
  17228. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17229. /**
  17230. * Represents a scene to be rendered by the engine.
  17231. * @see http://doc.babylonjs.com/page.php?p=21911
  17232. */
  17233. var Scene = /** @class */ (function () {
  17234. /**
  17235. * @constructor
  17236. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17237. */
  17238. function Scene(engine) {
  17239. // Members
  17240. this.autoClear = true;
  17241. this.autoClearDepthAndStencil = true;
  17242. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17243. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17244. this.forceWireframe = false;
  17245. this._forcePointsCloud = false;
  17246. this.forceShowBoundingBoxes = false;
  17247. this.animationsEnabled = true;
  17248. this.constantlyUpdateMeshUnderPointer = false;
  17249. this.hoverCursor = "pointer";
  17250. this.defaultCursor = "";
  17251. /**
  17252. * This is used to call preventDefault() on pointer down
  17253. * in order to block unwanted artifacts like system double clicks
  17254. */
  17255. this.preventDefaultOnPointerDown = true;
  17256. // Metadata
  17257. this.metadata = null;
  17258. /**
  17259. * An event triggered when the scene is disposed.
  17260. * @type {BABYLON.Observable}
  17261. */
  17262. this.onDisposeObservable = new BABYLON.Observable();
  17263. /**
  17264. * An event triggered before rendering the scene (right after animations and physics)
  17265. * @type {BABYLON.Observable}
  17266. */
  17267. this.onBeforeRenderObservable = new BABYLON.Observable();
  17268. /**
  17269. * An event triggered after rendering the scene
  17270. * @type {BABYLON.Observable}
  17271. */
  17272. this.onAfterRenderObservable = new BABYLON.Observable();
  17273. /**
  17274. * An event triggered before animating the scene
  17275. * @type {BABYLON.Observable}
  17276. */
  17277. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17278. /**
  17279. * An event triggered before draw calls are ready to be sent
  17280. * @type {BABYLON.Observable}
  17281. */
  17282. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17283. /**
  17284. * An event triggered after draw calls have been sent
  17285. * @type {BABYLON.Observable}
  17286. */
  17287. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17288. /**
  17289. * An event triggered when physic simulation is about to be run
  17290. * @type {BABYLON.Observable}
  17291. */
  17292. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17293. /**
  17294. * An event triggered when physic simulation has been done
  17295. * @type {BABYLON.Observable}
  17296. */
  17297. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17298. /**
  17299. * An event triggered when the scene is ready
  17300. * @type {BABYLON.Observable}
  17301. */
  17302. this.onReadyObservable = new BABYLON.Observable();
  17303. /**
  17304. * An event triggered before rendering a camera
  17305. * @type {BABYLON.Observable}
  17306. */
  17307. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17308. /**
  17309. * An event triggered after rendering a camera
  17310. * @type {BABYLON.Observable}
  17311. */
  17312. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17313. /**
  17314. * An event triggered when active meshes evaluation is about to start
  17315. * @type {BABYLON.Observable}
  17316. */
  17317. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17318. /**
  17319. * An event triggered when active meshes evaluation is done
  17320. * @type {BABYLON.Observable}
  17321. */
  17322. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17323. /**
  17324. * An event triggered when particles rendering is about to start
  17325. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17326. * @type {BABYLON.Observable}
  17327. */
  17328. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17329. /**
  17330. * An event triggered when particles rendering is done
  17331. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17332. * @type {BABYLON.Observable}
  17333. */
  17334. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17335. /**
  17336. * An event triggered when sprites rendering is about to start
  17337. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17338. * @type {BABYLON.Observable}
  17339. */
  17340. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17341. /**
  17342. * An event triggered when sprites rendering is done
  17343. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered when a camera is created
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17352. /**
  17353. * An event triggered when a camera is removed
  17354. * @type {BABYLON.Observable}
  17355. */
  17356. this.onCameraRemovedObservable = new BABYLON.Observable();
  17357. /**
  17358. * An event triggered when a light is created
  17359. * @type {BABYLON.Observable}
  17360. */
  17361. this.onNewLightAddedObservable = new BABYLON.Observable();
  17362. /**
  17363. * An event triggered when a light is removed
  17364. * @type {BABYLON.Observable}
  17365. */
  17366. this.onLightRemovedObservable = new BABYLON.Observable();
  17367. /**
  17368. * An event triggered when a geometry is created
  17369. * @type {BABYLON.Observable}
  17370. */
  17371. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17372. /**
  17373. * An event triggered when a geometry is removed
  17374. * @type {BABYLON.Observable}
  17375. */
  17376. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17377. /**
  17378. * An event triggered when a mesh is created
  17379. * @type {BABYLON.Observable}
  17380. */
  17381. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17382. /**
  17383. * An event triggered when a mesh is removed
  17384. * @type {BABYLON.Observable}
  17385. */
  17386. this.onMeshRemovedObservable = new BABYLON.Observable();
  17387. /**
  17388. * An event triggered when render targets are about to be rendered
  17389. * Can happen multiple times per frame.
  17390. * @type {BABYLON.Observable}
  17391. */
  17392. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17393. /**
  17394. * An event triggered when render targets were rendered.
  17395. * Can happen multiple times per frame.
  17396. * @type {BABYLON.Observable}
  17397. */
  17398. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17399. /**
  17400. * An event triggered before calculating deterministic simulation step
  17401. * @type {BABYLON.Observable}
  17402. */
  17403. this.onBeforeStepObservable = new BABYLON.Observable();
  17404. /**
  17405. * An event triggered after calculating deterministic simulation step
  17406. * @type {BABYLON.Observable}
  17407. */
  17408. this.onAfterStepObservable = new BABYLON.Observable();
  17409. /**
  17410. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17411. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17412. * 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)
  17413. */
  17414. this.onRenderingGroupObservable = new BABYLON.Observable();
  17415. // Animations
  17416. this.animations = [];
  17417. /**
  17418. * 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).
  17419. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17420. */
  17421. this.onPrePointerObservable = new BABYLON.Observable();
  17422. /**
  17423. * Observable event triggered each time an input event is received from the rendering canvas
  17424. */
  17425. this.onPointerObservable = new BABYLON.Observable();
  17426. this._meshPickProceed = false;
  17427. this._previousHasSwiped = false;
  17428. this._currentPickResult = null;
  17429. this._previousPickResult = null;
  17430. this._totalPointersPressed = 0;
  17431. this._doubleClickOccured = false;
  17432. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17433. this.cameraToUseForPointers = null;
  17434. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17435. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17436. this._startingPointerTime = 0;
  17437. this._previousStartingPointerTime = 0;
  17438. // Deterministic lockstep
  17439. this._timeAccumulator = 0;
  17440. this._currentStepId = 0;
  17441. this._currentInternalStep = 0;
  17442. // Keyboard
  17443. /**
  17444. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17445. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17446. */
  17447. this.onPreKeyboardObservable = new BABYLON.Observable();
  17448. /**
  17449. * Observable event triggered each time an keyboard event is received from the hosting window
  17450. */
  17451. this.onKeyboardObservable = new BABYLON.Observable();
  17452. // Coordinate system
  17453. /**
  17454. * use right-handed coordinate system on this scene.
  17455. * @type {boolean}
  17456. */
  17457. this._useRightHandedSystem = false;
  17458. // Fog
  17459. this._fogEnabled = true;
  17460. this._fogMode = Scene.FOGMODE_NONE;
  17461. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17462. this.fogDensity = 0.1;
  17463. this.fogStart = 0;
  17464. this.fogEnd = 1000.0;
  17465. // Lights
  17466. /**
  17467. * is shadow enabled on this scene.
  17468. * @type {boolean}
  17469. */
  17470. this._shadowsEnabled = true;
  17471. /**
  17472. * is light enabled on this scene.
  17473. * @type {boolean}
  17474. */
  17475. this._lightsEnabled = true;
  17476. /**
  17477. * All of the lights added to this scene.
  17478. * @see BABYLON.Light
  17479. * @type {BABYLON.Light[]}
  17480. */
  17481. this.lights = new Array();
  17482. // Cameras
  17483. /** All of the cameras added to this scene. */
  17484. this.cameras = new Array();
  17485. /** All of the active cameras added to this scene. */
  17486. this.activeCameras = new Array();
  17487. // Meshes
  17488. /**
  17489. * All of the (abstract) meshes added to this scene.
  17490. * @see BABYLON.AbstractMesh
  17491. * @type {BABYLON.AbstractMesh[]}
  17492. */
  17493. this.meshes = new Array();
  17494. // Geometries
  17495. this._geometries = new Array();
  17496. this.materials = new Array();
  17497. this.multiMaterials = new Array();
  17498. // Textures
  17499. this._texturesEnabled = true;
  17500. this.textures = new Array();
  17501. // Particles
  17502. this.particlesEnabled = true;
  17503. this.particleSystems = new Array();
  17504. // Sprites
  17505. this.spritesEnabled = true;
  17506. this.spriteManagers = new Array();
  17507. // Layers
  17508. this.layers = new Array();
  17509. this.highlightLayers = new Array();
  17510. // Skeletons
  17511. this._skeletonsEnabled = true;
  17512. this.skeletons = new Array();
  17513. // Morph targets
  17514. this.morphTargetManagers = new Array();
  17515. // Lens flares
  17516. this.lensFlaresEnabled = true;
  17517. this.lensFlareSystems = new Array();
  17518. // Collisions
  17519. this.collisionsEnabled = true;
  17520. /** Defines the gravity applied to this scene */
  17521. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17522. // Postprocesses
  17523. this.postProcesses = new Array();
  17524. this.postProcessesEnabled = true;
  17525. // Customs render targets
  17526. this.renderTargetsEnabled = true;
  17527. this.dumpNextRenderTargets = false;
  17528. this.customRenderTargets = new Array();
  17529. // Imported meshes
  17530. this.importedMeshesFiles = new Array();
  17531. // Probes
  17532. this.probesEnabled = true;
  17533. this.reflectionProbes = new Array();
  17534. this._actionManagers = new Array();
  17535. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17536. // Procedural textures
  17537. this.proceduralTexturesEnabled = true;
  17538. this._proceduralTextures = new Array();
  17539. this.soundTracks = new Array();
  17540. this._audioEnabled = true;
  17541. this._headphone = false;
  17542. // Performance counters
  17543. this._totalVertices = new BABYLON.PerfCounter();
  17544. this._activeIndices = new BABYLON.PerfCounter();
  17545. this._activeParticles = new BABYLON.PerfCounter();
  17546. this._activeBones = new BABYLON.PerfCounter();
  17547. this._animationTime = 0;
  17548. this.animationTimeScale = 1;
  17549. this._renderId = 0;
  17550. this._executeWhenReadyTimeoutId = -1;
  17551. this._intermediateRendering = false;
  17552. this._viewUpdateFlag = -1;
  17553. this._projectionUpdateFlag = -1;
  17554. this._alternateViewUpdateFlag = -1;
  17555. this._alternateProjectionUpdateFlag = -1;
  17556. this._toBeDisposed = new BABYLON.SmartArray(256);
  17557. this._pendingData = new Array();
  17558. this._isDisposed = false;
  17559. this._activeMeshes = new BABYLON.SmartArray(256);
  17560. this._processedMaterials = new BABYLON.SmartArray(256);
  17561. this._renderTargets = new BABYLON.SmartArray(256);
  17562. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17563. this._activeSkeletons = new BABYLON.SmartArray(32);
  17564. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17565. this._activeAnimatables = new Array();
  17566. this._transformMatrix = BABYLON.Matrix.Zero();
  17567. this._useAlternateCameraConfiguration = false;
  17568. this._alternateRendering = false;
  17569. this.requireLightSorting = false;
  17570. this._activeMeshesFrozen = false;
  17571. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17572. this._engine.scenes.push(this);
  17573. this._uid = null;
  17574. this._renderingManager = new BABYLON.RenderingManager(this);
  17575. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17576. if (BABYLON.OutlineRenderer) {
  17577. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17578. }
  17579. if (BABYLON.Tools.IsWindowObjectExist()) {
  17580. this.attachControl();
  17581. }
  17582. //simplification queue
  17583. if (BABYLON.SimplificationQueue) {
  17584. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17585. }
  17586. //collision coordinator initialization. For now legacy per default.
  17587. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17588. // Uniform Buffer
  17589. this._createUbo();
  17590. // Default Image processing definition.
  17591. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17592. }
  17593. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17594. /** The fog is deactivated */
  17595. get: function () {
  17596. return Scene._FOGMODE_NONE;
  17597. },
  17598. enumerable: true,
  17599. configurable: true
  17600. });
  17601. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17602. /** The fog density is following an exponential function */
  17603. get: function () {
  17604. return Scene._FOGMODE_EXP;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17610. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17611. get: function () {
  17612. return Scene._FOGMODE_EXP2;
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17618. /** The fog density is following a linear function. */
  17619. get: function () {
  17620. return Scene._FOGMODE_LINEAR;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17626. /**
  17627. * Texture used in all pbr material as the reflection texture.
  17628. * As in the majority of the scene they are the same (exception for multi room and so on),
  17629. * this is easier to reference from here than from all the materials.
  17630. */
  17631. get: function () {
  17632. return this._environmentTexture;
  17633. },
  17634. /**
  17635. * Texture used in all pbr material as the reflection texture.
  17636. * As in the majority of the scene they are the same (exception for multi room and so on),
  17637. * this is easier to set here than in all the materials.
  17638. */
  17639. set: function (value) {
  17640. if (this._environmentTexture === value) {
  17641. return;
  17642. }
  17643. this._environmentTexture = value;
  17644. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17650. /**
  17651. * Default image processing configuration used either in the rendering
  17652. * Forward main pass or through the imageProcessingPostProcess if present.
  17653. * As in the majority of the scene they are the same (exception for multi camera),
  17654. * this is easier to reference from here than from all the materials and post process.
  17655. *
  17656. * No setter as we it is a shared configuration, you can set the values instead.
  17657. */
  17658. get: function () {
  17659. return this._imageProcessingConfiguration;
  17660. },
  17661. enumerable: true,
  17662. configurable: true
  17663. });
  17664. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17665. get: function () {
  17666. return this._forcePointsCloud;
  17667. },
  17668. set: function (value) {
  17669. if (this._forcePointsCloud === value) {
  17670. return;
  17671. }
  17672. this._forcePointsCloud = value;
  17673. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(Scene.prototype, "onDispose", {
  17679. /** A function to be executed when this scene is disposed. */
  17680. set: function (callback) {
  17681. if (this._onDisposeObserver) {
  17682. this.onDisposeObservable.remove(this._onDisposeObserver);
  17683. }
  17684. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(Scene.prototype, "beforeRender", {
  17690. /** A function to be executed before rendering this scene */
  17691. set: function (callback) {
  17692. if (this._onBeforeRenderObserver) {
  17693. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17694. }
  17695. if (callback) {
  17696. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17697. }
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(Scene.prototype, "afterRender", {
  17703. /** A function to be executed after rendering this scene */
  17704. set: function (callback) {
  17705. if (this._onAfterRenderObserver) {
  17706. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17707. }
  17708. if (callback) {
  17709. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17710. }
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17716. set: function (callback) {
  17717. if (this._onBeforeCameraRenderObserver) {
  17718. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17719. }
  17720. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17726. set: function (callback) {
  17727. if (this._onAfterCameraRenderObserver) {
  17728. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17729. }
  17730. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17736. get: function () {
  17737. if (!this._gamepadManager) {
  17738. this._gamepadManager = new BABYLON.GamepadManager();
  17739. }
  17740. return this._gamepadManager;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17746. get: function () {
  17747. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17753. get: function () {
  17754. return this._useRightHandedSystem;
  17755. },
  17756. set: function (value) {
  17757. if (this._useRightHandedSystem === value) {
  17758. return;
  17759. }
  17760. this._useRightHandedSystem = value;
  17761. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Scene.prototype.setStepId = function (newStepId) {
  17767. this._currentStepId = newStepId;
  17768. };
  17769. ;
  17770. Scene.prototype.getStepId = function () {
  17771. return this._currentStepId;
  17772. };
  17773. ;
  17774. Scene.prototype.getInternalStep = function () {
  17775. return this._currentInternalStep;
  17776. };
  17777. ;
  17778. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17779. get: function () {
  17780. return this._fogEnabled;
  17781. },
  17782. /**
  17783. * is fog enabled on this scene.
  17784. */
  17785. set: function (value) {
  17786. if (this._fogEnabled === value) {
  17787. return;
  17788. }
  17789. this._fogEnabled = value;
  17790. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Scene.prototype, "fogMode", {
  17796. get: function () {
  17797. return this._fogMode;
  17798. },
  17799. set: function (value) {
  17800. if (this._fogMode === value) {
  17801. return;
  17802. }
  17803. this._fogMode = value;
  17804. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17810. get: function () {
  17811. return this._shadowsEnabled;
  17812. },
  17813. set: function (value) {
  17814. if (this._shadowsEnabled === value) {
  17815. return;
  17816. }
  17817. this._shadowsEnabled = value;
  17818. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17824. get: function () {
  17825. return this._lightsEnabled;
  17826. },
  17827. set: function (value) {
  17828. if (this._lightsEnabled === value) {
  17829. return;
  17830. }
  17831. this._lightsEnabled = value;
  17832. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17833. },
  17834. enumerable: true,
  17835. configurable: true
  17836. });
  17837. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17838. /** The default material used on meshes when no material is affected */
  17839. get: function () {
  17840. if (!this._defaultMaterial) {
  17841. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17842. }
  17843. return this._defaultMaterial;
  17844. },
  17845. /** The default material used on meshes when no material is affected */
  17846. set: function (value) {
  17847. this._defaultMaterial = value;
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17853. get: function () {
  17854. return this._texturesEnabled;
  17855. },
  17856. set: function (value) {
  17857. if (this._texturesEnabled === value) {
  17858. return;
  17859. }
  17860. this._texturesEnabled = value;
  17861. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17867. get: function () {
  17868. return this._skeletonsEnabled;
  17869. },
  17870. set: function (value) {
  17871. if (this._skeletonsEnabled === value) {
  17872. return;
  17873. }
  17874. this._skeletonsEnabled = value;
  17875. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17881. get: function () {
  17882. if (!this._postProcessRenderPipelineManager) {
  17883. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17884. }
  17885. return this._postProcessRenderPipelineManager;
  17886. },
  17887. enumerable: true,
  17888. configurable: true
  17889. });
  17890. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17891. get: function () {
  17892. if (!this._mainSoundTrack) {
  17893. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17894. }
  17895. return this._mainSoundTrack;
  17896. },
  17897. enumerable: true,
  17898. configurable: true
  17899. });
  17900. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17901. get: function () {
  17902. return this._alternateRendering;
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17908. get: function () {
  17909. return this._frustumPlanes;
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(Scene.prototype, "debugLayer", {
  17915. // Properties
  17916. get: function () {
  17917. if (!this._debugLayer) {
  17918. this._debugLayer = new BABYLON.DebugLayer(this);
  17919. }
  17920. return this._debugLayer;
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17926. get: function () {
  17927. return this._workerCollisions;
  17928. },
  17929. set: function (enabled) {
  17930. if (!BABYLON.CollisionCoordinatorLegacy) {
  17931. return;
  17932. }
  17933. enabled = (enabled && !!Worker);
  17934. this._workerCollisions = enabled;
  17935. if (this.collisionCoordinator) {
  17936. this.collisionCoordinator.destroy();
  17937. }
  17938. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17939. this.collisionCoordinator.init(this);
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17945. get: function () {
  17946. return this._selectionOctree;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17952. /**
  17953. * The mesh that is currently under the pointer.
  17954. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17955. */
  17956. get: function () {
  17957. return this._pointerOverMesh;
  17958. },
  17959. enumerable: true,
  17960. configurable: true
  17961. });
  17962. Object.defineProperty(Scene.prototype, "pointerX", {
  17963. /**
  17964. * Current on-screen X position of the pointer
  17965. * @return {number} X position of the pointer
  17966. */
  17967. get: function () {
  17968. return this._pointerX;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. Object.defineProperty(Scene.prototype, "pointerY", {
  17974. /**
  17975. * Current on-screen Y position of the pointer
  17976. * @return {number} Y position of the pointer
  17977. */
  17978. get: function () {
  17979. return this._pointerY;
  17980. },
  17981. enumerable: true,
  17982. configurable: true
  17983. });
  17984. Scene.prototype.getCachedMaterial = function () {
  17985. return this._cachedMaterial;
  17986. };
  17987. Scene.prototype.getCachedEffect = function () {
  17988. return this._cachedEffect;
  17989. };
  17990. Scene.prototype.getCachedVisibility = function () {
  17991. return this._cachedVisibility;
  17992. };
  17993. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17994. if (visibility === void 0) { visibility = 1; }
  17995. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17996. };
  17997. Scene.prototype.getBoundingBoxRenderer = function () {
  17998. if (!this._boundingBoxRenderer) {
  17999. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18000. }
  18001. return this._boundingBoxRenderer;
  18002. };
  18003. Scene.prototype.getOutlineRenderer = function () {
  18004. return this._outlineRenderer;
  18005. };
  18006. Scene.prototype.getEngine = function () {
  18007. return this._engine;
  18008. };
  18009. Scene.prototype.getTotalVertices = function () {
  18010. return this._totalVertices.current;
  18011. };
  18012. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18013. get: function () {
  18014. return this._totalVertices;
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Scene.prototype.getActiveIndices = function () {
  18020. return this._activeIndices.current;
  18021. };
  18022. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18023. get: function () {
  18024. return this._activeIndices;
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Scene.prototype.getActiveParticles = function () {
  18030. return this._activeParticles.current;
  18031. };
  18032. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18033. get: function () {
  18034. return this._activeParticles;
  18035. },
  18036. enumerable: true,
  18037. configurable: true
  18038. });
  18039. Scene.prototype.getActiveBones = function () {
  18040. return this._activeBones.current;
  18041. };
  18042. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18043. get: function () {
  18044. return this._activeBones;
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. // Stats
  18050. Scene.prototype.getInterFramePerfCounter = function () {
  18051. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18052. return 0;
  18053. };
  18054. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18055. get: function () {
  18056. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18057. return null;
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. Scene.prototype.getLastFrameDuration = function () {
  18063. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18064. return 0;
  18065. };
  18066. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18067. get: function () {
  18068. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18069. return null;
  18070. },
  18071. enumerable: true,
  18072. configurable: true
  18073. });
  18074. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18075. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18076. return 0;
  18077. };
  18078. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18079. get: function () {
  18080. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18081. return null;
  18082. },
  18083. enumerable: true,
  18084. configurable: true
  18085. });
  18086. Scene.prototype.getActiveMeshes = function () {
  18087. return this._activeMeshes;
  18088. };
  18089. Scene.prototype.getRenderTargetsDuration = function () {
  18090. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18091. return 0;
  18092. };
  18093. Scene.prototype.getRenderDuration = function () {
  18094. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18095. return 0;
  18096. };
  18097. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18098. get: function () {
  18099. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18100. return null;
  18101. },
  18102. enumerable: true,
  18103. configurable: true
  18104. });
  18105. Scene.prototype.getParticlesDuration = function () {
  18106. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18107. return 0;
  18108. };
  18109. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18110. get: function () {
  18111. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18112. return null;
  18113. },
  18114. enumerable: true,
  18115. configurable: true
  18116. });
  18117. Scene.prototype.getSpritesDuration = function () {
  18118. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18119. return 0;
  18120. };
  18121. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18122. get: function () {
  18123. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18124. return null;
  18125. },
  18126. enumerable: true,
  18127. configurable: true
  18128. });
  18129. Scene.prototype.getAnimationRatio = function () {
  18130. return this._animationRatio;
  18131. };
  18132. Scene.prototype.getRenderId = function () {
  18133. return this._renderId;
  18134. };
  18135. Scene.prototype.incrementRenderId = function () {
  18136. this._renderId++;
  18137. };
  18138. Scene.prototype._updatePointerPosition = function (evt) {
  18139. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18140. if (!canvasRect) {
  18141. return;
  18142. }
  18143. this._pointerX = evt.clientX - canvasRect.left;
  18144. this._pointerY = evt.clientY - canvasRect.top;
  18145. this._unTranslatedPointerX = this._pointerX;
  18146. this._unTranslatedPointerY = this._pointerY;
  18147. };
  18148. Scene.prototype._createUbo = function () {
  18149. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18150. this._sceneUbo.addUniform("viewProjection", 16);
  18151. this._sceneUbo.addUniform("view", 16);
  18152. };
  18153. Scene.prototype._createAlternateUbo = function () {
  18154. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18155. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18156. this._alternateSceneUbo.addUniform("view", 16);
  18157. };
  18158. // Pointers handling
  18159. /**
  18160. * Use this method to simulate a pointer move on a mesh
  18161. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18162. */
  18163. Scene.prototype.simulatePointerMove = function (pickResult) {
  18164. var evt = new PointerEvent("pointermove");
  18165. return this._processPointerMove(pickResult, evt);
  18166. };
  18167. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18168. var canvas = this._engine.getRenderingCanvas();
  18169. if (!canvas) {
  18170. return this;
  18171. }
  18172. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18173. this.setPointerOverSprite(null);
  18174. this.setPointerOverMesh(pickResult.pickedMesh);
  18175. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18176. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18177. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18178. }
  18179. else {
  18180. canvas.style.cursor = this.hoverCursor;
  18181. }
  18182. }
  18183. else {
  18184. canvas.style.cursor = this.defaultCursor;
  18185. }
  18186. }
  18187. else {
  18188. this.setPointerOverMesh(null);
  18189. // Sprites
  18190. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18191. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18192. this.setPointerOverSprite(pickResult.pickedSprite);
  18193. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18194. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18195. }
  18196. else {
  18197. canvas.style.cursor = this.hoverCursor;
  18198. }
  18199. }
  18200. else {
  18201. this.setPointerOverSprite(null);
  18202. // Restore pointer
  18203. canvas.style.cursor = this.defaultCursor;
  18204. }
  18205. }
  18206. if (pickResult) {
  18207. if (this.onPointerMove) {
  18208. this.onPointerMove(evt, pickResult);
  18209. }
  18210. if (this.onPointerObservable.hasObservers()) {
  18211. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18212. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18213. this.onPointerObservable.notifyObservers(pi, type);
  18214. }
  18215. }
  18216. return this;
  18217. };
  18218. /**
  18219. * Use this method to simulate a pointer down on a mesh
  18220. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18221. */
  18222. Scene.prototype.simulatePointerDown = function (pickResult) {
  18223. var evt = new PointerEvent("pointerdown");
  18224. return this._processPointerDown(pickResult, evt);
  18225. };
  18226. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18227. var _this = this;
  18228. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18229. this._pickedDownMesh = pickResult.pickedMesh;
  18230. var actionManager = pickResult.pickedMesh.actionManager;
  18231. if (actionManager) {
  18232. if (actionManager.hasPickTriggers) {
  18233. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18234. switch (evt.button) {
  18235. case 0:
  18236. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18237. break;
  18238. case 1:
  18239. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18240. break;
  18241. case 2:
  18242. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18243. break;
  18244. }
  18245. }
  18246. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18247. window.setTimeout(function () {
  18248. 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);
  18249. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18250. if (_this._totalPointersPressed !== 0 &&
  18251. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18252. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18253. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18254. _this._startingPointerTime = 0;
  18255. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18256. }
  18257. }
  18258. }, Scene.LongPressDelay);
  18259. }
  18260. }
  18261. }
  18262. if (pickResult) {
  18263. if (this.onPointerDown) {
  18264. this.onPointerDown(evt, pickResult);
  18265. }
  18266. if (this.onPointerObservable.hasObservers()) {
  18267. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18268. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18269. this.onPointerObservable.notifyObservers(pi, type);
  18270. }
  18271. }
  18272. return this;
  18273. };
  18274. /**
  18275. * Use this method to simulate a pointer up on a mesh
  18276. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18277. */
  18278. Scene.prototype.simulatePointerUp = function (pickResult) {
  18279. var evt = new PointerEvent("pointerup");
  18280. var clickInfo = new ClickInfo();
  18281. clickInfo.singleClick = true;
  18282. return this._processPointerUp(pickResult, evt, clickInfo);
  18283. };
  18284. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18285. if (pickResult && pickResult && pickResult.pickedMesh) {
  18286. this._pickedUpMesh = pickResult.pickedMesh;
  18287. if (this._pickedDownMesh === this._pickedUpMesh) {
  18288. if (this.onPointerPick) {
  18289. this.onPointerPick(evt, pickResult);
  18290. }
  18291. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18292. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18293. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18294. this.onPointerObservable.notifyObservers(pi, type);
  18295. }
  18296. }
  18297. if (pickResult.pickedMesh.actionManager) {
  18298. if (clickInfo.ignore) {
  18299. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18300. }
  18301. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18302. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18303. }
  18304. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18305. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18306. }
  18307. }
  18308. }
  18309. if (this._pickedDownMesh &&
  18310. this._pickedDownMesh.actionManager &&
  18311. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18312. this._pickedDownMesh !== this._pickedUpMesh) {
  18313. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18314. }
  18315. if (this.onPointerUp) {
  18316. this.onPointerUp(evt, pickResult);
  18317. }
  18318. if (this.onPointerObservable.hasObservers()) {
  18319. if (!clickInfo.ignore) {
  18320. if (!clickInfo.hasSwiped) {
  18321. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18322. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18323. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18324. this.onPointerObservable.notifyObservers(pi, type);
  18325. }
  18326. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18327. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18328. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18329. this.onPointerObservable.notifyObservers(pi, type);
  18330. }
  18331. }
  18332. }
  18333. else {
  18334. var type = BABYLON.PointerEventTypes.POINTERUP;
  18335. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18336. this.onPointerObservable.notifyObservers(pi, type);
  18337. }
  18338. }
  18339. return this;
  18340. };
  18341. /**
  18342. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18343. * @param attachUp defines if you want to attach events to pointerup
  18344. * @param attachDown defines if you want to attach events to pointerdown
  18345. * @param attachMove defines if you want to attach events to pointermove
  18346. */
  18347. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18348. var _this = this;
  18349. if (attachUp === void 0) { attachUp = true; }
  18350. if (attachDown === void 0) { attachDown = true; }
  18351. if (attachMove === void 0) { attachMove = true; }
  18352. this._initActionManager = function (act, clickInfo) {
  18353. if (!_this._meshPickProceed) {
  18354. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18355. _this._currentPickResult = pickResult;
  18356. if (pickResult) {
  18357. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18358. }
  18359. _this._meshPickProceed = true;
  18360. }
  18361. return act;
  18362. };
  18363. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18364. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18365. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18366. btn !== _this._previousButtonPressed) {
  18367. _this._doubleClickOccured = false;
  18368. clickInfo.singleClick = true;
  18369. clickInfo.ignore = false;
  18370. cb(clickInfo, _this._currentPickResult);
  18371. }
  18372. };
  18373. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18374. var clickInfo = new ClickInfo();
  18375. _this._currentPickResult = null;
  18376. var act = null;
  18377. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18378. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18379. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18380. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18381. act = _this._initActionManager(act, clickInfo);
  18382. if (act)
  18383. checkPicking = act.hasPickTriggers;
  18384. }
  18385. if (checkPicking) {
  18386. var btn = evt.button;
  18387. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18388. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18389. if (!clickInfo.hasSwiped) {
  18390. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18391. if (!checkSingleClickImmediately) {
  18392. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18393. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18394. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18395. act = _this._initActionManager(act, clickInfo);
  18396. if (act)
  18397. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18398. }
  18399. }
  18400. if (checkSingleClickImmediately) {
  18401. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18402. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18403. btn !== _this._previousButtonPressed) {
  18404. clickInfo.singleClick = true;
  18405. cb(clickInfo, _this._currentPickResult);
  18406. }
  18407. }
  18408. else {
  18409. // wait that no double click has been raised during the double click delay
  18410. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18411. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18412. }
  18413. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18414. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18415. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18416. act = _this._initActionManager(act, clickInfo);
  18417. if (act)
  18418. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18419. }
  18420. if (checkDoubleClick) {
  18421. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18422. if (btn === _this._previousButtonPressed &&
  18423. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18424. !_this._doubleClickOccured) {
  18425. // pointer has not moved for 2 clicks, it's a double click
  18426. if (!clickInfo.hasSwiped &&
  18427. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18428. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18429. _this._previousStartingPointerTime = 0;
  18430. _this._doubleClickOccured = true;
  18431. clickInfo.doubleClick = true;
  18432. clickInfo.ignore = false;
  18433. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18434. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18435. }
  18436. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18437. cb(clickInfo, _this._currentPickResult);
  18438. }
  18439. else {
  18440. _this._doubleClickOccured = false;
  18441. _this._previousStartingPointerTime = _this._startingPointerTime;
  18442. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18443. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18444. _this._previousButtonPressed = btn;
  18445. _this._previousHasSwiped = clickInfo.hasSwiped;
  18446. if (Scene.ExclusiveDoubleClickMode) {
  18447. if (_this._previousDelayedSimpleClickTimeout) {
  18448. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18449. }
  18450. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18451. cb(clickInfo, _this._previousPickResult);
  18452. }
  18453. else {
  18454. cb(clickInfo, _this._currentPickResult);
  18455. }
  18456. }
  18457. }
  18458. else {
  18459. _this._doubleClickOccured = false;
  18460. _this._previousStartingPointerTime = _this._startingPointerTime;
  18461. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18462. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18463. _this._previousButtonPressed = btn;
  18464. _this._previousHasSwiped = clickInfo.hasSwiped;
  18465. }
  18466. }
  18467. }
  18468. }
  18469. clickInfo.ignore = true;
  18470. cb(clickInfo, _this._currentPickResult);
  18471. };
  18472. this._spritePredicate = function (sprite) {
  18473. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18474. };
  18475. this._onPointerMove = function (evt) {
  18476. _this._updatePointerPosition(evt);
  18477. // PreObservable support
  18478. if (_this.onPrePointerObservable.hasObservers()) {
  18479. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18480. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18481. _this.onPrePointerObservable.notifyObservers(pi, type);
  18482. if (pi.skipOnPointerObservable) {
  18483. return;
  18484. }
  18485. }
  18486. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18487. return;
  18488. }
  18489. if (!_this.pointerMovePredicate) {
  18490. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18491. }
  18492. // Meshes
  18493. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18494. _this._processPointerMove(pickResult, evt);
  18495. };
  18496. this._onPointerDown = function (evt) {
  18497. _this._totalPointersPressed++;
  18498. _this._pickedDownMesh = null;
  18499. _this._meshPickProceed = false;
  18500. _this._updatePointerPosition(evt);
  18501. if (_this.preventDefaultOnPointerDown && canvas) {
  18502. evt.preventDefault();
  18503. canvas.focus();
  18504. }
  18505. // PreObservable support
  18506. if (_this.onPrePointerObservable.hasObservers()) {
  18507. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18508. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18509. _this.onPrePointerObservable.notifyObservers(pi, type);
  18510. if (pi.skipOnPointerObservable) {
  18511. return;
  18512. }
  18513. }
  18514. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18515. return;
  18516. }
  18517. _this._startingPointerPosition.x = _this._pointerX;
  18518. _this._startingPointerPosition.y = _this._pointerY;
  18519. _this._startingPointerTime = new Date().getTime();
  18520. if (!_this.pointerDownPredicate) {
  18521. _this.pointerDownPredicate = function (mesh) {
  18522. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18523. };
  18524. }
  18525. // Meshes
  18526. _this._pickedDownMesh = null;
  18527. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18528. _this._processPointerDown(pickResult, evt);
  18529. // Sprites
  18530. _this._pickedDownSprite = null;
  18531. if (_this.spriteManagers.length > 0) {
  18532. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18533. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18534. if (pickResult.pickedSprite.actionManager) {
  18535. _this._pickedDownSprite = pickResult.pickedSprite;
  18536. switch (evt.button) {
  18537. case 0:
  18538. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18539. break;
  18540. case 1:
  18541. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18542. break;
  18543. case 2:
  18544. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18545. break;
  18546. }
  18547. if (pickResult.pickedSprite.actionManager) {
  18548. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18549. }
  18550. }
  18551. }
  18552. }
  18553. };
  18554. this._onPointerUp = function (evt) {
  18555. if (_this._totalPointersPressed === 0) {
  18556. return; // So we need to test it the pointer down was pressed before.
  18557. }
  18558. _this._totalPointersPressed--;
  18559. _this._pickedUpMesh = null;
  18560. _this._meshPickProceed = false;
  18561. _this._updatePointerPosition(evt);
  18562. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18563. // PreObservable support
  18564. if (_this.onPrePointerObservable.hasObservers()) {
  18565. if (!clickInfo.ignore) {
  18566. if (!clickInfo.hasSwiped) {
  18567. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18568. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18569. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18570. _this.onPrePointerObservable.notifyObservers(pi, type);
  18571. if (pi.skipOnPointerObservable) {
  18572. return;
  18573. }
  18574. }
  18575. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18576. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18577. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18578. _this.onPrePointerObservable.notifyObservers(pi, type);
  18579. if (pi.skipOnPointerObservable) {
  18580. return;
  18581. }
  18582. }
  18583. }
  18584. }
  18585. else {
  18586. var type = BABYLON.PointerEventTypes.POINTERUP;
  18587. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18588. _this.onPrePointerObservable.notifyObservers(pi, type);
  18589. if (pi.skipOnPointerObservable) {
  18590. return;
  18591. }
  18592. }
  18593. }
  18594. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18595. return;
  18596. }
  18597. if (!_this.pointerUpPredicate) {
  18598. _this.pointerUpPredicate = function (mesh) {
  18599. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18600. };
  18601. }
  18602. // Meshes
  18603. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18604. _this._initActionManager(null, clickInfo);
  18605. }
  18606. if (!pickResult) {
  18607. pickResult = _this._currentPickResult;
  18608. }
  18609. _this._processPointerUp(pickResult, evt, clickInfo);
  18610. // Sprites
  18611. if (_this.spriteManagers.length > 0) {
  18612. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18613. if (spritePickResult) {
  18614. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18615. if (spritePickResult.pickedSprite.actionManager) {
  18616. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18617. if (spritePickResult.pickedSprite.actionManager) {
  18618. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18619. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18620. }
  18621. }
  18622. }
  18623. }
  18624. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18625. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18626. }
  18627. }
  18628. }
  18629. _this._previousPickResult = _this._currentPickResult;
  18630. });
  18631. };
  18632. this._onKeyDown = function (evt) {
  18633. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18634. if (_this.onPreKeyboardObservable.hasObservers()) {
  18635. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18636. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18637. if (pi.skipOnPointerObservable) {
  18638. return;
  18639. }
  18640. }
  18641. if (_this.onKeyboardObservable.hasObservers()) {
  18642. var pi = new BABYLON.KeyboardInfo(type, evt);
  18643. _this.onKeyboardObservable.notifyObservers(pi, type);
  18644. }
  18645. if (_this.actionManager) {
  18646. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18647. }
  18648. };
  18649. this._onKeyUp = function (evt) {
  18650. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18651. if (_this.onPreKeyboardObservable.hasObservers()) {
  18652. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18653. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18654. if (pi.skipOnPointerObservable) {
  18655. return;
  18656. }
  18657. }
  18658. if (_this.onKeyboardObservable.hasObservers()) {
  18659. var pi = new BABYLON.KeyboardInfo(type, evt);
  18660. _this.onKeyboardObservable.notifyObservers(pi, type);
  18661. }
  18662. if (_this.actionManager) {
  18663. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18664. }
  18665. };
  18666. var engine = this.getEngine();
  18667. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18668. if (!canvas) {
  18669. return;
  18670. }
  18671. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18672. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18673. });
  18674. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18675. if (!canvas) {
  18676. return;
  18677. }
  18678. canvas.removeEventListener("keydown", _this._onKeyDown);
  18679. canvas.removeEventListener("keyup", _this._onKeyUp);
  18680. });
  18681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18682. var canvas = this._engine.getRenderingCanvas();
  18683. if (!canvas) {
  18684. return;
  18685. }
  18686. if (attachMove) {
  18687. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18688. // Wheel
  18689. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18690. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18691. }
  18692. if (attachDown) {
  18693. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18694. }
  18695. if (attachUp) {
  18696. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18697. }
  18698. canvas.tabIndex = 1;
  18699. };
  18700. Scene.prototype.detachControl = function () {
  18701. var engine = this.getEngine();
  18702. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18703. var canvas = engine.getRenderingCanvas();
  18704. if (!canvas) {
  18705. return;
  18706. }
  18707. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18708. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18709. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18710. if (this._onCanvasBlurObserver) {
  18711. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18712. }
  18713. if (this._onCanvasFocusObserver) {
  18714. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18715. }
  18716. // Wheel
  18717. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18718. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18719. // Keyboard
  18720. canvas.removeEventListener("keydown", this._onKeyDown);
  18721. canvas.removeEventListener("keyup", this._onKeyUp);
  18722. // Observables
  18723. this.onKeyboardObservable.clear();
  18724. this.onPreKeyboardObservable.clear();
  18725. this.onPointerObservable.clear();
  18726. this.onPrePointerObservable.clear();
  18727. };
  18728. // Ready
  18729. Scene.prototype.isReady = function () {
  18730. if (this._isDisposed) {
  18731. return false;
  18732. }
  18733. if (this._pendingData.length > 0) {
  18734. return false;
  18735. }
  18736. var index;
  18737. // Geometries
  18738. for (index = 0; index < this._geometries.length; index++) {
  18739. var geometry = this._geometries[index];
  18740. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18741. return false;
  18742. }
  18743. }
  18744. // Meshes
  18745. for (index = 0; index < this.meshes.length; index++) {
  18746. var mesh = this.meshes[index];
  18747. if (!mesh.isEnabled()) {
  18748. continue;
  18749. }
  18750. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18751. continue;
  18752. }
  18753. if (!mesh.isReady()) {
  18754. return false;
  18755. }
  18756. var mat = mesh.material;
  18757. if (mat) {
  18758. if (!mat.isReady(mesh)) {
  18759. return false;
  18760. }
  18761. }
  18762. }
  18763. return true;
  18764. };
  18765. Scene.prototype.resetCachedMaterial = function () {
  18766. this._cachedMaterial = null;
  18767. this._cachedEffect = null;
  18768. this._cachedVisibility = null;
  18769. };
  18770. Scene.prototype.registerBeforeRender = function (func) {
  18771. this.onBeforeRenderObservable.add(func);
  18772. };
  18773. Scene.prototype.unregisterBeforeRender = function (func) {
  18774. this.onBeforeRenderObservable.removeCallback(func);
  18775. };
  18776. Scene.prototype.registerAfterRender = function (func) {
  18777. this.onAfterRenderObservable.add(func);
  18778. };
  18779. Scene.prototype.unregisterAfterRender = function (func) {
  18780. this.onAfterRenderObservable.removeCallback(func);
  18781. };
  18782. Scene.prototype._addPendingData = function (data) {
  18783. this._pendingData.push(data);
  18784. };
  18785. Scene.prototype._removePendingData = function (data) {
  18786. var index = this._pendingData.indexOf(data);
  18787. if (index !== -1) {
  18788. this._pendingData.splice(index, 1);
  18789. }
  18790. };
  18791. Scene.prototype.getWaitingItemsCount = function () {
  18792. return this._pendingData.length;
  18793. };
  18794. /**
  18795. * Registers a function to be executed when the scene is ready.
  18796. * @param {Function} func - the function to be executed.
  18797. */
  18798. Scene.prototype.executeWhenReady = function (func) {
  18799. var _this = this;
  18800. this.onReadyObservable.add(func);
  18801. if (this._executeWhenReadyTimeoutId !== -1) {
  18802. return;
  18803. }
  18804. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18805. _this._checkIsReady();
  18806. }, 150);
  18807. };
  18808. Scene.prototype._checkIsReady = function () {
  18809. var _this = this;
  18810. if (this.isReady()) {
  18811. this.onReadyObservable.notifyObservers(this);
  18812. this.onReadyObservable.clear();
  18813. this._executeWhenReadyTimeoutId = -1;
  18814. return;
  18815. }
  18816. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18817. _this._checkIsReady();
  18818. }, 150);
  18819. };
  18820. // Animations
  18821. /**
  18822. * Will start the animation sequence of a given target
  18823. * @param target - the target
  18824. * @param {number} from - from which frame should animation start
  18825. * @param {number} to - till which frame should animation run.
  18826. * @param {boolean} [loop] - should the animation loop
  18827. * @param {number} [speedRatio] - the speed in which to run the animation
  18828. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18829. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18830. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18831. * See BABYLON.Animatable
  18832. */
  18833. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18834. if (speedRatio === void 0) { speedRatio = 1.0; }
  18835. if (from > to && speedRatio > 0) {
  18836. speedRatio *= -1;
  18837. }
  18838. this.stopAnimation(target);
  18839. if (!animatable) {
  18840. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18841. }
  18842. // Local animations
  18843. if (target.animations) {
  18844. animatable.appendAnimations(target, target.animations);
  18845. }
  18846. // Children animations
  18847. if (target.getAnimatables) {
  18848. var animatables = target.getAnimatables();
  18849. for (var index = 0; index < animatables.length; index++) {
  18850. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18851. }
  18852. }
  18853. animatable.reset();
  18854. return animatable;
  18855. };
  18856. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18857. if (speedRatio === undefined) {
  18858. speedRatio = 1.0;
  18859. }
  18860. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18861. return animatable;
  18862. };
  18863. Scene.prototype.getAnimatableByTarget = function (target) {
  18864. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18865. if (this._activeAnimatables[index].target === target) {
  18866. return this._activeAnimatables[index];
  18867. }
  18868. }
  18869. return null;
  18870. };
  18871. Object.defineProperty(Scene.prototype, "Animatables", {
  18872. get: function () {
  18873. return this._activeAnimatables;
  18874. },
  18875. enumerable: true,
  18876. configurable: true
  18877. });
  18878. /**
  18879. * Will stop the animation of the given target
  18880. * @param target - the target
  18881. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18882. * @see beginAnimation
  18883. */
  18884. Scene.prototype.stopAnimation = function (target, animationName) {
  18885. var animatable = this.getAnimatableByTarget(target);
  18886. if (animatable) {
  18887. animatable.stop(animationName);
  18888. }
  18889. };
  18890. Scene.prototype._animate = function () {
  18891. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18892. return;
  18893. }
  18894. // Getting time
  18895. var now = BABYLON.Tools.Now;
  18896. if (!this._animationTimeLast) {
  18897. if (this._pendingData.length > 0) {
  18898. return;
  18899. }
  18900. this._animationTimeLast = now;
  18901. }
  18902. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18903. this._animationTime += deltaTime;
  18904. this._animationTimeLast = now;
  18905. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18906. this._activeAnimatables[index]._animate(this._animationTime);
  18907. }
  18908. };
  18909. // Matrix
  18910. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18911. this._useAlternateCameraConfiguration = active;
  18912. };
  18913. Scene.prototype.getViewMatrix = function () {
  18914. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18915. };
  18916. Scene.prototype.getProjectionMatrix = function () {
  18917. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18918. };
  18919. Scene.prototype.getTransformMatrix = function () {
  18920. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18921. };
  18922. Scene.prototype.setTransformMatrix = function (view, projection) {
  18923. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18924. return;
  18925. }
  18926. this._viewUpdateFlag = view.updateFlag;
  18927. this._projectionUpdateFlag = projection.updateFlag;
  18928. this._viewMatrix = view;
  18929. this._projectionMatrix = projection;
  18930. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18931. // Update frustum
  18932. if (!this._frustumPlanes) {
  18933. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18934. }
  18935. else {
  18936. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18937. }
  18938. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18939. var otherCamera = this.activeCamera._alternateCamera;
  18940. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18941. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18942. }
  18943. if (this._sceneUbo.useUbo) {
  18944. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18945. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18946. this._sceneUbo.update();
  18947. }
  18948. };
  18949. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18950. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18951. return;
  18952. }
  18953. this._alternateViewUpdateFlag = view.updateFlag;
  18954. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18955. this._alternateViewMatrix = view;
  18956. this._alternateProjectionMatrix = projection;
  18957. if (!this._alternateTransformMatrix) {
  18958. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18959. }
  18960. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18961. if (!this._alternateSceneUbo) {
  18962. this._createAlternateUbo();
  18963. }
  18964. if (this._alternateSceneUbo.useUbo) {
  18965. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18966. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18967. this._alternateSceneUbo.update();
  18968. }
  18969. };
  18970. Scene.prototype.getSceneUniformBuffer = function () {
  18971. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18972. };
  18973. // Methods
  18974. Scene.prototype.getUniqueId = function () {
  18975. var result = Scene._uniqueIdCounter;
  18976. Scene._uniqueIdCounter++;
  18977. return result;
  18978. };
  18979. Scene.prototype.addMesh = function (newMesh) {
  18980. this.meshes.push(newMesh);
  18981. //notify the collision coordinator
  18982. if (this.collisionCoordinator) {
  18983. this.collisionCoordinator.onMeshAdded(newMesh);
  18984. }
  18985. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18986. };
  18987. Scene.prototype.removeMesh = function (toRemove) {
  18988. var index = this.meshes.indexOf(toRemove);
  18989. if (index !== -1) {
  18990. // Remove from the scene if mesh found
  18991. this.meshes.splice(index, 1);
  18992. }
  18993. //notify the collision coordinator
  18994. if (this.collisionCoordinator) {
  18995. this.collisionCoordinator.onMeshRemoved(toRemove);
  18996. }
  18997. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18998. return index;
  18999. };
  19000. Scene.prototype.removeSkeleton = function (toRemove) {
  19001. var index = this.skeletons.indexOf(toRemove);
  19002. if (index !== -1) {
  19003. // Remove from the scene if found
  19004. this.skeletons.splice(index, 1);
  19005. }
  19006. return index;
  19007. };
  19008. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19009. var index = this.morphTargetManagers.indexOf(toRemove);
  19010. if (index !== -1) {
  19011. // Remove from the scene if found
  19012. this.morphTargetManagers.splice(index, 1);
  19013. }
  19014. return index;
  19015. };
  19016. Scene.prototype.removeLight = function (toRemove) {
  19017. var index = this.lights.indexOf(toRemove);
  19018. if (index !== -1) {
  19019. // Remove from the scene if mesh found
  19020. this.lights.splice(index, 1);
  19021. this.sortLightsByPriority();
  19022. }
  19023. this.onLightRemovedObservable.notifyObservers(toRemove);
  19024. return index;
  19025. };
  19026. Scene.prototype.removeCamera = function (toRemove) {
  19027. var index = this.cameras.indexOf(toRemove);
  19028. if (index !== -1) {
  19029. // Remove from the scene if mesh found
  19030. this.cameras.splice(index, 1);
  19031. }
  19032. // Remove from activeCameras
  19033. var index2 = this.activeCameras.indexOf(toRemove);
  19034. if (index2 !== -1) {
  19035. // Remove from the scene if mesh found
  19036. this.activeCameras.splice(index2, 1);
  19037. }
  19038. // Reset the activeCamera
  19039. if (this.activeCamera === toRemove) {
  19040. if (this.cameras.length > 0) {
  19041. this.activeCamera = this.cameras[0];
  19042. }
  19043. else {
  19044. this.activeCamera = null;
  19045. }
  19046. }
  19047. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19048. return index;
  19049. };
  19050. Scene.prototype.addLight = function (newLight) {
  19051. this.lights.push(newLight);
  19052. this.sortLightsByPriority();
  19053. this.onNewLightAddedObservable.notifyObservers(newLight);
  19054. };
  19055. Scene.prototype.sortLightsByPriority = function () {
  19056. if (this.requireLightSorting) {
  19057. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19058. }
  19059. };
  19060. Scene.prototype.addCamera = function (newCamera) {
  19061. this.cameras.push(newCamera);
  19062. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19063. };
  19064. /**
  19065. * Switch active camera
  19066. * @param {Camera} newCamera - new active camera
  19067. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19068. */
  19069. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19070. if (attachControl === void 0) { attachControl = true; }
  19071. var canvas = this._engine.getRenderingCanvas();
  19072. if (!canvas) {
  19073. return;
  19074. }
  19075. if (this.activeCamera) {
  19076. this.activeCamera.detachControl(canvas);
  19077. }
  19078. this.activeCamera = newCamera;
  19079. if (attachControl) {
  19080. newCamera.attachControl(canvas);
  19081. }
  19082. };
  19083. /**
  19084. * sets the active camera of the scene using its ID
  19085. * @param {string} id - the camera's ID
  19086. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19087. * @see activeCamera
  19088. */
  19089. Scene.prototype.setActiveCameraByID = function (id) {
  19090. var camera = this.getCameraByID(id);
  19091. if (camera) {
  19092. this.activeCamera = camera;
  19093. return camera;
  19094. }
  19095. return null;
  19096. };
  19097. /**
  19098. * sets the active camera of the scene using its name
  19099. * @param {string} name - the camera's name
  19100. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19101. * @see activeCamera
  19102. */
  19103. Scene.prototype.setActiveCameraByName = function (name) {
  19104. var camera = this.getCameraByName(name);
  19105. if (camera) {
  19106. this.activeCamera = camera;
  19107. return camera;
  19108. }
  19109. return null;
  19110. };
  19111. /**
  19112. * get a material using its id
  19113. * @param {string} the material's ID
  19114. * @return {BABYLON.Material|null} the material or null if none found.
  19115. */
  19116. Scene.prototype.getMaterialByID = function (id) {
  19117. for (var index = 0; index < this.materials.length; index++) {
  19118. if (this.materials[index].id === id) {
  19119. return this.materials[index];
  19120. }
  19121. }
  19122. return null;
  19123. };
  19124. /**
  19125. * get a material using its name
  19126. * @param {string} the material's name
  19127. * @return {BABYLON.Material|null} the material or null if none found.
  19128. */
  19129. Scene.prototype.getMaterialByName = function (name) {
  19130. for (var index = 0; index < this.materials.length; index++) {
  19131. if (this.materials[index].name === name) {
  19132. return this.materials[index];
  19133. }
  19134. }
  19135. return null;
  19136. };
  19137. Scene.prototype.getLensFlareSystemByName = function (name) {
  19138. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19139. if (this.lensFlareSystems[index].name === name) {
  19140. return this.lensFlareSystems[index];
  19141. }
  19142. }
  19143. return null;
  19144. };
  19145. Scene.prototype.getLensFlareSystemByID = function (id) {
  19146. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19147. if (this.lensFlareSystems[index].id === id) {
  19148. return this.lensFlareSystems[index];
  19149. }
  19150. }
  19151. return null;
  19152. };
  19153. Scene.prototype.getCameraByID = function (id) {
  19154. for (var index = 0; index < this.cameras.length; index++) {
  19155. if (this.cameras[index].id === id) {
  19156. return this.cameras[index];
  19157. }
  19158. }
  19159. return null;
  19160. };
  19161. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19162. for (var index = 0; index < this.cameras.length; index++) {
  19163. if (this.cameras[index].uniqueId === uniqueId) {
  19164. return this.cameras[index];
  19165. }
  19166. }
  19167. return null;
  19168. };
  19169. /**
  19170. * get a camera using its name
  19171. * @param {string} the camera's name
  19172. * @return {BABYLON.Camera|null} the camera or null if none found.
  19173. */
  19174. Scene.prototype.getCameraByName = function (name) {
  19175. for (var index = 0; index < this.cameras.length; index++) {
  19176. if (this.cameras[index].name === name) {
  19177. return this.cameras[index];
  19178. }
  19179. }
  19180. return null;
  19181. };
  19182. /**
  19183. * get a bone using its id
  19184. * @param {string} the bone's id
  19185. * @return {BABYLON.Bone|null} the bone or null if not found
  19186. */
  19187. Scene.prototype.getBoneByID = function (id) {
  19188. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19189. var skeleton = this.skeletons[skeletonIndex];
  19190. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19191. if (skeleton.bones[boneIndex].id === id) {
  19192. return skeleton.bones[boneIndex];
  19193. }
  19194. }
  19195. }
  19196. return null;
  19197. };
  19198. /**
  19199. * get a bone using its id
  19200. * @param {string} the bone's name
  19201. * @return {BABYLON.Bone|null} the bone or null if not found
  19202. */
  19203. Scene.prototype.getBoneByName = function (name) {
  19204. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19205. var skeleton = this.skeletons[skeletonIndex];
  19206. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19207. if (skeleton.bones[boneIndex].name === name) {
  19208. return skeleton.bones[boneIndex];
  19209. }
  19210. }
  19211. }
  19212. return null;
  19213. };
  19214. /**
  19215. * get a light node using its name
  19216. * @param {string} the light's name
  19217. * @return {BABYLON.Light|null} the light or null if none found.
  19218. */
  19219. Scene.prototype.getLightByName = function (name) {
  19220. for (var index = 0; index < this.lights.length; index++) {
  19221. if (this.lights[index].name === name) {
  19222. return this.lights[index];
  19223. }
  19224. }
  19225. return null;
  19226. };
  19227. /**
  19228. * get a light node using its ID
  19229. * @param {string} the light's id
  19230. * @return {BABYLON.Light|null} the light or null if none found.
  19231. */
  19232. Scene.prototype.getLightByID = function (id) {
  19233. for (var index = 0; index < this.lights.length; index++) {
  19234. if (this.lights[index].id === id) {
  19235. return this.lights[index];
  19236. }
  19237. }
  19238. return null;
  19239. };
  19240. /**
  19241. * get a light node using its scene-generated unique ID
  19242. * @param {number} the light's unique id
  19243. * @return {BABYLON.Light|null} the light or null if none found.
  19244. */
  19245. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19246. for (var index = 0; index < this.lights.length; index++) {
  19247. if (this.lights[index].uniqueId === uniqueId) {
  19248. return this.lights[index];
  19249. }
  19250. }
  19251. return null;
  19252. };
  19253. /**
  19254. * get a particle system by id
  19255. * @param id {number} the particle system id
  19256. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19257. */
  19258. Scene.prototype.getParticleSystemByID = function (id) {
  19259. for (var index = 0; index < this.particleSystems.length; index++) {
  19260. if (this.particleSystems[index].id === id) {
  19261. return this.particleSystems[index];
  19262. }
  19263. }
  19264. return null;
  19265. };
  19266. /**
  19267. * get a geometry using its ID
  19268. * @param {string} the geometry's id
  19269. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19270. */
  19271. Scene.prototype.getGeometryByID = function (id) {
  19272. for (var index = 0; index < this._geometries.length; index++) {
  19273. if (this._geometries[index].id === id) {
  19274. return this._geometries[index];
  19275. }
  19276. }
  19277. return null;
  19278. };
  19279. /**
  19280. * add a new geometry to this scene.
  19281. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19282. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19283. * @return {boolean} was the geometry added or not
  19284. */
  19285. Scene.prototype.pushGeometry = function (geometry, force) {
  19286. if (!force && this.getGeometryByID(geometry.id)) {
  19287. return false;
  19288. }
  19289. this._geometries.push(geometry);
  19290. //notify the collision coordinator
  19291. if (this.collisionCoordinator) {
  19292. this.collisionCoordinator.onGeometryAdded(geometry);
  19293. }
  19294. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19295. return true;
  19296. };
  19297. /**
  19298. * Removes an existing geometry
  19299. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19300. * @return {boolean} was the geometry removed or not
  19301. */
  19302. Scene.prototype.removeGeometry = function (geometry) {
  19303. var index = this._geometries.indexOf(geometry);
  19304. if (index > -1) {
  19305. this._geometries.splice(index, 1);
  19306. //notify the collision coordinator
  19307. if (this.collisionCoordinator) {
  19308. this.collisionCoordinator.onGeometryDeleted(geometry);
  19309. }
  19310. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19311. return true;
  19312. }
  19313. return false;
  19314. };
  19315. Scene.prototype.getGeometries = function () {
  19316. return this._geometries;
  19317. };
  19318. /**
  19319. * Get the first added mesh found of a given ID
  19320. * @param {string} id - the id to search for
  19321. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19322. */
  19323. Scene.prototype.getMeshByID = function (id) {
  19324. for (var index = 0; index < this.meshes.length; index++) {
  19325. if (this.meshes[index].id === id) {
  19326. return this.meshes[index];
  19327. }
  19328. }
  19329. return null;
  19330. };
  19331. Scene.prototype.getMeshesByID = function (id) {
  19332. return this.meshes.filter(function (m) {
  19333. return m.id === id;
  19334. });
  19335. };
  19336. /**
  19337. * Get a mesh with its auto-generated unique id
  19338. * @param {number} uniqueId - the unique id to search for
  19339. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19340. */
  19341. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19342. for (var index = 0; index < this.meshes.length; index++) {
  19343. if (this.meshes[index].uniqueId === uniqueId) {
  19344. return this.meshes[index];
  19345. }
  19346. }
  19347. return null;
  19348. };
  19349. /**
  19350. * Get a the last added mesh found of a given ID
  19351. * @param {string} id - the id to search for
  19352. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19353. */
  19354. Scene.prototype.getLastMeshByID = function (id) {
  19355. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19356. if (this.meshes[index].id === id) {
  19357. return this.meshes[index];
  19358. }
  19359. }
  19360. return null;
  19361. };
  19362. /**
  19363. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19364. * @param {string} id - the id to search for
  19365. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19366. */
  19367. Scene.prototype.getLastEntryByID = function (id) {
  19368. var index;
  19369. for (index = this.meshes.length - 1; index >= 0; index--) {
  19370. if (this.meshes[index].id === id) {
  19371. return this.meshes[index];
  19372. }
  19373. }
  19374. for (index = this.cameras.length - 1; index >= 0; index--) {
  19375. if (this.cameras[index].id === id) {
  19376. return this.cameras[index];
  19377. }
  19378. }
  19379. for (index = this.lights.length - 1; index >= 0; index--) {
  19380. if (this.lights[index].id === id) {
  19381. return this.lights[index];
  19382. }
  19383. }
  19384. return null;
  19385. };
  19386. Scene.prototype.getNodeByID = function (id) {
  19387. var mesh = this.getMeshByID(id);
  19388. if (mesh) {
  19389. return mesh;
  19390. }
  19391. var light = this.getLightByID(id);
  19392. if (light) {
  19393. return light;
  19394. }
  19395. var camera = this.getCameraByID(id);
  19396. if (camera) {
  19397. return camera;
  19398. }
  19399. var bone = this.getBoneByID(id);
  19400. return bone;
  19401. };
  19402. Scene.prototype.getNodeByName = function (name) {
  19403. var mesh = this.getMeshByName(name);
  19404. if (mesh) {
  19405. return mesh;
  19406. }
  19407. var light = this.getLightByName(name);
  19408. if (light) {
  19409. return light;
  19410. }
  19411. var camera = this.getCameraByName(name);
  19412. if (camera) {
  19413. return camera;
  19414. }
  19415. var bone = this.getBoneByName(name);
  19416. return bone;
  19417. };
  19418. Scene.prototype.getMeshByName = function (name) {
  19419. for (var index = 0; index < this.meshes.length; index++) {
  19420. if (this.meshes[index].name === name) {
  19421. return this.meshes[index];
  19422. }
  19423. }
  19424. return null;
  19425. };
  19426. Scene.prototype.getSoundByName = function (name) {
  19427. var index;
  19428. if (BABYLON.AudioEngine) {
  19429. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19430. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19431. return this.mainSoundTrack.soundCollection[index];
  19432. }
  19433. }
  19434. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19435. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19436. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19437. return this.soundTracks[sdIndex].soundCollection[index];
  19438. }
  19439. }
  19440. }
  19441. }
  19442. return null;
  19443. };
  19444. Scene.prototype.getLastSkeletonByID = function (id) {
  19445. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19446. if (this.skeletons[index].id === id) {
  19447. return this.skeletons[index];
  19448. }
  19449. }
  19450. return null;
  19451. };
  19452. Scene.prototype.getSkeletonById = function (id) {
  19453. for (var index = 0; index < this.skeletons.length; index++) {
  19454. if (this.skeletons[index].id === id) {
  19455. return this.skeletons[index];
  19456. }
  19457. }
  19458. return null;
  19459. };
  19460. Scene.prototype.getSkeletonByName = function (name) {
  19461. for (var index = 0; index < this.skeletons.length; index++) {
  19462. if (this.skeletons[index].name === name) {
  19463. return this.skeletons[index];
  19464. }
  19465. }
  19466. return null;
  19467. };
  19468. Scene.prototype.getMorphTargetManagerById = function (id) {
  19469. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19470. if (this.morphTargetManagers[index].uniqueId === id) {
  19471. return this.morphTargetManagers[index];
  19472. }
  19473. }
  19474. return null;
  19475. };
  19476. Scene.prototype.isActiveMesh = function (mesh) {
  19477. return (this._activeMeshes.indexOf(mesh) !== -1);
  19478. };
  19479. /**
  19480. * Return a the first highlight layer of the scene with a given name.
  19481. * @param name The name of the highlight layer to look for.
  19482. * @return The highlight layer if found otherwise null.
  19483. */
  19484. Scene.prototype.getHighlightLayerByName = function (name) {
  19485. for (var index = 0; index < this.highlightLayers.length; index++) {
  19486. if (this.highlightLayers[index].name === name) {
  19487. return this.highlightLayers[index];
  19488. }
  19489. }
  19490. return null;
  19491. };
  19492. Object.defineProperty(Scene.prototype, "uid", {
  19493. /**
  19494. * Return a unique id as a string which can serve as an identifier for the scene
  19495. */
  19496. get: function () {
  19497. if (!this._uid) {
  19498. this._uid = BABYLON.Tools.RandomId();
  19499. }
  19500. return this._uid;
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. /**
  19506. * Add an externaly attached data from its key.
  19507. * This method call will fail and return false, if such key already exists.
  19508. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19509. * @param key the unique key that identifies the data
  19510. * @param data the data object to associate to the key for this Engine instance
  19511. * @return true if no such key were already present and the data was added successfully, false otherwise
  19512. */
  19513. Scene.prototype.addExternalData = function (key, data) {
  19514. if (!this._externalData) {
  19515. this._externalData = new BABYLON.StringDictionary();
  19516. }
  19517. return this._externalData.add(key, data);
  19518. };
  19519. /**
  19520. * Get an externaly attached data from its key
  19521. * @param key the unique key that identifies the data
  19522. * @return the associated data, if present (can be null), or undefined if not present
  19523. */
  19524. Scene.prototype.getExternalData = function (key) {
  19525. if (!this._externalData) {
  19526. return null;
  19527. }
  19528. return this._externalData.get(key);
  19529. };
  19530. /**
  19531. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19532. * @param key the unique key that identifies the data
  19533. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19534. * @return the associated data, can be null if the factory returned null.
  19535. */
  19536. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19537. if (!this._externalData) {
  19538. this._externalData = new BABYLON.StringDictionary();
  19539. }
  19540. return this._externalData.getOrAddWithFactory(key, factory);
  19541. };
  19542. /**
  19543. * Remove an externaly attached data from the Engine instance
  19544. * @param key the unique key that identifies the data
  19545. * @return true if the data was successfully removed, false if it doesn't exist
  19546. */
  19547. Scene.prototype.removeExternalData = function (key) {
  19548. return this._externalData.remove(key);
  19549. };
  19550. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19551. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19552. var material = subMesh.getMaterial();
  19553. if (mesh.showSubMeshesBoundingBox) {
  19554. var boundingInfo = subMesh.getBoundingInfo();
  19555. if (boundingInfo) {
  19556. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19557. }
  19558. }
  19559. if (material) {
  19560. // Render targets
  19561. if (material.getRenderTargetTextures) {
  19562. if (this._processedMaterials.indexOf(material) === -1) {
  19563. this._processedMaterials.push(material);
  19564. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19565. }
  19566. }
  19567. // Dispatch
  19568. this._activeIndices.addCount(subMesh.indexCount, false);
  19569. this._renderingManager.dispatch(subMesh);
  19570. }
  19571. }
  19572. };
  19573. Scene.prototype._isInIntermediateRendering = function () {
  19574. return this._intermediateRendering;
  19575. };
  19576. /**
  19577. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19578. */
  19579. Scene.prototype.freezeActiveMeshes = function () {
  19580. this._evaluateActiveMeshes();
  19581. this._activeMeshesFrozen = true;
  19582. return this;
  19583. };
  19584. /**
  19585. * Use this function to restart evaluating active meshes on every frame
  19586. */
  19587. Scene.prototype.unfreezeActiveMeshes = function () {
  19588. this._activeMeshesFrozen = false;
  19589. return this;
  19590. };
  19591. Scene.prototype._evaluateActiveMeshes = function () {
  19592. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19593. return;
  19594. }
  19595. if (!this.activeCamera) {
  19596. return;
  19597. }
  19598. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19599. this.activeCamera._activeMeshes.reset();
  19600. this._activeMeshes.reset();
  19601. this._renderingManager.reset();
  19602. this._processedMaterials.reset();
  19603. this._activeParticleSystems.reset();
  19604. this._activeSkeletons.reset();
  19605. this._softwareSkinnedMeshes.reset();
  19606. if (this._boundingBoxRenderer) {
  19607. this._boundingBoxRenderer.reset();
  19608. }
  19609. // Meshes
  19610. var meshes;
  19611. var len;
  19612. if (this._selectionOctree) {
  19613. var selection = this._selectionOctree.select(this._frustumPlanes);
  19614. meshes = selection.data;
  19615. len = selection.length;
  19616. }
  19617. else {
  19618. len = this.meshes.length;
  19619. meshes = this.meshes;
  19620. }
  19621. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19622. var mesh = meshes[meshIndex];
  19623. if (mesh.isBlocked) {
  19624. continue;
  19625. }
  19626. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19627. if (!mesh.isReady() || !mesh.isEnabled()) {
  19628. continue;
  19629. }
  19630. mesh.computeWorldMatrix();
  19631. // Intersections
  19632. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19633. this._meshesForIntersections.pushNoDuplicate(mesh);
  19634. }
  19635. // Switch to current LOD
  19636. var meshLOD = mesh.getLOD(this.activeCamera);
  19637. if (!meshLOD) {
  19638. continue;
  19639. }
  19640. mesh._preActivate();
  19641. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19642. this._activeMeshes.push(mesh);
  19643. this.activeCamera._activeMeshes.push(mesh);
  19644. mesh._activate(this._renderId);
  19645. if (meshLOD !== mesh) {
  19646. meshLOD._activate(this._renderId);
  19647. }
  19648. this._activeMesh(mesh, meshLOD);
  19649. }
  19650. }
  19651. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19652. // Particle systems
  19653. if (this.particlesEnabled) {
  19654. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19655. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19656. var particleSystem = this.particleSystems[particleIndex];
  19657. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19658. continue;
  19659. }
  19660. var emitter = particleSystem.emitter;
  19661. if (!emitter.position || emitter.isEnabled()) {
  19662. this._activeParticleSystems.push(particleSystem);
  19663. particleSystem.animate();
  19664. this._renderingManager.dispatchParticles(particleSystem);
  19665. }
  19666. }
  19667. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19668. }
  19669. };
  19670. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19671. if (mesh.skeleton && this.skeletonsEnabled) {
  19672. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19673. mesh.skeleton.prepare();
  19674. }
  19675. if (!mesh.computeBonesUsingShaders) {
  19676. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19677. }
  19678. }
  19679. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19680. var boundingInfo = sourceMesh.getBoundingInfo();
  19681. if (boundingInfo) {
  19682. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19683. }
  19684. }
  19685. if (mesh && mesh.subMeshes) {
  19686. // Submeshes Octrees
  19687. var len;
  19688. var subMeshes;
  19689. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19690. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19691. len = intersections.length;
  19692. subMeshes = intersections.data;
  19693. }
  19694. else {
  19695. subMeshes = mesh.subMeshes;
  19696. len = subMeshes.length;
  19697. }
  19698. for (var subIndex = 0; subIndex < len; subIndex++) {
  19699. var subMesh = subMeshes[subIndex];
  19700. this._evaluateSubMesh(subMesh, mesh);
  19701. }
  19702. }
  19703. };
  19704. Scene.prototype.updateTransformMatrix = function (force) {
  19705. if (!this.activeCamera) {
  19706. return;
  19707. }
  19708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19709. };
  19710. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19711. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19712. };
  19713. Scene.prototype._renderForCamera = function (camera) {
  19714. if (camera && camera._skipRendering) {
  19715. return;
  19716. }
  19717. var engine = this._engine;
  19718. this.activeCamera = camera;
  19719. if (!this.activeCamera)
  19720. throw new Error("Active camera not set");
  19721. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19722. // Viewport
  19723. engine.setViewport(this.activeCamera.viewport);
  19724. // Camera
  19725. this.resetCachedMaterial();
  19726. this._renderId++;
  19727. this.activeCamera.update();
  19728. this.updateTransformMatrix();
  19729. if (camera._alternateCamera) {
  19730. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19731. this._alternateRendering = true;
  19732. }
  19733. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19734. // Meshes
  19735. this._evaluateActiveMeshes();
  19736. // Software skinning
  19737. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19738. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19739. mesh.applySkeleton(mesh.skeleton);
  19740. }
  19741. // Render targets
  19742. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19743. var needsRestoreFrameBuffer = false;
  19744. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19745. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19746. }
  19747. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19748. this._intermediateRendering = true;
  19749. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19750. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19751. var renderTarget = this._renderTargets.data[renderIndex];
  19752. if (renderTarget._shouldRender()) {
  19753. this._renderId++;
  19754. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19755. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19756. }
  19757. }
  19758. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19759. this._intermediateRendering = false;
  19760. this._renderId++;
  19761. needsRestoreFrameBuffer = true; // Restore back buffer
  19762. }
  19763. // Render HighlightLayer Texture
  19764. var stencilState = this._engine.getStencilBuffer();
  19765. var renderhighlights = false;
  19766. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19767. this._intermediateRendering = true;
  19768. for (var i = 0; i < this.highlightLayers.length; i++) {
  19769. var highlightLayer = this.highlightLayers[i];
  19770. if (highlightLayer.shouldRender() &&
  19771. (!highlightLayer.camera ||
  19772. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19773. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19774. renderhighlights = true;
  19775. var renderTarget = highlightLayer._mainTexture;
  19776. if (renderTarget._shouldRender()) {
  19777. this._renderId++;
  19778. renderTarget.render(false, false);
  19779. needsRestoreFrameBuffer = true;
  19780. }
  19781. }
  19782. }
  19783. this._intermediateRendering = false;
  19784. this._renderId++;
  19785. }
  19786. if (needsRestoreFrameBuffer) {
  19787. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19788. }
  19789. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19790. // Prepare Frame
  19791. this.postProcessManager._prepareFrame();
  19792. // Backgrounds
  19793. var layerIndex;
  19794. var layer;
  19795. if (this.layers.length) {
  19796. engine.setDepthBuffer(false);
  19797. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19798. layer = this.layers[layerIndex];
  19799. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19800. layer.render();
  19801. }
  19802. }
  19803. engine.setDepthBuffer(true);
  19804. }
  19805. // Activate HighlightLayer stencil
  19806. if (renderhighlights) {
  19807. this._engine.setStencilBuffer(true);
  19808. }
  19809. // Render
  19810. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19811. this._renderingManager.render(null, null, true, true);
  19812. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19813. // Restore HighlightLayer stencil
  19814. if (renderhighlights) {
  19815. this._engine.setStencilBuffer(stencilState);
  19816. }
  19817. // Bounding boxes
  19818. if (this._boundingBoxRenderer) {
  19819. this._boundingBoxRenderer.render();
  19820. }
  19821. // Lens flares
  19822. if (this.lensFlaresEnabled) {
  19823. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19824. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19825. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19826. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19827. lensFlareSystem.render();
  19828. }
  19829. }
  19830. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19831. }
  19832. // Foregrounds
  19833. if (this.layers.length) {
  19834. engine.setDepthBuffer(false);
  19835. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19836. layer = this.layers[layerIndex];
  19837. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19838. layer.render();
  19839. }
  19840. }
  19841. engine.setDepthBuffer(true);
  19842. }
  19843. // Highlight Layer
  19844. if (renderhighlights) {
  19845. engine.setDepthBuffer(false);
  19846. for (var i = 0; i < this.highlightLayers.length; i++) {
  19847. if (this.highlightLayers[i].shouldRender()) {
  19848. this.highlightLayers[i].render();
  19849. }
  19850. }
  19851. engine.setDepthBuffer(true);
  19852. }
  19853. // Finalize frame
  19854. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19855. // Reset some special arrays
  19856. this._renderTargets.reset();
  19857. this._alternateRendering = false;
  19858. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19859. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19860. };
  19861. Scene.prototype._processSubCameras = function (camera) {
  19862. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19863. this._renderForCamera(camera);
  19864. return;
  19865. }
  19866. // Update camera
  19867. if (this.activeCamera) {
  19868. this.activeCamera.update();
  19869. }
  19870. // rig cameras
  19871. for (var index = 0; index < camera._rigCameras.length; index++) {
  19872. this._renderForCamera(camera._rigCameras[index]);
  19873. }
  19874. this.activeCamera = camera;
  19875. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19876. };
  19877. Scene.prototype._checkIntersections = function () {
  19878. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19879. var sourceMesh = this._meshesForIntersections.data[index];
  19880. if (!sourceMesh.actionManager) {
  19881. continue;
  19882. }
  19883. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19884. var action = sourceMesh.actionManager.actions[actionIndex];
  19885. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19886. var parameters = action.getTriggerParameter();
  19887. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19888. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19889. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19890. if (areIntersecting && currentIntersectionInProgress === -1) {
  19891. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19892. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19893. sourceMesh._intersectionsInProgress.push(otherMesh);
  19894. }
  19895. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19896. sourceMesh._intersectionsInProgress.push(otherMesh);
  19897. }
  19898. }
  19899. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19900. //They intersected, and now they don't.
  19901. //is this trigger an exit trigger? execute an event.
  19902. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19903. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19904. }
  19905. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19906. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19907. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19908. }
  19909. }
  19910. }
  19911. }
  19912. }
  19913. };
  19914. Scene.prototype.render = function () {
  19915. if (this.isDisposed) {
  19916. return;
  19917. }
  19918. this._activeParticles.fetchNewFrame();
  19919. this._totalVertices.fetchNewFrame();
  19920. this._activeIndices.fetchNewFrame();
  19921. this._activeBones.fetchNewFrame();
  19922. this._meshesForIntersections.reset();
  19923. this.resetCachedMaterial();
  19924. this.onBeforeAnimationsObservable.notifyObservers(this);
  19925. // Actions
  19926. if (this.actionManager) {
  19927. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19928. }
  19929. //Simplification Queue
  19930. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19931. this.simplificationQueue.executeNext();
  19932. }
  19933. if (this._engine.isDeterministicLockStep()) {
  19934. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19935. var defaultTimeStep = (60.0 / 1000.0);
  19936. if (this._physicsEngine) {
  19937. defaultTimeStep = this._physicsEngine.getTimeStep();
  19938. }
  19939. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19940. this._timeAccumulator += deltaTime;
  19941. // compute the amount of fixed steps we should have taken since the last step
  19942. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19943. internalSteps = Math.min(internalSteps, maxSubSteps);
  19944. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19945. this.onBeforeStepObservable.notifyObservers(this);
  19946. // Animations
  19947. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19948. this._animate();
  19949. // Physics
  19950. if (this._physicsEngine) {
  19951. this.onBeforePhysicsObservable.notifyObservers(this);
  19952. this._physicsEngine._step(defaultTimeStep);
  19953. this.onAfterPhysicsObservable.notifyObservers(this);
  19954. }
  19955. this._timeAccumulator -= defaultTimeStep;
  19956. this.onAfterStepObservable.notifyObservers(this);
  19957. this._currentStepId++;
  19958. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19959. this._evaluateActiveMeshes();
  19960. }
  19961. }
  19962. }
  19963. else {
  19964. // Animations
  19965. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19966. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19967. this._animate();
  19968. // Physics
  19969. if (this._physicsEngine) {
  19970. this.onBeforePhysicsObservable.notifyObservers(this);
  19971. this._physicsEngine._step(deltaTime / 1000.0);
  19972. this.onAfterPhysicsObservable.notifyObservers(this);
  19973. }
  19974. }
  19975. // Before render
  19976. this.onBeforeRenderObservable.notifyObservers(this);
  19977. // Customs render targets
  19978. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19979. var engine = this.getEngine();
  19980. var currentActiveCamera = this.activeCamera;
  19981. if (this.renderTargetsEnabled) {
  19982. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19983. this._intermediateRendering = true;
  19984. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19985. var renderTarget = this.customRenderTargets[customIndex];
  19986. if (renderTarget._shouldRender()) {
  19987. this._renderId++;
  19988. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19989. if (!this.activeCamera)
  19990. throw new Error("Active camera not set");
  19991. // Viewport
  19992. engine.setViewport(this.activeCamera.viewport);
  19993. // Camera
  19994. this.updateTransformMatrix();
  19995. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19996. }
  19997. }
  19998. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19999. this._intermediateRendering = false;
  20000. this._renderId++;
  20001. }
  20002. // Restore back buffer
  20003. if (this.customRenderTargets.length > 0) {
  20004. engine.restoreDefaultFramebuffer();
  20005. }
  20006. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20007. this.activeCamera = currentActiveCamera;
  20008. // Procedural textures
  20009. if (this.proceduralTexturesEnabled) {
  20010. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20011. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20012. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20013. if (proceduralTexture._shouldRender()) {
  20014. proceduralTexture.render();
  20015. }
  20016. }
  20017. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20018. }
  20019. // Clear
  20020. if (this.autoClearDepthAndStencil || this.autoClear) {
  20021. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20022. }
  20023. // Shadows
  20024. if (this.shadowsEnabled) {
  20025. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20026. var light = this.lights[lightIndex];
  20027. var shadowGenerator = light.getShadowGenerator();
  20028. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20029. var shadowMap = (shadowGenerator.getShadowMap());
  20030. if (this.textures.indexOf(shadowMap) !== -1) {
  20031. this._renderTargets.push(shadowMap);
  20032. }
  20033. }
  20034. }
  20035. }
  20036. // Depth renderer
  20037. if (this._depthRenderer) {
  20038. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20039. }
  20040. // Geometry renderer
  20041. if (this._geometryBufferRenderer) {
  20042. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20043. }
  20044. // RenderPipeline
  20045. if (this._postProcessRenderPipelineManager) {
  20046. this._postProcessRenderPipelineManager.update();
  20047. }
  20048. // Multi-cameras?
  20049. if (this.activeCameras.length > 0) {
  20050. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20051. if (cameraIndex > 0) {
  20052. this._engine.clear(null, false, true, true);
  20053. }
  20054. this._processSubCameras(this.activeCameras[cameraIndex]);
  20055. }
  20056. }
  20057. else {
  20058. if (!this.activeCamera) {
  20059. throw new Error("No camera defined");
  20060. }
  20061. this._processSubCameras(this.activeCamera);
  20062. }
  20063. // Intersection checks
  20064. this._checkIntersections();
  20065. // Update the audio listener attached to the camera
  20066. if (BABYLON.AudioEngine) {
  20067. this._updateAudioParameters();
  20068. }
  20069. // After render
  20070. if (this.afterRender) {
  20071. this.afterRender();
  20072. }
  20073. this.onAfterRenderObservable.notifyObservers(this);
  20074. // Cleaning
  20075. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20076. var data = this._toBeDisposed.data[index];
  20077. if (data) {
  20078. data.dispose();
  20079. }
  20080. this._toBeDisposed[index] = null;
  20081. }
  20082. this._toBeDisposed.reset();
  20083. if (this.dumpNextRenderTargets) {
  20084. this.dumpNextRenderTargets = false;
  20085. }
  20086. this._activeBones.addCount(0, true);
  20087. this._activeIndices.addCount(0, true);
  20088. this._activeParticles.addCount(0, true);
  20089. };
  20090. Scene.prototype._updateAudioParameters = function () {
  20091. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20092. return;
  20093. }
  20094. var listeningCamera;
  20095. var audioEngine = BABYLON.Engine.audioEngine;
  20096. if (this.activeCameras.length > 0) {
  20097. listeningCamera = this.activeCameras[0];
  20098. }
  20099. else {
  20100. listeningCamera = this.activeCamera;
  20101. }
  20102. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20103. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20104. // for VR cameras
  20105. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20106. listeningCamera = listeningCamera.rigCameras[0];
  20107. }
  20108. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20109. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20110. cameraDirection.normalize();
  20111. // To avoid some errors on GearVR
  20112. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20113. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20114. }
  20115. var i;
  20116. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20117. var sound = this.mainSoundTrack.soundCollection[i];
  20118. if (sound.useCustomAttenuation) {
  20119. sound.updateDistanceFromListener();
  20120. }
  20121. }
  20122. for (i = 0; i < this.soundTracks.length; i++) {
  20123. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20124. sound = this.soundTracks[i].soundCollection[j];
  20125. if (sound.useCustomAttenuation) {
  20126. sound.updateDistanceFromListener();
  20127. }
  20128. }
  20129. }
  20130. }
  20131. };
  20132. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20133. // Audio
  20134. get: function () {
  20135. return this._audioEnabled;
  20136. },
  20137. set: function (value) {
  20138. this._audioEnabled = value;
  20139. if (BABYLON.AudioEngine) {
  20140. if (this._audioEnabled) {
  20141. this._enableAudio();
  20142. }
  20143. else {
  20144. this._disableAudio();
  20145. }
  20146. }
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. Scene.prototype._disableAudio = function () {
  20152. var i;
  20153. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20154. this.mainSoundTrack.soundCollection[i].pause();
  20155. }
  20156. for (i = 0; i < this.soundTracks.length; i++) {
  20157. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20158. this.soundTracks[i].soundCollection[j].pause();
  20159. }
  20160. }
  20161. };
  20162. Scene.prototype._enableAudio = function () {
  20163. var i;
  20164. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20165. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20166. this.mainSoundTrack.soundCollection[i].play();
  20167. }
  20168. }
  20169. for (i = 0; i < this.soundTracks.length; i++) {
  20170. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20171. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20172. this.soundTracks[i].soundCollection[j].play();
  20173. }
  20174. }
  20175. }
  20176. };
  20177. Object.defineProperty(Scene.prototype, "headphone", {
  20178. get: function () {
  20179. return this._headphone;
  20180. },
  20181. set: function (value) {
  20182. this._headphone = value;
  20183. if (BABYLON.AudioEngine) {
  20184. if (this._headphone) {
  20185. this._switchAudioModeForHeadphones();
  20186. }
  20187. else {
  20188. this._switchAudioModeForNormalSpeakers();
  20189. }
  20190. }
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. Scene.prototype._switchAudioModeForHeadphones = function () {
  20196. this.mainSoundTrack.switchPanningModelToHRTF();
  20197. for (var i = 0; i < this.soundTracks.length; i++) {
  20198. this.soundTracks[i].switchPanningModelToHRTF();
  20199. }
  20200. };
  20201. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20202. this.mainSoundTrack.switchPanningModelToEqualPower();
  20203. for (var i = 0; i < this.soundTracks.length; i++) {
  20204. this.soundTracks[i].switchPanningModelToEqualPower();
  20205. }
  20206. };
  20207. Scene.prototype.enableDepthRenderer = function () {
  20208. if (this._depthRenderer) {
  20209. return this._depthRenderer;
  20210. }
  20211. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20212. return this._depthRenderer;
  20213. };
  20214. Scene.prototype.disableDepthRenderer = function () {
  20215. if (!this._depthRenderer) {
  20216. return;
  20217. }
  20218. this._depthRenderer.dispose();
  20219. this._depthRenderer = null;
  20220. };
  20221. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20222. if (ratio === void 0) { ratio = 1; }
  20223. if (this._geometryBufferRenderer) {
  20224. return this._geometryBufferRenderer;
  20225. }
  20226. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20227. if (!this._geometryBufferRenderer.isSupported) {
  20228. this._geometryBufferRenderer = null;
  20229. }
  20230. return this._geometryBufferRenderer;
  20231. };
  20232. Scene.prototype.disableGeometryBufferRenderer = function () {
  20233. if (!this._geometryBufferRenderer) {
  20234. return;
  20235. }
  20236. this._geometryBufferRenderer.dispose();
  20237. this._geometryBufferRenderer = null;
  20238. };
  20239. Scene.prototype.freezeMaterials = function () {
  20240. for (var i = 0; i < this.materials.length; i++) {
  20241. this.materials[i].freeze();
  20242. }
  20243. };
  20244. Scene.prototype.unfreezeMaterials = function () {
  20245. for (var i = 0; i < this.materials.length; i++) {
  20246. this.materials[i].unfreeze();
  20247. }
  20248. };
  20249. Scene.prototype.dispose = function () {
  20250. this.beforeRender = null;
  20251. this.afterRender = null;
  20252. this.skeletons = [];
  20253. this.morphTargetManagers = [];
  20254. this.importedMeshesFiles = new Array();
  20255. this.resetCachedMaterial();
  20256. if (this._depthRenderer) {
  20257. this._depthRenderer.dispose();
  20258. }
  20259. if (this._gamepadManager) {
  20260. this._gamepadManager.dispose();
  20261. this._gamepadManager = null;
  20262. }
  20263. // Smart arrays
  20264. if (this.activeCamera) {
  20265. this.activeCamera._activeMeshes.dispose();
  20266. this.activeCamera = null;
  20267. }
  20268. this._activeMeshes.dispose();
  20269. this._renderingManager.dispose();
  20270. this._processedMaterials.dispose();
  20271. this._activeParticleSystems.dispose();
  20272. this._activeSkeletons.dispose();
  20273. this._softwareSkinnedMeshes.dispose();
  20274. this._renderTargets.dispose();
  20275. if (this._boundingBoxRenderer) {
  20276. this._boundingBoxRenderer.dispose();
  20277. }
  20278. this._meshesForIntersections.dispose();
  20279. this._toBeDisposed.dispose();
  20280. // Debug layer
  20281. if (this._debugLayer) {
  20282. this._debugLayer.hide();
  20283. }
  20284. // Events
  20285. this.onDisposeObservable.notifyObservers(this);
  20286. this.onDisposeObservable.clear();
  20287. this.onBeforeRenderObservable.clear();
  20288. this.onAfterRenderObservable.clear();
  20289. this.OnBeforeRenderTargetsRenderObservable.clear();
  20290. this.OnAfterRenderTargetsRenderObservable.clear();
  20291. this.onAfterStepObservable.clear();
  20292. this.onBeforeStepObservable.clear();
  20293. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20294. this.onAfterActiveMeshesEvaluationObservable.clear();
  20295. this.onBeforeParticlesRenderingObservable.clear();
  20296. this.onAfterParticlesRenderingObservable.clear();
  20297. this.onBeforeSpritesRenderingObservable.clear();
  20298. this.onAfterSpritesRenderingObservable.clear();
  20299. this.onBeforeDrawPhaseObservable.clear();
  20300. this.onAfterDrawPhaseObservable.clear();
  20301. this.onBeforePhysicsObservable.clear();
  20302. this.onAfterPhysicsObservable.clear();
  20303. this.detachControl();
  20304. // Release sounds & sounds tracks
  20305. if (BABYLON.AudioEngine) {
  20306. this.disposeSounds();
  20307. }
  20308. // VR Helper
  20309. if (this.VRHelper) {
  20310. this.VRHelper.dispose();
  20311. }
  20312. // Detach cameras
  20313. var canvas = this._engine.getRenderingCanvas();
  20314. if (canvas) {
  20315. var index;
  20316. for (index = 0; index < this.cameras.length; index++) {
  20317. this.cameras[index].detachControl(canvas);
  20318. }
  20319. }
  20320. // Release lights
  20321. while (this.lights.length) {
  20322. this.lights[0].dispose();
  20323. }
  20324. // Release meshes
  20325. while (this.meshes.length) {
  20326. this.meshes[0].dispose(true);
  20327. }
  20328. // Release cameras
  20329. while (this.cameras.length) {
  20330. this.cameras[0].dispose();
  20331. }
  20332. // Release materials
  20333. if (this.defaultMaterial) {
  20334. this.defaultMaterial.dispose();
  20335. }
  20336. while (this.multiMaterials.length) {
  20337. this.multiMaterials[0].dispose();
  20338. }
  20339. while (this.materials.length) {
  20340. this.materials[0].dispose();
  20341. }
  20342. // Release particles
  20343. while (this.particleSystems.length) {
  20344. this.particleSystems[0].dispose();
  20345. }
  20346. // Release sprites
  20347. while (this.spriteManagers.length) {
  20348. this.spriteManagers[0].dispose();
  20349. }
  20350. // Release postProcesses
  20351. while (this.postProcesses.length) {
  20352. this.postProcesses[0].dispose();
  20353. }
  20354. // Release layers
  20355. while (this.layers.length) {
  20356. this.layers[0].dispose();
  20357. }
  20358. while (this.highlightLayers.length) {
  20359. this.highlightLayers[0].dispose();
  20360. }
  20361. // Release textures
  20362. while (this.textures.length) {
  20363. this.textures[0].dispose();
  20364. }
  20365. // Release UBO
  20366. this._sceneUbo.dispose();
  20367. if (this._alternateSceneUbo) {
  20368. this._alternateSceneUbo.dispose();
  20369. }
  20370. // Post-processes
  20371. this.postProcessManager.dispose();
  20372. if (this._postProcessRenderPipelineManager) {
  20373. this._postProcessRenderPipelineManager.dispose();
  20374. }
  20375. // Physics
  20376. if (this._physicsEngine) {
  20377. this.disablePhysicsEngine();
  20378. }
  20379. // Remove from engine
  20380. index = this._engine.scenes.indexOf(this);
  20381. if (index > -1) {
  20382. this._engine.scenes.splice(index, 1);
  20383. }
  20384. this._engine.wipeCaches();
  20385. this._isDisposed = true;
  20386. };
  20387. Object.defineProperty(Scene.prototype, "isDisposed", {
  20388. get: function () {
  20389. return this._isDisposed;
  20390. },
  20391. enumerable: true,
  20392. configurable: true
  20393. });
  20394. // Release sounds & sounds tracks
  20395. Scene.prototype.disposeSounds = function () {
  20396. if (!this._mainSoundTrack) {
  20397. return;
  20398. }
  20399. this.mainSoundTrack.dispose();
  20400. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20401. this.soundTracks[scIndex].dispose();
  20402. }
  20403. };
  20404. // Octrees
  20405. Scene.prototype.getWorldExtends = function () {
  20406. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20407. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20408. for (var index = 0; index < this.meshes.length; index++) {
  20409. var mesh = this.meshes[index];
  20410. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20411. continue;
  20412. }
  20413. mesh.computeWorldMatrix(true);
  20414. var boundingInfo = mesh.getBoundingInfo();
  20415. if (boundingInfo) {
  20416. var minBox = boundingInfo.boundingBox.minimumWorld;
  20417. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20418. BABYLON.Tools.CheckExtends(minBox, min, max);
  20419. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20420. }
  20421. }
  20422. return {
  20423. min: min,
  20424. max: max
  20425. };
  20426. };
  20427. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20428. if (maxCapacity === void 0) { maxCapacity = 64; }
  20429. if (maxDepth === void 0) { maxDepth = 2; }
  20430. if (!this._selectionOctree) {
  20431. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20432. }
  20433. var worldExtends = this.getWorldExtends();
  20434. // Update octree
  20435. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20436. return this._selectionOctree;
  20437. };
  20438. // Picking
  20439. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20440. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20441. var engine = this._engine;
  20442. if (!camera) {
  20443. if (!this.activeCamera)
  20444. throw new Error("Active camera not set");
  20445. camera = this.activeCamera;
  20446. }
  20447. var cameraViewport = camera.viewport;
  20448. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20449. // Moving coordinates to local viewport world
  20450. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20451. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20452. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20453. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20454. };
  20455. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20456. if (!BABYLON.PickingInfo) {
  20457. return null;
  20458. }
  20459. var engine = this._engine;
  20460. if (!camera) {
  20461. if (!this.activeCamera)
  20462. throw new Error("Active camera not set");
  20463. camera = this.activeCamera;
  20464. }
  20465. var cameraViewport = camera.viewport;
  20466. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20467. var identity = BABYLON.Matrix.Identity();
  20468. // Moving coordinates to local viewport world
  20469. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20470. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20471. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20472. };
  20473. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20474. if (!BABYLON.PickingInfo) {
  20475. return null;
  20476. }
  20477. var pickingInfo = null;
  20478. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20479. var mesh = this.meshes[meshIndex];
  20480. if (predicate) {
  20481. if (!predicate(mesh)) {
  20482. continue;
  20483. }
  20484. }
  20485. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20486. continue;
  20487. }
  20488. var world = mesh.getWorldMatrix();
  20489. var ray = rayFunction(world);
  20490. var result = mesh.intersects(ray, fastCheck);
  20491. if (!result || !result.hit)
  20492. continue;
  20493. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20494. continue;
  20495. pickingInfo = result;
  20496. if (fastCheck) {
  20497. break;
  20498. }
  20499. }
  20500. return pickingInfo || new BABYLON.PickingInfo();
  20501. };
  20502. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20503. if (!BABYLON.PickingInfo) {
  20504. return null;
  20505. }
  20506. var pickingInfos = new Array();
  20507. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20508. var mesh = this.meshes[meshIndex];
  20509. if (predicate) {
  20510. if (!predicate(mesh)) {
  20511. continue;
  20512. }
  20513. }
  20514. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20515. continue;
  20516. }
  20517. var world = mesh.getWorldMatrix();
  20518. var ray = rayFunction(world);
  20519. var result = mesh.intersects(ray, false);
  20520. if (!result || !result.hit)
  20521. continue;
  20522. pickingInfos.push(result);
  20523. }
  20524. return pickingInfos;
  20525. };
  20526. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20527. if (!BABYLON.PickingInfo) {
  20528. return null;
  20529. }
  20530. var pickingInfo = null;
  20531. if (!camera) {
  20532. if (!this.activeCamera) {
  20533. return null;
  20534. }
  20535. camera = this.activeCamera;
  20536. }
  20537. if (this.spriteManagers.length > 0) {
  20538. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20539. var spriteManager = this.spriteManagers[spriteIndex];
  20540. if (!spriteManager.isPickable) {
  20541. continue;
  20542. }
  20543. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20544. if (!result || !result.hit)
  20545. continue;
  20546. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20547. continue;
  20548. pickingInfo = result;
  20549. if (fastCheck) {
  20550. break;
  20551. }
  20552. }
  20553. }
  20554. return pickingInfo || new BABYLON.PickingInfo();
  20555. };
  20556. /** Launch a ray to try to pick a mesh in the scene
  20557. * @param x position on screen
  20558. * @param y position on screen
  20559. * @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
  20560. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20561. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20562. */
  20563. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20564. var _this = this;
  20565. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20566. };
  20567. /** Launch a ray to try to pick a sprite in the scene
  20568. * @param x position on screen
  20569. * @param y position on screen
  20570. * @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
  20571. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20572. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20573. */
  20574. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20575. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20576. if (!ray) {
  20577. return null;
  20578. }
  20579. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20580. };
  20581. /** Use the given ray to pick a mesh in the scene
  20582. * @param ray The ray to use to pick meshes
  20583. * @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
  20584. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20585. */
  20586. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20587. var _this = this;
  20588. return this._internalPick(function (world) {
  20589. if (!_this._pickWithRayInverseMatrix) {
  20590. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20591. }
  20592. world.invertToRef(_this._pickWithRayInverseMatrix);
  20593. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20594. }, predicate, fastCheck);
  20595. };
  20596. /**
  20597. * Launch a ray to try to pick a mesh in the scene
  20598. * @param x X position on screen
  20599. * @param y Y position on screen
  20600. * @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
  20601. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20602. */
  20603. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20604. var _this = this;
  20605. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20606. };
  20607. /**
  20608. * Launch a ray to try to pick a mesh in the scene
  20609. * @param ray Ray to use
  20610. * @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
  20611. */
  20612. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20613. var _this = this;
  20614. return this._internalMultiPick(function (world) {
  20615. if (!_this._pickWithRayInverseMatrix) {
  20616. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20617. }
  20618. world.invertToRef(_this._pickWithRayInverseMatrix);
  20619. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20620. }, predicate);
  20621. };
  20622. Scene.prototype.setPointerOverMesh = function (mesh) {
  20623. if (this._pointerOverMesh === mesh) {
  20624. return;
  20625. }
  20626. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20627. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20628. }
  20629. this._pointerOverMesh = mesh;
  20630. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20631. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20632. }
  20633. };
  20634. Scene.prototype.getPointerOverMesh = function () {
  20635. return this._pointerOverMesh;
  20636. };
  20637. Scene.prototype.setPointerOverSprite = function (sprite) {
  20638. if (this._pointerOverSprite === sprite) {
  20639. return;
  20640. }
  20641. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20642. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20643. }
  20644. this._pointerOverSprite = sprite;
  20645. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20646. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20647. }
  20648. };
  20649. Scene.prototype.getPointerOverSprite = function () {
  20650. return this._pointerOverSprite;
  20651. };
  20652. // Physics
  20653. Scene.prototype.getPhysicsEngine = function () {
  20654. return this._physicsEngine;
  20655. };
  20656. /**
  20657. * Enables physics to the current scene
  20658. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20659. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20660. * @return {boolean} was the physics engine initialized
  20661. */
  20662. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20663. if (gravity === void 0) { gravity = null; }
  20664. if (this._physicsEngine) {
  20665. return true;
  20666. }
  20667. try {
  20668. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20669. return true;
  20670. }
  20671. catch (e) {
  20672. BABYLON.Tools.Error(e.message);
  20673. return false;
  20674. }
  20675. };
  20676. Scene.prototype.disablePhysicsEngine = function () {
  20677. if (!this._physicsEngine) {
  20678. return;
  20679. }
  20680. this._physicsEngine.dispose();
  20681. this._physicsEngine = null;
  20682. };
  20683. Scene.prototype.isPhysicsEnabled = function () {
  20684. return this._physicsEngine !== undefined;
  20685. };
  20686. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20687. var mesh = compound.parts[0].mesh;
  20688. if (mesh.physicsImpostor) {
  20689. mesh.physicsImpostor.dispose();
  20690. mesh.physicsImpostor = null;
  20691. }
  20692. };
  20693. // Misc.
  20694. Scene.prototype._rebuildGeometries = function () {
  20695. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20696. var geometry = _a[_i];
  20697. geometry._rebuild();
  20698. }
  20699. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20700. var mesh = _c[_b];
  20701. mesh._rebuild();
  20702. }
  20703. if (this.postProcessManager) {
  20704. this.postProcessManager._rebuild();
  20705. }
  20706. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20707. var layer = _e[_d];
  20708. layer._rebuild();
  20709. }
  20710. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20711. var highlightLayer = _g[_f];
  20712. highlightLayer._rebuild();
  20713. }
  20714. if (this._boundingBoxRenderer) {
  20715. this._boundingBoxRenderer._rebuild();
  20716. }
  20717. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20718. var system = _j[_h];
  20719. system.rebuild();
  20720. }
  20721. if (this._postProcessRenderPipelineManager) {
  20722. this._postProcessRenderPipelineManager._rebuild();
  20723. }
  20724. };
  20725. Scene.prototype._rebuildTextures = function () {
  20726. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20727. var texture = _a[_i];
  20728. texture._rebuild();
  20729. }
  20730. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20731. };
  20732. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20733. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20734. if (replace === void 0) { replace = false; }
  20735. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20736. // Dispose existing camera or light in replace mode.
  20737. if (replace) {
  20738. if (this.activeCamera) {
  20739. this.activeCamera.dispose();
  20740. this.activeCamera = null;
  20741. }
  20742. if (this.lights) {
  20743. for (var i = 0; i < this.lights.length; i++) {
  20744. this.lights[i].dispose();
  20745. }
  20746. }
  20747. }
  20748. // Light
  20749. if (this.lights.length === 0) {
  20750. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20751. }
  20752. // Camera
  20753. if (!this.activeCamera) {
  20754. var worldExtends = this.getWorldExtends();
  20755. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20756. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20757. var camera;
  20758. var radius = worldSize.length() * 1.5;
  20759. if (createArcRotateCamera) {
  20760. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20761. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20762. arcRotateCamera.wheelPrecision = 100 / radius;
  20763. camera = arcRotateCamera;
  20764. }
  20765. else {
  20766. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20767. freeCamera.setTarget(worldCenter);
  20768. camera = freeCamera;
  20769. }
  20770. camera.minZ = radius * 0.01;
  20771. camera.maxZ = radius * 100;
  20772. camera.speed = radius * 0.2;
  20773. this.activeCamera = camera;
  20774. var canvas = this.getEngine().getRenderingCanvas();
  20775. if (attachCameraControls && canvas) {
  20776. camera.attachControl(canvas);
  20777. }
  20778. }
  20779. };
  20780. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20781. if (pbr === void 0) { pbr = false; }
  20782. if (scale === void 0) { scale = 1000; }
  20783. if (blur === void 0) { blur = 0; }
  20784. if (environmentTexture) {
  20785. this.environmentTexture = environmentTexture;
  20786. }
  20787. if (!this.environmentTexture) {
  20788. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20789. return null;
  20790. }
  20791. // Skybox
  20792. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20793. if (pbr) {
  20794. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20795. hdrSkyboxMaterial.backFaceCulling = false;
  20796. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20797. if (hdrSkyboxMaterial.reflectionTexture) {
  20798. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20799. }
  20800. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20801. hdrSkyboxMaterial.disableLighting = true;
  20802. hdrSkyboxMaterial.twoSidedLighting = true;
  20803. hdrSkybox.infiniteDistance = true;
  20804. hdrSkybox.material = hdrSkyboxMaterial;
  20805. }
  20806. else {
  20807. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20808. skyboxMaterial.backFaceCulling = false;
  20809. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20810. if (skyboxMaterial.reflectionTexture) {
  20811. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20812. }
  20813. skyboxMaterial.disableLighting = true;
  20814. hdrSkybox.infiniteDistance = true;
  20815. hdrSkybox.material = skyboxMaterial;
  20816. }
  20817. return hdrSkybox;
  20818. };
  20819. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20820. if (webVROptions === void 0) { webVROptions = {}; }
  20821. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20822. };
  20823. // Tags
  20824. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20825. if (tagsQuery === undefined) {
  20826. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20827. return list;
  20828. }
  20829. var listByTags = [];
  20830. forEach = forEach || (function (item) { return; });
  20831. for (var i in list) {
  20832. var item = list[i];
  20833. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20834. listByTags.push(item);
  20835. forEach(item);
  20836. }
  20837. }
  20838. return listByTags;
  20839. };
  20840. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20841. return this._getByTags(this.meshes, tagsQuery, forEach);
  20842. };
  20843. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20844. return this._getByTags(this.cameras, tagsQuery, forEach);
  20845. };
  20846. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20847. return this._getByTags(this.lights, tagsQuery, forEach);
  20848. };
  20849. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20850. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20851. };
  20852. /**
  20853. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20854. * This allowed control for front to back rendering or reversly depending of the special needs.
  20855. *
  20856. * @param renderingGroupId The rendering group id corresponding to its index
  20857. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20858. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20859. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20860. */
  20861. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20862. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20863. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20864. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20865. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20866. };
  20867. /**
  20868. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20869. *
  20870. * @param renderingGroupId The rendering group id corresponding to its index
  20871. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20872. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20873. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20874. */
  20875. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20876. if (depth === void 0) { depth = true; }
  20877. if (stencil === void 0) { stencil = true; }
  20878. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20879. };
  20880. /**
  20881. * Will flag all materials as dirty to trigger new shader compilation
  20882. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20883. */
  20884. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20885. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20886. var material = _a[_i];
  20887. if (predicate && !predicate(material)) {
  20888. continue;
  20889. }
  20890. material.markAsDirty(flag);
  20891. }
  20892. };
  20893. // Statics
  20894. Scene._FOGMODE_NONE = 0;
  20895. Scene._FOGMODE_EXP = 1;
  20896. Scene._FOGMODE_EXP2 = 2;
  20897. Scene._FOGMODE_LINEAR = 3;
  20898. Scene._uniqueIdCounter = 0;
  20899. Scene.MinDeltaTime = 1.0;
  20900. Scene.MaxDeltaTime = 1000.0;
  20901. /** The distance in pixel that you have to move to prevent some events */
  20902. Scene.DragMovementThreshold = 10; // in pixels
  20903. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20904. Scene.LongPressDelay = 500; // in milliseconds
  20905. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20906. Scene.DoubleClickDelay = 300; // in milliseconds
  20907. /** If you need to check double click without raising a single click at first click, enable this flag */
  20908. Scene.ExclusiveDoubleClickMode = false;
  20909. return Scene;
  20910. }());
  20911. BABYLON.Scene = Scene;
  20912. })(BABYLON || (BABYLON = {}));
  20913. //# sourceMappingURL=babylon.scene.js.map
  20914. var BABYLON;
  20915. (function (BABYLON) {
  20916. var Buffer = /** @class */ (function () {
  20917. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20918. if (instanced === void 0) { instanced = false; }
  20919. if (engine instanceof BABYLON.Mesh) {
  20920. this._engine = engine.getScene().getEngine();
  20921. }
  20922. else {
  20923. this._engine = engine;
  20924. }
  20925. this._updatable = updatable;
  20926. this._data = data;
  20927. this._strideSize = stride;
  20928. if (!postponeInternalCreation) {
  20929. this.create();
  20930. }
  20931. this._instanced = instanced;
  20932. this._instanceDivisor = instanced ? 1 : 0;
  20933. }
  20934. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20935. // a lot of these parameters are ignored as they are overriden by the buffer
  20936. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20937. };
  20938. // Properties
  20939. Buffer.prototype.isUpdatable = function () {
  20940. return this._updatable;
  20941. };
  20942. Buffer.prototype.getData = function () {
  20943. return this._data;
  20944. };
  20945. Buffer.prototype.getBuffer = function () {
  20946. return this._buffer;
  20947. };
  20948. Buffer.prototype.getStrideSize = function () {
  20949. return this._strideSize;
  20950. };
  20951. Buffer.prototype.getIsInstanced = function () {
  20952. return this._instanced;
  20953. };
  20954. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20955. get: function () {
  20956. return this._instanceDivisor;
  20957. },
  20958. set: function (value) {
  20959. this._instanceDivisor = value;
  20960. if (value == 0) {
  20961. this._instanced = false;
  20962. }
  20963. else {
  20964. this._instanced = true;
  20965. }
  20966. },
  20967. enumerable: true,
  20968. configurable: true
  20969. });
  20970. // Methods
  20971. Buffer.prototype.create = function (data) {
  20972. if (data === void 0) { data = null; }
  20973. if (!data && this._buffer) {
  20974. return; // nothing to do
  20975. }
  20976. data = data || this._data;
  20977. if (!data) {
  20978. return;
  20979. }
  20980. if (!this._buffer) {
  20981. if (this._updatable) {
  20982. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20983. this._data = data;
  20984. }
  20985. else {
  20986. this._buffer = this._engine.createVertexBuffer(data);
  20987. }
  20988. }
  20989. else if (this._updatable) {
  20990. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20991. this._data = data;
  20992. }
  20993. };
  20994. Buffer.prototype._rebuild = function () {
  20995. this._buffer = null;
  20996. this.create(this._data);
  20997. };
  20998. Buffer.prototype.update = function (data) {
  20999. this.create(data);
  21000. };
  21001. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21002. if (!this._buffer) {
  21003. return;
  21004. }
  21005. if (this._updatable) {
  21006. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21007. this._data = null;
  21008. }
  21009. };
  21010. Buffer.prototype.dispose = function () {
  21011. if (!this._buffer) {
  21012. return;
  21013. }
  21014. if (this._engine._releaseBuffer(this._buffer)) {
  21015. this._buffer = null;
  21016. }
  21017. };
  21018. return Buffer;
  21019. }());
  21020. BABYLON.Buffer = Buffer;
  21021. })(BABYLON || (BABYLON = {}));
  21022. //# sourceMappingURL=babylon.buffer.js.map
  21023. var BABYLON;
  21024. (function (BABYLON) {
  21025. var VertexBuffer = /** @class */ (function () {
  21026. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21027. if (!stride) {
  21028. // Deduce stride from kind
  21029. switch (kind) {
  21030. case VertexBuffer.PositionKind:
  21031. stride = 3;
  21032. break;
  21033. case VertexBuffer.NormalKind:
  21034. stride = 3;
  21035. break;
  21036. case VertexBuffer.UVKind:
  21037. case VertexBuffer.UV2Kind:
  21038. case VertexBuffer.UV3Kind:
  21039. case VertexBuffer.UV4Kind:
  21040. case VertexBuffer.UV5Kind:
  21041. case VertexBuffer.UV6Kind:
  21042. stride = 2;
  21043. break;
  21044. case VertexBuffer.TangentKind:
  21045. case VertexBuffer.ColorKind:
  21046. stride = 4;
  21047. break;
  21048. case VertexBuffer.MatricesIndicesKind:
  21049. case VertexBuffer.MatricesIndicesExtraKind:
  21050. stride = 4;
  21051. break;
  21052. case VertexBuffer.MatricesWeightsKind:
  21053. case VertexBuffer.MatricesWeightsExtraKind:
  21054. default:
  21055. stride = 4;
  21056. break;
  21057. }
  21058. }
  21059. if (data instanceof BABYLON.Buffer) {
  21060. if (!stride) {
  21061. stride = data.getStrideSize();
  21062. }
  21063. this._buffer = data;
  21064. this._ownsBuffer = false;
  21065. }
  21066. else {
  21067. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21068. this._ownsBuffer = true;
  21069. }
  21070. this._stride = stride;
  21071. this._offset = offset ? offset : 0;
  21072. this._size = size ? size : stride;
  21073. this._kind = kind;
  21074. }
  21075. VertexBuffer.prototype._rebuild = function () {
  21076. if (!this._buffer) {
  21077. return;
  21078. }
  21079. this._buffer._rebuild();
  21080. };
  21081. /**
  21082. * Returns the kind of the VertexBuffer (string).
  21083. */
  21084. VertexBuffer.prototype.getKind = function () {
  21085. return this._kind;
  21086. };
  21087. // Properties
  21088. /**
  21089. * Boolean : is the VertexBuffer updatable ?
  21090. */
  21091. VertexBuffer.prototype.isUpdatable = function () {
  21092. return this._buffer.isUpdatable();
  21093. };
  21094. /**
  21095. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21096. */
  21097. VertexBuffer.prototype.getData = function () {
  21098. return this._buffer.getData();
  21099. };
  21100. /**
  21101. * Returns the WebGLBuffer associated to the VertexBuffer.
  21102. */
  21103. VertexBuffer.prototype.getBuffer = function () {
  21104. return this._buffer.getBuffer();
  21105. };
  21106. /**
  21107. * Returns the stride of the VertexBuffer (integer).
  21108. */
  21109. VertexBuffer.prototype.getStrideSize = function () {
  21110. return this._stride;
  21111. };
  21112. /**
  21113. * Returns the offset (integer).
  21114. */
  21115. VertexBuffer.prototype.getOffset = function () {
  21116. return this._offset;
  21117. };
  21118. /**
  21119. * Returns the VertexBuffer total size (integer).
  21120. */
  21121. VertexBuffer.prototype.getSize = function () {
  21122. return this._size;
  21123. };
  21124. /**
  21125. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21126. */
  21127. VertexBuffer.prototype.getIsInstanced = function () {
  21128. return this._buffer.getIsInstanced();
  21129. };
  21130. /**
  21131. * Returns the instancing divisor, zero for non-instanced (integer).
  21132. */
  21133. VertexBuffer.prototype.getInstanceDivisor = function () {
  21134. return this._buffer.instanceDivisor;
  21135. };
  21136. // Methods
  21137. /**
  21138. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21139. * Returns the created WebGLBuffer.
  21140. */
  21141. VertexBuffer.prototype.create = function (data) {
  21142. return this._buffer.create(data);
  21143. };
  21144. /**
  21145. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21146. * Returns the updated WebGLBuffer.
  21147. */
  21148. VertexBuffer.prototype.update = function (data) {
  21149. return this._buffer.update(data);
  21150. };
  21151. /**
  21152. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21153. * Returns the directly updated WebGLBuffer.
  21154. */
  21155. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21156. return this._buffer.updateDirectly(data, offset);
  21157. };
  21158. /**
  21159. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21160. */
  21161. VertexBuffer.prototype.dispose = function () {
  21162. if (this._ownsBuffer) {
  21163. this._buffer.dispose();
  21164. }
  21165. };
  21166. Object.defineProperty(VertexBuffer, "PositionKind", {
  21167. get: function () {
  21168. return VertexBuffer._PositionKind;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(VertexBuffer, "NormalKind", {
  21174. get: function () {
  21175. return VertexBuffer._NormalKind;
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. Object.defineProperty(VertexBuffer, "TangentKind", {
  21181. get: function () {
  21182. return VertexBuffer._TangentKind;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. Object.defineProperty(VertexBuffer, "UVKind", {
  21188. get: function () {
  21189. return VertexBuffer._UVKind;
  21190. },
  21191. enumerable: true,
  21192. configurable: true
  21193. });
  21194. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21195. get: function () {
  21196. return VertexBuffer._UV2Kind;
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21202. get: function () {
  21203. return VertexBuffer._UV3Kind;
  21204. },
  21205. enumerable: true,
  21206. configurable: true
  21207. });
  21208. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21209. get: function () {
  21210. return VertexBuffer._UV4Kind;
  21211. },
  21212. enumerable: true,
  21213. configurable: true
  21214. });
  21215. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21216. get: function () {
  21217. return VertexBuffer._UV5Kind;
  21218. },
  21219. enumerable: true,
  21220. configurable: true
  21221. });
  21222. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21223. get: function () {
  21224. return VertexBuffer._UV6Kind;
  21225. },
  21226. enumerable: true,
  21227. configurable: true
  21228. });
  21229. Object.defineProperty(VertexBuffer, "ColorKind", {
  21230. get: function () {
  21231. return VertexBuffer._ColorKind;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21237. get: function () {
  21238. return VertexBuffer._MatricesIndicesKind;
  21239. },
  21240. enumerable: true,
  21241. configurable: true
  21242. });
  21243. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21244. get: function () {
  21245. return VertexBuffer._MatricesWeightsKind;
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21251. get: function () {
  21252. return VertexBuffer._MatricesIndicesExtraKind;
  21253. },
  21254. enumerable: true,
  21255. configurable: true
  21256. });
  21257. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21258. get: function () {
  21259. return VertexBuffer._MatricesWeightsExtraKind;
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. // Enums
  21265. VertexBuffer._PositionKind = "position";
  21266. VertexBuffer._NormalKind = "normal";
  21267. VertexBuffer._TangentKind = "tangent";
  21268. VertexBuffer._UVKind = "uv";
  21269. VertexBuffer._UV2Kind = "uv2";
  21270. VertexBuffer._UV3Kind = "uv3";
  21271. VertexBuffer._UV4Kind = "uv4";
  21272. VertexBuffer._UV5Kind = "uv5";
  21273. VertexBuffer._UV6Kind = "uv6";
  21274. VertexBuffer._ColorKind = "color";
  21275. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21276. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21277. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21278. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21279. return VertexBuffer;
  21280. }());
  21281. BABYLON.VertexBuffer = VertexBuffer;
  21282. })(BABYLON || (BABYLON = {}));
  21283. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21284. var BABYLON;
  21285. (function (BABYLON) {
  21286. var InternalTexture = /** @class */ (function () {
  21287. function InternalTexture(engine, dataSource) {
  21288. this.onLoadedObservable = new BABYLON.Observable();
  21289. // Private
  21290. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21291. this._references = 1;
  21292. this._engine = engine;
  21293. this._dataSource = dataSource;
  21294. this._webGLTexture = engine._createTexture();
  21295. }
  21296. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21297. get: function () {
  21298. return this._dataSource;
  21299. },
  21300. enumerable: true,
  21301. configurable: true
  21302. });
  21303. InternalTexture.prototype.incrementReferences = function () {
  21304. this._references++;
  21305. };
  21306. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21307. if (depth === void 0) { depth = 1; }
  21308. this.width = width;
  21309. this.height = height;
  21310. this.depth = depth;
  21311. this.baseWidth = width;
  21312. this.baseHeight = height;
  21313. this.baseDepth = depth;
  21314. this._size = width * height * depth;
  21315. };
  21316. InternalTexture.prototype._rebuild = function () {
  21317. var _this = this;
  21318. var proxy;
  21319. this.isReady = false;
  21320. this._cachedCoordinatesMode = null;
  21321. this._cachedWrapU = null;
  21322. this._cachedWrapV = null;
  21323. this._cachedAnisotropicFilteringLevel = null;
  21324. switch (this._dataSource) {
  21325. case InternalTexture.DATASOURCE_TEMP:
  21326. return;
  21327. case InternalTexture.DATASOURCE_URL:
  21328. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21329. _this.isReady = true;
  21330. }, null, this._buffer, undefined, this.format);
  21331. proxy._swapAndDie(this);
  21332. return;
  21333. case InternalTexture.DATASOURCE_RAW:
  21334. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21335. proxy._swapAndDie(this);
  21336. this.isReady = true;
  21337. return;
  21338. case InternalTexture.DATASOURCE_RAW3D:
  21339. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21340. proxy._swapAndDie(this);
  21341. this.isReady = true;
  21342. return;
  21343. case InternalTexture.DATASOURCE_DYNAMIC:
  21344. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21345. proxy._swapAndDie(this);
  21346. // The engine will make sure to update content so no need to flag it as isReady = true
  21347. return;
  21348. case InternalTexture.DATASOURCE_RENDERTARGET:
  21349. var options = new BABYLON.RenderTargetCreationOptions();
  21350. options.generateDepthBuffer = this._generateDepthBuffer;
  21351. options.generateMipMaps = this.generateMipMaps;
  21352. options.generateStencilBuffer = this._generateStencilBuffer;
  21353. options.samplingMode = this.samplingMode;
  21354. options.type = this.type;
  21355. if (this.isCube) {
  21356. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21357. }
  21358. else {
  21359. var size = {
  21360. width: this.width,
  21361. height: this.height
  21362. };
  21363. proxy = this._engine.createRenderTargetTexture(size, options);
  21364. }
  21365. proxy._swapAndDie(this);
  21366. this.isReady = true;
  21367. return;
  21368. case InternalTexture.DATASOURCE_CUBE:
  21369. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21370. _this.isReady = true;
  21371. }, null, this.format, this._extension);
  21372. proxy._swapAndDie(this);
  21373. return;
  21374. case InternalTexture.DATASOURCE_CUBERAW:
  21375. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21376. proxy._swapAndDie(this);
  21377. this.isReady = true;
  21378. return;
  21379. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21380. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21381. if (proxy) {
  21382. proxy._swapAndDie(_this);
  21383. }
  21384. _this.isReady = true;
  21385. }, null, this.format, this._extension);
  21386. return;
  21387. }
  21388. };
  21389. InternalTexture.prototype._swapAndDie = function (target) {
  21390. target._webGLTexture = this._webGLTexture;
  21391. if (this._framebuffer) {
  21392. target._framebuffer = this._framebuffer;
  21393. }
  21394. if (this._depthStencilBuffer) {
  21395. target._depthStencilBuffer = this._depthStencilBuffer;
  21396. }
  21397. if (this._lodTextureHigh) {
  21398. if (target._lodTextureHigh) {
  21399. target._lodTextureHigh.dispose();
  21400. }
  21401. target._lodTextureHigh = this._lodTextureHigh;
  21402. }
  21403. if (this._lodTextureMid) {
  21404. if (target._lodTextureMid) {
  21405. target._lodTextureMid.dispose();
  21406. }
  21407. target._lodTextureMid = this._lodTextureMid;
  21408. }
  21409. if (this._lodTextureLow) {
  21410. if (target._lodTextureLow) {
  21411. target._lodTextureLow.dispose();
  21412. }
  21413. target._lodTextureLow = this._lodTextureLow;
  21414. }
  21415. var cache = this._engine.getLoadedTexturesCache();
  21416. var index = cache.indexOf(this);
  21417. if (index !== -1) {
  21418. cache.splice(index, 1);
  21419. }
  21420. };
  21421. InternalTexture.prototype.dispose = function () {
  21422. if (!this._webGLTexture) {
  21423. return;
  21424. }
  21425. this._references--;
  21426. if (this._references === 0) {
  21427. this._engine._releaseTexture(this);
  21428. this._webGLTexture = null;
  21429. }
  21430. };
  21431. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21432. InternalTexture.DATASOURCE_URL = 1;
  21433. InternalTexture.DATASOURCE_TEMP = 2;
  21434. InternalTexture.DATASOURCE_RAW = 3;
  21435. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21436. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21437. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21438. InternalTexture.DATASOURCE_CUBE = 7;
  21439. InternalTexture.DATASOURCE_CUBERAW = 8;
  21440. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21441. InternalTexture.DATASOURCE_RAW3D = 10;
  21442. return InternalTexture;
  21443. }());
  21444. BABYLON.InternalTexture = InternalTexture;
  21445. })(BABYLON || (BABYLON = {}));
  21446. //# sourceMappingURL=babylon.internalTexture.js.map
  21447. var BABYLON;
  21448. (function (BABYLON) {
  21449. var BaseTexture = /** @class */ (function () {
  21450. function BaseTexture(scene) {
  21451. this._hasAlpha = false;
  21452. this.getAlphaFromRGB = false;
  21453. this.level = 1;
  21454. this.coordinatesIndex = 0;
  21455. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21456. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21457. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21458. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21459. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21460. this.isCube = false;
  21461. this.is3D = false;
  21462. this.gammaSpace = true;
  21463. this.invertZ = false;
  21464. this.lodLevelInAlpha = false;
  21465. this.lodGenerationOffset = 0.0;
  21466. this.lodGenerationScale = 0.8;
  21467. this.isRenderTarget = false;
  21468. this.animations = new Array();
  21469. /**
  21470. * An event triggered when the texture is disposed.
  21471. * @type {BABYLON.Observable}
  21472. */
  21473. this.onDisposeObservable = new BABYLON.Observable();
  21474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21475. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21476. if (this._scene) {
  21477. this._scene.textures.push(this);
  21478. }
  21479. this._uid = null;
  21480. }
  21481. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21482. get: function () {
  21483. return this._hasAlpha;
  21484. },
  21485. set: function (value) {
  21486. if (this._hasAlpha === value) {
  21487. return;
  21488. }
  21489. this._hasAlpha = value;
  21490. if (this._scene) {
  21491. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21492. }
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21498. get: function () {
  21499. return this._coordinatesMode;
  21500. },
  21501. set: function (value) {
  21502. if (this._coordinatesMode === value) {
  21503. return;
  21504. }
  21505. this._coordinatesMode = value;
  21506. if (this._scene) {
  21507. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21508. }
  21509. },
  21510. enumerable: true,
  21511. configurable: true
  21512. });
  21513. Object.defineProperty(BaseTexture.prototype, "uid", {
  21514. get: function () {
  21515. if (!this._uid) {
  21516. this._uid = BABYLON.Tools.RandomId();
  21517. }
  21518. return this._uid;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. BaseTexture.prototype.toString = function () {
  21524. return this.name;
  21525. };
  21526. BaseTexture.prototype.getClassName = function () {
  21527. return "BaseTexture";
  21528. };
  21529. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21530. set: function (callback) {
  21531. if (this._onDisposeObserver) {
  21532. this.onDisposeObservable.remove(this._onDisposeObserver);
  21533. }
  21534. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21540. get: function () {
  21541. return true;
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. BaseTexture.prototype.getScene = function () {
  21547. return this._scene;
  21548. };
  21549. BaseTexture.prototype.getTextureMatrix = function () {
  21550. return BABYLON.Matrix.IdentityReadOnly;
  21551. };
  21552. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21553. return BABYLON.Matrix.IdentityReadOnly;
  21554. };
  21555. BaseTexture.prototype.getInternalTexture = function () {
  21556. return this._texture;
  21557. };
  21558. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21559. return !this.isBlocking || this.isReady();
  21560. };
  21561. BaseTexture.prototype.isReady = function () {
  21562. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21563. this.delayLoad();
  21564. return false;
  21565. }
  21566. if (this._texture) {
  21567. return this._texture.isReady;
  21568. }
  21569. return false;
  21570. };
  21571. BaseTexture.prototype.getSize = function () {
  21572. if (this._texture && this._texture.width) {
  21573. return new BABYLON.Size(this._texture.width, this._texture.height);
  21574. }
  21575. if (this._texture && this._texture._size) {
  21576. return new BABYLON.Size(this._texture._size, this._texture._size);
  21577. }
  21578. return BABYLON.Size.Zero();
  21579. };
  21580. BaseTexture.prototype.getBaseSize = function () {
  21581. if (!this.isReady() || !this._texture)
  21582. return BABYLON.Size.Zero();
  21583. if (this._texture._size) {
  21584. return new BABYLON.Size(this._texture._size, this._texture._size);
  21585. }
  21586. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21587. };
  21588. BaseTexture.prototype.scale = function (ratio) {
  21589. };
  21590. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21591. get: function () {
  21592. return false;
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21598. if (!this._scene) {
  21599. return null;
  21600. }
  21601. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21602. for (var index = 0; index < texturesCache.length; index++) {
  21603. var texturesCacheEntry = texturesCache[index];
  21604. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21605. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21606. texturesCacheEntry.incrementReferences();
  21607. return texturesCacheEntry;
  21608. }
  21609. }
  21610. }
  21611. return null;
  21612. };
  21613. BaseTexture.prototype._rebuild = function () {
  21614. };
  21615. BaseTexture.prototype.delayLoad = function () {
  21616. };
  21617. BaseTexture.prototype.clone = function () {
  21618. return null;
  21619. };
  21620. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21621. get: function () {
  21622. if (!this._texture) {
  21623. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21624. }
  21625. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21631. get: function () {
  21632. if (!this._texture) {
  21633. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21634. }
  21635. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. BaseTexture.prototype.readPixels = function (faceIndex) {
  21641. if (faceIndex === void 0) { faceIndex = 0; }
  21642. if (!this._texture) {
  21643. return null;
  21644. }
  21645. var size = this.getSize();
  21646. var scene = this.getScene();
  21647. if (!scene) {
  21648. return null;
  21649. }
  21650. var engine = scene.getEngine();
  21651. if (this._texture.isCube) {
  21652. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21653. }
  21654. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21655. };
  21656. BaseTexture.prototype.releaseInternalTexture = function () {
  21657. if (this._texture) {
  21658. this._texture.dispose();
  21659. this._texture = null;
  21660. }
  21661. };
  21662. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21663. get: function () {
  21664. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21665. return null;
  21666. }
  21667. if (!this._texture._sphericalPolynomial) {
  21668. this._texture._sphericalPolynomial =
  21669. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21670. }
  21671. return this._texture._sphericalPolynomial;
  21672. },
  21673. set: function (value) {
  21674. if (this._texture) {
  21675. this._texture._sphericalPolynomial = value;
  21676. }
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21682. get: function () {
  21683. if (this._texture) {
  21684. return this._texture._lodTextureHigh;
  21685. }
  21686. return null;
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21692. get: function () {
  21693. if (this._texture) {
  21694. return this._texture._lodTextureMid;
  21695. }
  21696. return null;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21702. get: function () {
  21703. if (this._texture) {
  21704. return this._texture._lodTextureLow;
  21705. }
  21706. return null;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. BaseTexture.prototype.dispose = function () {
  21712. if (!this._scene) {
  21713. return;
  21714. }
  21715. // Animations
  21716. this._scene.stopAnimation(this);
  21717. // Remove from scene
  21718. this._scene._removePendingData(this);
  21719. var index = this._scene.textures.indexOf(this);
  21720. if (index >= 0) {
  21721. this._scene.textures.splice(index, 1);
  21722. }
  21723. if (this._texture === undefined) {
  21724. return;
  21725. }
  21726. // Release
  21727. this.releaseInternalTexture();
  21728. // Callback
  21729. this.onDisposeObservable.notifyObservers(this);
  21730. this.onDisposeObservable.clear();
  21731. };
  21732. BaseTexture.prototype.serialize = function () {
  21733. if (!this.name) {
  21734. return null;
  21735. }
  21736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21737. // Animations
  21738. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21739. return serializationObject;
  21740. };
  21741. BaseTexture.WhenAllReady = function (textures, callback) {
  21742. var numRemaining = textures.length;
  21743. if (numRemaining === 0) {
  21744. callback();
  21745. return;
  21746. }
  21747. var _loop_1 = function () {
  21748. texture = textures[i];
  21749. if (texture.isReady()) {
  21750. if (--numRemaining === 0) {
  21751. callback();
  21752. }
  21753. }
  21754. else {
  21755. onLoadObservable = texture.onLoadObservable;
  21756. var onLoadCallback_1 = function () {
  21757. onLoadObservable.removeCallback(onLoadCallback_1);
  21758. if (--numRemaining === 0) {
  21759. callback();
  21760. }
  21761. };
  21762. onLoadObservable.add(onLoadCallback_1);
  21763. }
  21764. };
  21765. var texture, onLoadObservable;
  21766. for (var i = 0; i < textures.length; i++) {
  21767. _loop_1();
  21768. }
  21769. };
  21770. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21771. __decorate([
  21772. BABYLON.serialize()
  21773. ], BaseTexture.prototype, "name", void 0);
  21774. __decorate([
  21775. BABYLON.serialize("hasAlpha")
  21776. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21777. __decorate([
  21778. BABYLON.serialize()
  21779. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21780. __decorate([
  21781. BABYLON.serialize()
  21782. ], BaseTexture.prototype, "level", void 0);
  21783. __decorate([
  21784. BABYLON.serialize()
  21785. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21786. __decorate([
  21787. BABYLON.serialize("coordinatesMode")
  21788. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21789. __decorate([
  21790. BABYLON.serialize()
  21791. ], BaseTexture.prototype, "wrapU", void 0);
  21792. __decorate([
  21793. BABYLON.serialize()
  21794. ], BaseTexture.prototype, "wrapV", void 0);
  21795. __decorate([
  21796. BABYLON.serialize()
  21797. ], BaseTexture.prototype, "wrapR", void 0);
  21798. __decorate([
  21799. BABYLON.serialize()
  21800. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21801. __decorate([
  21802. BABYLON.serialize()
  21803. ], BaseTexture.prototype, "isCube", void 0);
  21804. __decorate([
  21805. BABYLON.serialize()
  21806. ], BaseTexture.prototype, "is3D", void 0);
  21807. __decorate([
  21808. BABYLON.serialize()
  21809. ], BaseTexture.prototype, "gammaSpace", void 0);
  21810. __decorate([
  21811. BABYLON.serialize()
  21812. ], BaseTexture.prototype, "invertZ", void 0);
  21813. __decorate([
  21814. BABYLON.serialize()
  21815. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21816. __decorate([
  21817. BABYLON.serialize()
  21818. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21819. __decorate([
  21820. BABYLON.serialize()
  21821. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21822. __decorate([
  21823. BABYLON.serialize()
  21824. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21825. return BaseTexture;
  21826. }());
  21827. BABYLON.BaseTexture = BaseTexture;
  21828. })(BABYLON || (BABYLON = {}));
  21829. //# sourceMappingURL=babylon.baseTexture.js.map
  21830. var BABYLON;
  21831. (function (BABYLON) {
  21832. var Texture = /** @class */ (function (_super) {
  21833. __extends(Texture, _super);
  21834. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21835. if (noMipmap === void 0) { noMipmap = false; }
  21836. if (invertY === void 0) { invertY = true; }
  21837. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21838. if (onLoad === void 0) { onLoad = null; }
  21839. if (onError === void 0) { onError = null; }
  21840. if (buffer === void 0) { buffer = null; }
  21841. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21842. var _this = _super.call(this, scene) || this;
  21843. _this.uOffset = 0;
  21844. _this.vOffset = 0;
  21845. _this.uScale = 1.0;
  21846. _this.vScale = 1.0;
  21847. _this.uAng = 0;
  21848. _this.vAng = 0;
  21849. _this.wAng = 0;
  21850. _this._isBlocking = true;
  21851. _this.name = url || "";
  21852. _this.url = url;
  21853. _this._noMipmap = noMipmap;
  21854. _this._invertY = invertY;
  21855. _this._samplingMode = samplingMode;
  21856. _this._buffer = buffer;
  21857. _this._deleteBuffer = deleteBuffer;
  21858. if (format) {
  21859. _this._format = format;
  21860. }
  21861. scene = _this.getScene();
  21862. if (!scene) {
  21863. return _this;
  21864. }
  21865. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21866. var load = function () {
  21867. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21868. _this.onLoadObservable.notifyObservers(_this);
  21869. }
  21870. if (onLoad) {
  21871. onLoad();
  21872. }
  21873. if (!_this.isBlocking && scene) {
  21874. scene.resetCachedMaterial();
  21875. }
  21876. };
  21877. if (!_this.url) {
  21878. _this._delayedOnLoad = load;
  21879. _this._delayedOnError = onError;
  21880. return _this;
  21881. }
  21882. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21883. if (!_this._texture) {
  21884. if (!scene.useDelayedTextureLoading) {
  21885. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21886. if (deleteBuffer) {
  21887. delete _this._buffer;
  21888. }
  21889. }
  21890. else {
  21891. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21892. _this._delayedOnLoad = load;
  21893. _this._delayedOnError = onError;
  21894. }
  21895. }
  21896. else {
  21897. if (_this._texture.isReady) {
  21898. BABYLON.Tools.SetImmediate(function () { return load(); });
  21899. }
  21900. else {
  21901. _this._texture.onLoadedObservable.add(load);
  21902. }
  21903. }
  21904. return _this;
  21905. }
  21906. Object.defineProperty(Texture.prototype, "noMipmap", {
  21907. get: function () {
  21908. return this._noMipmap;
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. Object.defineProperty(Texture.prototype, "isBlocking", {
  21914. get: function () {
  21915. return this._isBlocking;
  21916. },
  21917. set: function (value) {
  21918. this._isBlocking = value;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(Texture.prototype, "samplingMode", {
  21924. get: function () {
  21925. return this._samplingMode;
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Texture.prototype.updateURL = function (url) {
  21931. this.url = url;
  21932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21933. this.delayLoad();
  21934. };
  21935. Texture.prototype.delayLoad = function () {
  21936. var _this = this;
  21937. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21938. return;
  21939. }
  21940. var scene = this.getScene();
  21941. if (!scene) {
  21942. return;
  21943. }
  21944. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21945. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21946. if (!this._texture) {
  21947. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21948. if (this._deleteBuffer) {
  21949. delete this._buffer;
  21950. }
  21951. }
  21952. else {
  21953. if (this._texture.isReady) {
  21954. BABYLON.Tools.SetImmediate(function () {
  21955. if (!_this._delayedOnLoad) {
  21956. return;
  21957. }
  21958. _this._delayedOnLoad();
  21959. });
  21960. }
  21961. else {
  21962. if (this._delayedOnLoad) {
  21963. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21964. }
  21965. }
  21966. }
  21967. };
  21968. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21969. if (!this._texture) {
  21970. return;
  21971. }
  21972. var scene = this.getScene();
  21973. if (!scene) {
  21974. return;
  21975. }
  21976. this._samplingMode = samplingMode;
  21977. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21978. };
  21979. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21980. x *= this.uScale;
  21981. y *= this.vScale;
  21982. x -= 0.5 * this.uScale;
  21983. y -= 0.5 * this.vScale;
  21984. z -= 0.5;
  21985. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21986. t.x += 0.5 * this.uScale + this.uOffset;
  21987. t.y += 0.5 * this.vScale + this.vOffset;
  21988. t.z += 0.5;
  21989. };
  21990. Texture.prototype.getTextureMatrix = function () {
  21991. var _this = this;
  21992. if (this.uOffset === this._cachedUOffset &&
  21993. this.vOffset === this._cachedVOffset &&
  21994. this.uScale === this._cachedUScale &&
  21995. this.vScale === this._cachedVScale &&
  21996. this.uAng === this._cachedUAng &&
  21997. this.vAng === this._cachedVAng &&
  21998. this.wAng === this._cachedWAng) {
  21999. return this._cachedTextureMatrix;
  22000. }
  22001. this._cachedUOffset = this.uOffset;
  22002. this._cachedVOffset = this.vOffset;
  22003. this._cachedUScale = this.uScale;
  22004. this._cachedVScale = this.vScale;
  22005. this._cachedUAng = this.uAng;
  22006. this._cachedVAng = this.vAng;
  22007. this._cachedWAng = this.wAng;
  22008. if (!this._cachedTextureMatrix) {
  22009. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22010. this._rowGenerationMatrix = new BABYLON.Matrix();
  22011. this._t0 = BABYLON.Vector3.Zero();
  22012. this._t1 = BABYLON.Vector3.Zero();
  22013. this._t2 = BABYLON.Vector3.Zero();
  22014. }
  22015. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22016. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22017. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22018. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22019. this._t1.subtractInPlace(this._t0);
  22020. this._t2.subtractInPlace(this._t0);
  22021. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22022. this._cachedTextureMatrix.m[0] = this._t1.x;
  22023. this._cachedTextureMatrix.m[1] = this._t1.y;
  22024. this._cachedTextureMatrix.m[2] = this._t1.z;
  22025. this._cachedTextureMatrix.m[4] = this._t2.x;
  22026. this._cachedTextureMatrix.m[5] = this._t2.y;
  22027. this._cachedTextureMatrix.m[6] = this._t2.z;
  22028. this._cachedTextureMatrix.m[8] = this._t0.x;
  22029. this._cachedTextureMatrix.m[9] = this._t0.y;
  22030. this._cachedTextureMatrix.m[10] = this._t0.z;
  22031. var scene = this.getScene();
  22032. if (!scene) {
  22033. return this._cachedTextureMatrix;
  22034. }
  22035. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22036. return mat.hasTexture(_this);
  22037. });
  22038. return this._cachedTextureMatrix;
  22039. };
  22040. Texture.prototype.getReflectionTextureMatrix = function () {
  22041. var _this = this;
  22042. var scene = this.getScene();
  22043. if (!scene) {
  22044. return this._cachedTextureMatrix;
  22045. }
  22046. if (this.uOffset === this._cachedUOffset &&
  22047. this.vOffset === this._cachedVOffset &&
  22048. this.uScale === this._cachedUScale &&
  22049. this.vScale === this._cachedVScale &&
  22050. this.coordinatesMode === this._cachedCoordinatesMode) {
  22051. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22052. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22053. return this._cachedTextureMatrix;
  22054. }
  22055. }
  22056. else {
  22057. return this._cachedTextureMatrix;
  22058. }
  22059. }
  22060. if (!this._cachedTextureMatrix) {
  22061. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22062. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22063. }
  22064. this._cachedUOffset = this.uOffset;
  22065. this._cachedVOffset = this.vOffset;
  22066. this._cachedUScale = this.uScale;
  22067. this._cachedVScale = this.vScale;
  22068. this._cachedCoordinatesMode = this.coordinatesMode;
  22069. switch (this.coordinatesMode) {
  22070. case Texture.PLANAR_MODE:
  22071. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22072. this._cachedTextureMatrix[0] = this.uScale;
  22073. this._cachedTextureMatrix[5] = this.vScale;
  22074. this._cachedTextureMatrix[12] = this.uOffset;
  22075. this._cachedTextureMatrix[13] = this.vOffset;
  22076. break;
  22077. case Texture.PROJECTION_MODE:
  22078. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22079. this._projectionModeMatrix.m[0] = 0.5;
  22080. this._projectionModeMatrix.m[5] = -0.5;
  22081. this._projectionModeMatrix.m[10] = 0.0;
  22082. this._projectionModeMatrix.m[12] = 0.5;
  22083. this._projectionModeMatrix.m[13] = 0.5;
  22084. this._projectionModeMatrix.m[14] = 1.0;
  22085. this._projectionModeMatrix.m[15] = 1.0;
  22086. var projectionMatrix = scene.getProjectionMatrix();
  22087. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22088. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22089. break;
  22090. default:
  22091. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22092. break;
  22093. }
  22094. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22095. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22096. });
  22097. return this._cachedTextureMatrix;
  22098. };
  22099. Texture.prototype.clone = function () {
  22100. var _this = this;
  22101. return BABYLON.SerializationHelper.Clone(function () {
  22102. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22103. }, this);
  22104. };
  22105. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22106. get: function () {
  22107. if (!this._onLoadObservable) {
  22108. this._onLoadObservable = new BABYLON.Observable();
  22109. }
  22110. return this._onLoadObservable;
  22111. },
  22112. enumerable: true,
  22113. configurable: true
  22114. });
  22115. Texture.prototype.serialize = function () {
  22116. var serializationObject = _super.prototype.serialize.call(this);
  22117. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22118. serializationObject.base64String = this._buffer;
  22119. serializationObject.name = serializationObject.name.replace("data:", "");
  22120. }
  22121. return serializationObject;
  22122. };
  22123. Texture.prototype.getClassName = function () {
  22124. return "Texture";
  22125. };
  22126. Texture.prototype.dispose = function () {
  22127. _super.prototype.dispose.call(this);
  22128. if (this.onLoadObservable) {
  22129. this.onLoadObservable.clear();
  22130. this._onLoadObservable = null;
  22131. }
  22132. this._delayedOnLoad = null;
  22133. this._delayedOnError = null;
  22134. };
  22135. // Statics
  22136. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22137. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22138. if (onLoad === void 0) { onLoad = null; }
  22139. if (onError === void 0) { onError = null; }
  22140. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22141. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22142. };
  22143. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22144. if (parsedTexture.customType) {
  22145. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22146. // Update Sampling Mode
  22147. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22148. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22149. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22150. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22151. }
  22152. }
  22153. return parsedCustomTexture;
  22154. }
  22155. if (parsedTexture.isCube) {
  22156. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22157. }
  22158. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22159. return null;
  22160. }
  22161. var texture = BABYLON.SerializationHelper.Parse(function () {
  22162. if (parsedTexture.mirrorPlane) {
  22163. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22164. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22165. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22166. return mirrorTexture;
  22167. }
  22168. else if (parsedTexture.isRenderTarget) {
  22169. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22170. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22171. return renderTargetTexture;
  22172. }
  22173. else {
  22174. var texture;
  22175. if (parsedTexture.base64String) {
  22176. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22177. }
  22178. else {
  22179. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22180. }
  22181. return texture;
  22182. }
  22183. }, parsedTexture, scene);
  22184. // Update Sampling Mode
  22185. if (parsedTexture.samplingMode) {
  22186. var sampling = parsedTexture.samplingMode;
  22187. if (texture._samplingMode !== sampling) {
  22188. texture.updateSamplingMode(sampling);
  22189. }
  22190. }
  22191. // Animations
  22192. if (parsedTexture.animations) {
  22193. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22194. var parsedAnimation = parsedTexture.animations[animationIndex];
  22195. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22196. }
  22197. }
  22198. return texture;
  22199. };
  22200. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22201. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22202. if (noMipmap === void 0) { noMipmap = false; }
  22203. if (invertY === void 0) { invertY = true; }
  22204. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22205. if (onLoad === void 0) { onLoad = null; }
  22206. if (onError === void 0) { onError = null; }
  22207. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22208. if (name.substr(0, 5) !== "data:") {
  22209. name = "data:" + name;
  22210. }
  22211. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22212. };
  22213. // Constants
  22214. Texture.NEAREST_SAMPLINGMODE = 1;
  22215. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22216. Texture.BILINEAR_SAMPLINGMODE = 2;
  22217. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22218. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22219. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22220. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22221. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22222. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22223. Texture.NEAREST_LINEAR = 7;
  22224. Texture.NEAREST_NEAREST = 8;
  22225. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22226. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22227. Texture.LINEAR_LINEAR = 11;
  22228. Texture.LINEAR_NEAREST = 12;
  22229. Texture.EXPLICIT_MODE = 0;
  22230. Texture.SPHERICAL_MODE = 1;
  22231. Texture.PLANAR_MODE = 2;
  22232. Texture.CUBIC_MODE = 3;
  22233. Texture.PROJECTION_MODE = 4;
  22234. Texture.SKYBOX_MODE = 5;
  22235. Texture.INVCUBIC_MODE = 6;
  22236. Texture.EQUIRECTANGULAR_MODE = 7;
  22237. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22238. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22239. Texture.CLAMP_ADDRESSMODE = 0;
  22240. Texture.WRAP_ADDRESSMODE = 1;
  22241. Texture.MIRROR_ADDRESSMODE = 2;
  22242. __decorate([
  22243. BABYLON.serialize()
  22244. ], Texture.prototype, "url", void 0);
  22245. __decorate([
  22246. BABYLON.serialize()
  22247. ], Texture.prototype, "uOffset", void 0);
  22248. __decorate([
  22249. BABYLON.serialize()
  22250. ], Texture.prototype, "vOffset", void 0);
  22251. __decorate([
  22252. BABYLON.serialize()
  22253. ], Texture.prototype, "uScale", void 0);
  22254. __decorate([
  22255. BABYLON.serialize()
  22256. ], Texture.prototype, "vScale", void 0);
  22257. __decorate([
  22258. BABYLON.serialize()
  22259. ], Texture.prototype, "uAng", void 0);
  22260. __decorate([
  22261. BABYLON.serialize()
  22262. ], Texture.prototype, "vAng", void 0);
  22263. __decorate([
  22264. BABYLON.serialize()
  22265. ], Texture.prototype, "wAng", void 0);
  22266. __decorate([
  22267. BABYLON.serialize()
  22268. ], Texture.prototype, "isBlocking", null);
  22269. return Texture;
  22270. }(BABYLON.BaseTexture));
  22271. BABYLON.Texture = Texture;
  22272. })(BABYLON || (BABYLON = {}));
  22273. //# sourceMappingURL=babylon.texture.js.map
  22274. var BABYLON;
  22275. (function (BABYLON) {
  22276. var _InstancesBatch = /** @class */ (function () {
  22277. function _InstancesBatch() {
  22278. this.mustReturn = false;
  22279. this.visibleInstances = new Array();
  22280. this.renderSelf = new Array();
  22281. }
  22282. return _InstancesBatch;
  22283. }());
  22284. BABYLON._InstancesBatch = _InstancesBatch;
  22285. var Mesh = /** @class */ (function (_super) {
  22286. __extends(Mesh, _super);
  22287. /**
  22288. * @constructor
  22289. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22290. * @param {Scene} scene The scene to add this mesh to.
  22291. * @param {Node} parent The parent of this mesh, if it has one
  22292. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22293. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22294. * When false, achieved by calling a clone(), also passing False.
  22295. * This will make creation of children, recursive.
  22296. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22297. */
  22298. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22299. if (scene === void 0) { scene = null; }
  22300. if (parent === void 0) { parent = null; }
  22301. if (source === void 0) { source = null; }
  22302. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22303. var _this = _super.call(this, name, scene) || this;
  22304. // Events
  22305. /**
  22306. * An event triggered before rendering the mesh
  22307. * @type {BABYLON.Observable}
  22308. */
  22309. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22310. /**
  22311. * An event triggered after rendering the mesh
  22312. * @type {BABYLON.Observable}
  22313. */
  22314. _this.onAfterRenderObservable = new BABYLON.Observable();
  22315. /**
  22316. * An event triggered before drawing the mesh
  22317. * @type {BABYLON.Observable}
  22318. */
  22319. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22320. // Members
  22321. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22322. _this.instances = new Array();
  22323. _this._LODLevels = new Array();
  22324. _this._visibleInstances = {};
  22325. _this._renderIdForInstances = new Array();
  22326. _this._batchCache = new _InstancesBatch();
  22327. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22328. // Use by builder only to know what orientation were the mesh build in.
  22329. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22330. _this.overrideMaterialSideOrientation = null;
  22331. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22332. // Will be used to save a source mesh reference, If any
  22333. _this._source = null;
  22334. scene = _this.getScene();
  22335. if (source) {
  22336. // Source mesh
  22337. _this._source = source;
  22338. // Geometry
  22339. if (source._geometry) {
  22340. source._geometry.applyToMesh(_this);
  22341. }
  22342. // Deep copy
  22343. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22344. // Tags
  22345. if (BABYLON.Tags.HasTags(source)) {
  22346. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22347. }
  22348. _this.metadata = source.metadata;
  22349. // Parent
  22350. _this.parent = source.parent;
  22351. // Pivot
  22352. _this.setPivotMatrix(source.getPivotMatrix());
  22353. _this.id = name + "." + source.id;
  22354. // Material
  22355. _this.material = source.material;
  22356. var index;
  22357. if (!doNotCloneChildren) {
  22358. // Children
  22359. for (index = 0; index < scene.meshes.length; index++) {
  22360. var mesh = scene.meshes[index];
  22361. if (mesh.parent === source) {
  22362. // doNotCloneChildren is always going to be False
  22363. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22364. }
  22365. }
  22366. }
  22367. // Physics clone
  22368. var physicsEngine = _this.getScene().getPhysicsEngine();
  22369. if (clonePhysicsImpostor && physicsEngine) {
  22370. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22371. if (impostor) {
  22372. _this.physicsImpostor = impostor.clone(_this);
  22373. }
  22374. }
  22375. // Particles
  22376. for (index = 0; index < scene.particleSystems.length; index++) {
  22377. var system = scene.particleSystems[index];
  22378. if (system.emitter === source) {
  22379. system.clone(system.name, _this);
  22380. }
  22381. }
  22382. _this.computeWorldMatrix(true);
  22383. }
  22384. // Parent
  22385. if (parent !== null) {
  22386. _this.parent = parent;
  22387. }
  22388. return _this;
  22389. }
  22390. Object.defineProperty(Mesh, "FRONTSIDE", {
  22391. /**
  22392. * Mesh side orientation : usually the external or front surface
  22393. */
  22394. get: function () {
  22395. return Mesh._FRONTSIDE;
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. Object.defineProperty(Mesh, "BACKSIDE", {
  22401. /**
  22402. * Mesh side orientation : usually the internal or back surface
  22403. */
  22404. get: function () {
  22405. return Mesh._BACKSIDE;
  22406. },
  22407. enumerable: true,
  22408. configurable: true
  22409. });
  22410. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22411. /**
  22412. * Mesh side orientation : both internal and external or front and back surfaces
  22413. */
  22414. get: function () {
  22415. return Mesh._DOUBLESIDE;
  22416. },
  22417. enumerable: true,
  22418. configurable: true
  22419. });
  22420. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22421. /**
  22422. * Mesh side orientation : by default, `FRONTSIDE`
  22423. */
  22424. get: function () {
  22425. return Mesh._DEFAULTSIDE;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Mesh, "NO_CAP", {
  22431. /**
  22432. * Mesh cap setting : no cap
  22433. */
  22434. get: function () {
  22435. return Mesh._NO_CAP;
  22436. },
  22437. enumerable: true,
  22438. configurable: true
  22439. });
  22440. Object.defineProperty(Mesh, "CAP_START", {
  22441. /**
  22442. * Mesh cap setting : one cap at the beginning of the mesh
  22443. */
  22444. get: function () {
  22445. return Mesh._CAP_START;
  22446. },
  22447. enumerable: true,
  22448. configurable: true
  22449. });
  22450. Object.defineProperty(Mesh, "CAP_END", {
  22451. /**
  22452. * Mesh cap setting : one cap at the end of the mesh
  22453. */
  22454. get: function () {
  22455. return Mesh._CAP_END;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(Mesh, "CAP_ALL", {
  22461. /**
  22462. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22463. */
  22464. get: function () {
  22465. return Mesh._CAP_ALL;
  22466. },
  22467. enumerable: true,
  22468. configurable: true
  22469. });
  22470. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22471. set: function (callback) {
  22472. if (this._onBeforeDrawObserver) {
  22473. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22474. }
  22475. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22476. },
  22477. enumerable: true,
  22478. configurable: true
  22479. });
  22480. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22481. get: function () {
  22482. return this._morphTargetManager;
  22483. },
  22484. set: function (value) {
  22485. if (this._morphTargetManager === value) {
  22486. return;
  22487. }
  22488. this._morphTargetManager = value;
  22489. this._syncGeometryWithMorphTargetManager();
  22490. },
  22491. enumerable: true,
  22492. configurable: true
  22493. });
  22494. Object.defineProperty(Mesh.prototype, "source", {
  22495. get: function () {
  22496. return this._source;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. // Methods
  22502. /**
  22503. * Returns the string "Mesh".
  22504. */
  22505. Mesh.prototype.getClassName = function () {
  22506. return "Mesh";
  22507. };
  22508. /**
  22509. * Returns a string.
  22510. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22511. */
  22512. Mesh.prototype.toString = function (fullDetails) {
  22513. var ret = _super.prototype.toString.call(this, fullDetails);
  22514. ret += ", n vertices: " + this.getTotalVertices();
  22515. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22516. if (this.animations) {
  22517. for (var i = 0; i < this.animations.length; i++) {
  22518. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22519. }
  22520. }
  22521. if (fullDetails) {
  22522. if (this._geometry) {
  22523. var ib = this.getIndices();
  22524. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22525. if (vb && ib) {
  22526. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22527. }
  22528. }
  22529. else {
  22530. ret += ", flat shading: UNKNOWN";
  22531. }
  22532. }
  22533. return ret;
  22534. };
  22535. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22536. /**
  22537. * True if the mesh has some Levels Of Details (LOD).
  22538. * Returns a boolean.
  22539. */
  22540. get: function () {
  22541. return this._LODLevels.length > 0;
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Mesh.prototype._sortLODLevels = function () {
  22547. this._LODLevels.sort(function (a, b) {
  22548. if (a.distance < b.distance) {
  22549. return 1;
  22550. }
  22551. if (a.distance > b.distance) {
  22552. return -1;
  22553. }
  22554. return 0;
  22555. });
  22556. };
  22557. /**
  22558. * Add a mesh as LOD level triggered at the given distance.
  22559. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22560. * @param {number} distance The distance from the center of the object to show this level
  22561. * @param {Mesh} mesh The mesh to be added as LOD level
  22562. * @return {Mesh} This mesh (for chaining)
  22563. */
  22564. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22565. if (mesh && mesh._masterMesh) {
  22566. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22567. return this;
  22568. }
  22569. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22570. this._LODLevels.push(level);
  22571. if (mesh) {
  22572. mesh._masterMesh = this;
  22573. }
  22574. this._sortLODLevels();
  22575. return this;
  22576. };
  22577. /**
  22578. * Returns the LOD level mesh at the passed distance or null if not found.
  22579. * It is related to the method `addLODLevel(distance, mesh)`.
  22580. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22581. * Returns an object Mesh or `null`.
  22582. */
  22583. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22584. for (var index = 0; index < this._LODLevels.length; index++) {
  22585. var level = this._LODLevels[index];
  22586. if (level.distance === distance) {
  22587. return level.mesh;
  22588. }
  22589. }
  22590. return null;
  22591. };
  22592. /**
  22593. * Remove a mesh from the LOD array
  22594. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22595. * @param {Mesh} mesh The mesh to be removed.
  22596. * @return {Mesh} This mesh (for chaining)
  22597. */
  22598. Mesh.prototype.removeLODLevel = function (mesh) {
  22599. for (var index = 0; index < this._LODLevels.length; index++) {
  22600. if (this._LODLevels[index].mesh === mesh) {
  22601. this._LODLevels.splice(index, 1);
  22602. if (mesh) {
  22603. mesh._masterMesh = null;
  22604. }
  22605. }
  22606. }
  22607. this._sortLODLevels();
  22608. return this;
  22609. };
  22610. /**
  22611. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22612. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22613. */
  22614. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22615. if (!this._LODLevels || this._LODLevels.length === 0) {
  22616. return this;
  22617. }
  22618. var bSphere;
  22619. if (boundingSphere) {
  22620. bSphere = boundingSphere;
  22621. }
  22622. else {
  22623. var boundingInfo = this.getBoundingInfo();
  22624. if (!boundingInfo) {
  22625. return this;
  22626. }
  22627. bSphere = boundingInfo.boundingSphere;
  22628. }
  22629. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22630. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22631. if (this.onLODLevelSelection) {
  22632. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22633. }
  22634. return this;
  22635. }
  22636. for (var index = 0; index < this._LODLevels.length; index++) {
  22637. var level = this._LODLevels[index];
  22638. if (level.distance < distanceToCamera) {
  22639. if (level.mesh) {
  22640. level.mesh._preActivate();
  22641. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22642. }
  22643. if (this.onLODLevelSelection) {
  22644. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22645. }
  22646. return level.mesh;
  22647. }
  22648. }
  22649. if (this.onLODLevelSelection) {
  22650. this.onLODLevelSelection(distanceToCamera, this, this);
  22651. }
  22652. return this;
  22653. };
  22654. Object.defineProperty(Mesh.prototype, "geometry", {
  22655. /**
  22656. * Returns the mesh internal Geometry object.
  22657. */
  22658. get: function () {
  22659. return this._geometry;
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. /**
  22665. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22666. */
  22667. Mesh.prototype.getTotalVertices = function () {
  22668. if (!this._geometry) {
  22669. return 0;
  22670. }
  22671. return this._geometry.getTotalVertices();
  22672. };
  22673. /**
  22674. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22675. * 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.
  22676. * You can force the copy with forceCopy === true
  22677. * Returns null if the mesh has no geometry or no vertex buffer.
  22678. * Possible `kind` values :
  22679. * - BABYLON.VertexBuffer.PositionKind
  22680. * - BABYLON.VertexBuffer.UVKind
  22681. * - BABYLON.VertexBuffer.UV2Kind
  22682. * - BABYLON.VertexBuffer.UV3Kind
  22683. * - BABYLON.VertexBuffer.UV4Kind
  22684. * - BABYLON.VertexBuffer.UV5Kind
  22685. * - BABYLON.VertexBuffer.UV6Kind
  22686. * - BABYLON.VertexBuffer.ColorKind
  22687. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22688. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22689. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22690. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22691. */
  22692. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22693. if (!this._geometry) {
  22694. return null;
  22695. }
  22696. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22697. };
  22698. /**
  22699. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22700. * Returns `null` if the mesh has no geometry.
  22701. * Possible `kind` values :
  22702. * - BABYLON.VertexBuffer.PositionKind
  22703. * - BABYLON.VertexBuffer.UVKind
  22704. * - BABYLON.VertexBuffer.UV2Kind
  22705. * - BABYLON.VertexBuffer.UV3Kind
  22706. * - BABYLON.VertexBuffer.UV4Kind
  22707. * - BABYLON.VertexBuffer.UV5Kind
  22708. * - BABYLON.VertexBuffer.UV6Kind
  22709. * - BABYLON.VertexBuffer.ColorKind
  22710. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22711. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22712. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22713. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22714. */
  22715. Mesh.prototype.getVertexBuffer = function (kind) {
  22716. if (!this._geometry) {
  22717. return null;
  22718. }
  22719. return this._geometry.getVertexBuffer(kind);
  22720. };
  22721. /**
  22722. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22723. * Possible `kind` values :
  22724. * - BABYLON.VertexBuffer.PositionKind
  22725. * - BABYLON.VertexBuffer.UVKind
  22726. * - BABYLON.VertexBuffer.UV2Kind
  22727. * - BABYLON.VertexBuffer.UV3Kind
  22728. * - BABYLON.VertexBuffer.UV4Kind
  22729. * - BABYLON.VertexBuffer.UV5Kind
  22730. * - BABYLON.VertexBuffer.UV6Kind
  22731. * - BABYLON.VertexBuffer.ColorKind
  22732. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22733. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22734. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22735. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22736. */
  22737. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22738. if (!this._geometry) {
  22739. if (this._delayInfo) {
  22740. return this._delayInfo.indexOf(kind) !== -1;
  22741. }
  22742. return false;
  22743. }
  22744. return this._geometry.isVerticesDataPresent(kind);
  22745. };
  22746. /**
  22747. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22748. * Possible `kind` values :
  22749. * - BABYLON.VertexBuffer.PositionKind
  22750. * - BABYLON.VertexBuffer.UVKind
  22751. * - BABYLON.VertexBuffer.UV2Kind
  22752. * - BABYLON.VertexBuffer.UV3Kind
  22753. * - BABYLON.VertexBuffer.UV4Kind
  22754. * - BABYLON.VertexBuffer.UV5Kind
  22755. * - BABYLON.VertexBuffer.UV6Kind
  22756. * - BABYLON.VertexBuffer.ColorKind
  22757. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22758. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22759. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22760. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22761. */
  22762. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22763. if (!this._geometry) {
  22764. if (this._delayInfo) {
  22765. return this._delayInfo.indexOf(kind) !== -1;
  22766. }
  22767. return false;
  22768. }
  22769. return this._geometry.isVertexBufferUpdatable(kind);
  22770. };
  22771. /**
  22772. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22773. * Possible `kind` values :
  22774. * - BABYLON.VertexBuffer.PositionKind
  22775. * - BABYLON.VertexBuffer.UVKind
  22776. * - BABYLON.VertexBuffer.UV2Kind
  22777. * - BABYLON.VertexBuffer.UV3Kind
  22778. * - BABYLON.VertexBuffer.UV4Kind
  22779. * - BABYLON.VertexBuffer.UV5Kind
  22780. * - BABYLON.VertexBuffer.UV6Kind
  22781. * - BABYLON.VertexBuffer.ColorKind
  22782. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22783. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22784. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22785. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22786. */
  22787. Mesh.prototype.getVerticesDataKinds = function () {
  22788. if (!this._geometry) {
  22789. var result = new Array();
  22790. if (this._delayInfo) {
  22791. this._delayInfo.forEach(function (kind, index, array) {
  22792. result.push(kind);
  22793. });
  22794. }
  22795. return result;
  22796. }
  22797. return this._geometry.getVerticesDataKinds();
  22798. };
  22799. /**
  22800. * Returns a positive integer : the total number of indices in this mesh geometry.
  22801. * Returns zero if the mesh has no geometry.
  22802. */
  22803. Mesh.prototype.getTotalIndices = function () {
  22804. if (!this._geometry) {
  22805. return 0;
  22806. }
  22807. return this._geometry.getTotalIndices();
  22808. };
  22809. /**
  22810. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22811. * 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.
  22812. * Returns an empty array if the mesh has no geometry.
  22813. */
  22814. Mesh.prototype.getIndices = function (copyWhenShared) {
  22815. if (!this._geometry) {
  22816. return [];
  22817. }
  22818. return this._geometry.getIndices(copyWhenShared);
  22819. };
  22820. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22821. get: function () {
  22822. return this._masterMesh !== null && this._masterMesh !== undefined;
  22823. },
  22824. enumerable: true,
  22825. configurable: true
  22826. });
  22827. /**
  22828. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22829. */
  22830. Mesh.prototype.isReady = function () {
  22831. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22832. return false;
  22833. }
  22834. return _super.prototype.isReady.call(this);
  22835. };
  22836. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22837. /**
  22838. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22839. * This property is pertinent only for updatable parametric shapes.
  22840. */
  22841. get: function () {
  22842. return this._areNormalsFrozen;
  22843. },
  22844. enumerable: true,
  22845. configurable: true
  22846. });
  22847. /**
  22848. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22849. * It has no effect at all on other shapes.
  22850. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22851. * Returns the Mesh.
  22852. */
  22853. Mesh.prototype.freezeNormals = function () {
  22854. this._areNormalsFrozen = true;
  22855. return this;
  22856. };
  22857. /**
  22858. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22859. * It has no effect at all on other shapes.
  22860. * It reactivates the mesh normals computation if it was previously frozen.
  22861. * Returns the Mesh.
  22862. */
  22863. Mesh.prototype.unfreezeNormals = function () {
  22864. this._areNormalsFrozen = false;
  22865. return this;
  22866. };
  22867. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22868. /**
  22869. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22870. */
  22871. set: function (count) {
  22872. this._overridenInstanceCount = count;
  22873. },
  22874. enumerable: true,
  22875. configurable: true
  22876. });
  22877. // Methods
  22878. Mesh.prototype._preActivate = function () {
  22879. var sceneRenderId = this.getScene().getRenderId();
  22880. if (this._preActivateId === sceneRenderId) {
  22881. return this;
  22882. }
  22883. this._preActivateId = sceneRenderId;
  22884. this._visibleInstances = null;
  22885. return this;
  22886. };
  22887. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22888. if (this._visibleInstances) {
  22889. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22890. }
  22891. return this;
  22892. };
  22893. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22894. if (!this._visibleInstances) {
  22895. this._visibleInstances = {};
  22896. this._visibleInstances.defaultRenderId = renderId;
  22897. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22898. }
  22899. if (!this._visibleInstances[renderId]) {
  22900. this._visibleInstances[renderId] = new Array();
  22901. }
  22902. this._visibleInstances[renderId].push(instance);
  22903. return this;
  22904. };
  22905. /**
  22906. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22907. * This means the mesh underlying bounding box and sphere are recomputed.
  22908. * Returns the Mesh.
  22909. */
  22910. Mesh.prototype.refreshBoundingInfo = function () {
  22911. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22912. return this;
  22913. }
  22914. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22915. if (data) {
  22916. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22917. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22918. }
  22919. if (this.subMeshes) {
  22920. for (var index = 0; index < this.subMeshes.length; index++) {
  22921. this.subMeshes[index].refreshBoundingInfo();
  22922. }
  22923. }
  22924. this._updateBoundingInfo();
  22925. return this;
  22926. };
  22927. Mesh.prototype._createGlobalSubMesh = function (force) {
  22928. var totalVertices = this.getTotalVertices();
  22929. if (!totalVertices || !this.getIndices()) {
  22930. return null;
  22931. }
  22932. // Check if we need to recreate the submeshes
  22933. if (this.subMeshes && this.subMeshes.length > 0) {
  22934. var ib = this.getIndices();
  22935. if (!ib) {
  22936. return null;
  22937. }
  22938. var totalIndices = ib.length;
  22939. var needToRecreate = false;
  22940. if (force) {
  22941. needToRecreate = true;
  22942. }
  22943. else {
  22944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22945. var submesh = _a[_i];
  22946. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22947. needToRecreate = true;
  22948. break;
  22949. }
  22950. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22951. needToRecreate = true;
  22952. break;
  22953. }
  22954. }
  22955. }
  22956. if (!needToRecreate) {
  22957. return this.subMeshes[0];
  22958. }
  22959. }
  22960. this.releaseSubMeshes();
  22961. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22962. };
  22963. Mesh.prototype.subdivide = function (count) {
  22964. if (count < 1) {
  22965. return;
  22966. }
  22967. var totalIndices = this.getTotalIndices();
  22968. var subdivisionSize = (totalIndices / count) | 0;
  22969. var offset = 0;
  22970. // Ensure that subdivisionSize is a multiple of 3
  22971. while (subdivisionSize % 3 !== 0) {
  22972. subdivisionSize++;
  22973. }
  22974. this.releaseSubMeshes();
  22975. for (var index = 0; index < count; index++) {
  22976. if (offset >= totalIndices) {
  22977. break;
  22978. }
  22979. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22980. offset += subdivisionSize;
  22981. }
  22982. this.synchronizeInstances();
  22983. };
  22984. /**
  22985. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22986. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22987. * The `data` are either a numeric array either a Float32Array.
  22988. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22989. * 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).
  22990. * Note that a new underlying VertexBuffer object is created each call.
  22991. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22992. *
  22993. * Possible `kind` values :
  22994. * - BABYLON.VertexBuffer.PositionKind
  22995. * - BABYLON.VertexBuffer.UVKind
  22996. * - BABYLON.VertexBuffer.UV2Kind
  22997. * - BABYLON.VertexBuffer.UV3Kind
  22998. * - BABYLON.VertexBuffer.UV4Kind
  22999. * - BABYLON.VertexBuffer.UV5Kind
  23000. * - BABYLON.VertexBuffer.UV6Kind
  23001. * - BABYLON.VertexBuffer.ColorKind
  23002. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23003. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23004. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23005. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23006. *
  23007. * Returns the Mesh.
  23008. */
  23009. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23010. if (updatable === void 0) { updatable = false; }
  23011. if (!this._geometry) {
  23012. var vertexData = new BABYLON.VertexData();
  23013. vertexData.set(data, kind);
  23014. var scene = this.getScene();
  23015. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23016. }
  23017. else {
  23018. this._geometry.setVerticesData(kind, data, updatable, stride);
  23019. }
  23020. return this;
  23021. };
  23022. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23023. if (updatable === void 0) { updatable = true; }
  23024. var vb = this.getVertexBuffer(kind);
  23025. if (!vb || vb.isUpdatable() === updatable) {
  23026. return;
  23027. }
  23028. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23029. };
  23030. /**
  23031. * Sets the mesh VertexBuffer.
  23032. * Returns the Mesh.
  23033. */
  23034. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23035. if (!this._geometry) {
  23036. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23037. }
  23038. this._geometry.setVerticesBuffer(buffer);
  23039. return this;
  23040. };
  23041. /**
  23042. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23043. * If the mesh has no geometry, it is simply returned as it is.
  23044. * The `data` are either a numeric array either a Float32Array.
  23045. * No new underlying VertexBuffer object is created.
  23046. * 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.
  23047. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23048. *
  23049. * Possible `kind` values :
  23050. * - BABYLON.VertexBuffer.PositionKind
  23051. * - BABYLON.VertexBuffer.UVKind
  23052. * - BABYLON.VertexBuffer.UV2Kind
  23053. * - BABYLON.VertexBuffer.UV3Kind
  23054. * - BABYLON.VertexBuffer.UV4Kind
  23055. * - BABYLON.VertexBuffer.UV5Kind
  23056. * - BABYLON.VertexBuffer.UV6Kind
  23057. * - BABYLON.VertexBuffer.ColorKind
  23058. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23059. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23060. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23061. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23062. *
  23063. * Returns the Mesh.
  23064. */
  23065. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23066. if (!this._geometry) {
  23067. return this;
  23068. }
  23069. if (!makeItUnique) {
  23070. this._geometry.updateVerticesData(kind, data, updateExtends);
  23071. }
  23072. else {
  23073. this.makeGeometryUnique();
  23074. this.updateVerticesData(kind, data, updateExtends, false);
  23075. }
  23076. return this;
  23077. };
  23078. /**
  23079. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23080. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23081. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23082. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23083. * Returns the Mesh.
  23084. */
  23085. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23086. if (computeNormals === void 0) { computeNormals = true; }
  23087. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23088. if (!positions) {
  23089. return this;
  23090. }
  23091. positionFunction(positions);
  23092. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23093. if (computeNormals) {
  23094. var indices = this.getIndices();
  23095. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23096. if (!normals) {
  23097. return this;
  23098. }
  23099. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23100. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23101. }
  23102. return this;
  23103. };
  23104. /**
  23105. * Creates a un-shared specific occurence of the geometry for the mesh.
  23106. * Returns the Mesh.
  23107. */
  23108. Mesh.prototype.makeGeometryUnique = function () {
  23109. if (!this._geometry) {
  23110. return this;
  23111. }
  23112. var oldGeometry = this._geometry;
  23113. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23114. oldGeometry.releaseForMesh(this, true);
  23115. geometry.applyToMesh(this);
  23116. return this;
  23117. };
  23118. /**
  23119. * Sets the mesh indices.
  23120. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23121. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23122. * This method creates a new index buffer each call.
  23123. * Returns the Mesh.
  23124. */
  23125. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23126. if (totalVertices === void 0) { totalVertices = null; }
  23127. if (updatable === void 0) { updatable = false; }
  23128. if (!this._geometry) {
  23129. var vertexData = new BABYLON.VertexData();
  23130. vertexData.indices = indices;
  23131. var scene = this.getScene();
  23132. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23133. }
  23134. else {
  23135. this._geometry.setIndices(indices, totalVertices, updatable);
  23136. }
  23137. return this;
  23138. };
  23139. /**
  23140. * Update the current index buffer
  23141. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23142. * Returns the Mesh.
  23143. */
  23144. Mesh.prototype.updateIndices = function (indices, offset) {
  23145. if (!this._geometry) {
  23146. return this;
  23147. }
  23148. this._geometry.updateIndices(indices, offset);
  23149. return this;
  23150. };
  23151. /**
  23152. * Invert the geometry to move from a right handed system to a left handed one.
  23153. * Returns the Mesh.
  23154. */
  23155. Mesh.prototype.toLeftHanded = function () {
  23156. if (!this._geometry) {
  23157. return this;
  23158. }
  23159. this._geometry.toLeftHanded();
  23160. return this;
  23161. };
  23162. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23163. if (!this._geometry) {
  23164. return this;
  23165. }
  23166. var engine = this.getScene().getEngine();
  23167. // Wireframe
  23168. var indexToBind;
  23169. if (this._unIndexed) {
  23170. indexToBind = null;
  23171. }
  23172. else {
  23173. switch (fillMode) {
  23174. case BABYLON.Material.PointFillMode:
  23175. indexToBind = null;
  23176. break;
  23177. case BABYLON.Material.WireFrameFillMode:
  23178. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23179. break;
  23180. default:
  23181. case BABYLON.Material.TriangleFillMode:
  23182. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23183. break;
  23184. }
  23185. }
  23186. // VBOs
  23187. this._geometry._bind(effect, indexToBind);
  23188. return this;
  23189. };
  23190. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23191. if (alternate === void 0) { alternate = false; }
  23192. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23193. return this;
  23194. }
  23195. this.onBeforeDrawObservable.notifyObservers(this);
  23196. var scene = this.getScene();
  23197. var engine = scene.getEngine();
  23198. // Draw order
  23199. switch (fillMode) {
  23200. case BABYLON.Material.PointFillMode:
  23201. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23202. break;
  23203. case BABYLON.Material.WireFrameFillMode:
  23204. if (this._unIndexed) {
  23205. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23206. }
  23207. else {
  23208. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23209. }
  23210. break;
  23211. default:
  23212. if (this._unIndexed) {
  23213. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23214. }
  23215. else {
  23216. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23217. }
  23218. }
  23219. if (scene._isAlternateRenderingEnabled && !alternate) {
  23220. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23221. if (!effect || !scene.activeCamera) {
  23222. return this;
  23223. }
  23224. scene._switchToAlternateCameraConfiguration(true);
  23225. this._effectiveMaterial.bindView(effect);
  23226. this._effectiveMaterial.bindViewProjection(effect);
  23227. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23228. this._draw(subMesh, fillMode, instancesCount, true);
  23229. engine.setViewport(scene.activeCamera.viewport);
  23230. scene._switchToAlternateCameraConfiguration(false);
  23231. this._effectiveMaterial.bindView(effect);
  23232. this._effectiveMaterial.bindViewProjection(effect);
  23233. }
  23234. return this;
  23235. };
  23236. /**
  23237. * Registers for this mesh a javascript function called just before the rendering process.
  23238. * This function is passed the current mesh.
  23239. * Return the Mesh.
  23240. */
  23241. Mesh.prototype.registerBeforeRender = function (func) {
  23242. this.onBeforeRenderObservable.add(func);
  23243. return this;
  23244. };
  23245. /**
  23246. * Disposes a previously registered javascript function called before the rendering.
  23247. * This function is passed the current mesh.
  23248. * Returns the Mesh.
  23249. */
  23250. Mesh.prototype.unregisterBeforeRender = function (func) {
  23251. this.onBeforeRenderObservable.removeCallback(func);
  23252. return this;
  23253. };
  23254. /**
  23255. * Registers for this mesh a javascript function called just after the rendering is complete.
  23256. * This function is passed the current mesh.
  23257. * Returns the Mesh.
  23258. */
  23259. Mesh.prototype.registerAfterRender = function (func) {
  23260. this.onAfterRenderObservable.add(func);
  23261. return this;
  23262. };
  23263. /**
  23264. * Disposes a previously registered javascript function called after the rendering.
  23265. * This function is passed the current mesh.
  23266. * Return the Mesh.
  23267. */
  23268. Mesh.prototype.unregisterAfterRender = function (func) {
  23269. this.onAfterRenderObservable.removeCallback(func);
  23270. return this;
  23271. };
  23272. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23273. var scene = this.getScene();
  23274. this._batchCache.mustReturn = false;
  23275. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23276. this._batchCache.visibleInstances[subMeshId] = null;
  23277. if (this._visibleInstances) {
  23278. var currentRenderId = scene.getRenderId();
  23279. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23280. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23281. var selfRenderId = this._renderId;
  23282. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23283. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23284. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23285. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23286. }
  23287. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23288. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23289. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23290. this._batchCache.mustReturn = true;
  23291. return this._batchCache;
  23292. }
  23293. if (currentRenderId !== selfRenderId) {
  23294. this._batchCache.renderSelf[subMeshId] = false;
  23295. }
  23296. }
  23297. this._renderIdForInstances[subMeshId] = currentRenderId;
  23298. }
  23299. return this._batchCache;
  23300. };
  23301. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23302. var visibleInstances = batch.visibleInstances[subMesh._id];
  23303. if (!visibleInstances) {
  23304. return this;
  23305. }
  23306. var matricesCount = visibleInstances.length + 1;
  23307. var bufferSize = matricesCount * 16 * 4;
  23308. var currentInstancesBufferSize = this._instancesBufferSize;
  23309. var instancesBuffer = this._instancesBuffer;
  23310. while (this._instancesBufferSize < bufferSize) {
  23311. this._instancesBufferSize *= 2;
  23312. }
  23313. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23314. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23315. }
  23316. var offset = 0;
  23317. var instancesCount = 0;
  23318. var world = this.getWorldMatrix();
  23319. if (batch.renderSelf[subMesh._id]) {
  23320. world.copyToArray(this._instancesData, offset);
  23321. offset += 16;
  23322. instancesCount++;
  23323. }
  23324. if (visibleInstances) {
  23325. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23326. var instance = visibleInstances[instanceIndex];
  23327. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23328. offset += 16;
  23329. instancesCount++;
  23330. }
  23331. }
  23332. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23333. if (instancesBuffer) {
  23334. instancesBuffer.dispose();
  23335. }
  23336. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23337. this._instancesBuffer = instancesBuffer;
  23338. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23339. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23340. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23341. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23342. }
  23343. else {
  23344. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23345. }
  23346. this._bind(subMesh, effect, fillMode);
  23347. this._draw(subMesh, fillMode, instancesCount);
  23348. engine.unbindInstanceAttributes();
  23349. return this;
  23350. };
  23351. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23352. var scene = this.getScene();
  23353. var engine = scene.getEngine();
  23354. if (hardwareInstancedRendering) {
  23355. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23356. }
  23357. else {
  23358. if (batch.renderSelf[subMesh._id]) {
  23359. // Draw
  23360. if (onBeforeDraw) {
  23361. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23362. }
  23363. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23364. }
  23365. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23366. if (visibleInstancesForSubMesh) {
  23367. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23368. var instance = visibleInstancesForSubMesh[instanceIndex];
  23369. // World
  23370. var world = instance.getWorldMatrix();
  23371. if (onBeforeDraw) {
  23372. onBeforeDraw(true, world, effectiveMaterial);
  23373. }
  23374. // Draw
  23375. this._draw(subMesh, fillMode);
  23376. }
  23377. }
  23378. }
  23379. return this;
  23380. };
  23381. /**
  23382. * Triggers the draw call for the mesh.
  23383. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23384. * Returns the Mesh.
  23385. */
  23386. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23387. this.checkOcclusionQuery();
  23388. if (this._isOccluded) {
  23389. return this;
  23390. }
  23391. var scene = this.getScene();
  23392. // Managing instances
  23393. var batch = this._getInstancesRenderList(subMesh._id);
  23394. if (batch.mustReturn) {
  23395. return this;
  23396. }
  23397. // Checking geometry state
  23398. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23399. return this;
  23400. }
  23401. this.onBeforeRenderObservable.notifyObservers(this);
  23402. var engine = scene.getEngine();
  23403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23404. // Material
  23405. var material = subMesh.getMaterial();
  23406. if (!material) {
  23407. return this;
  23408. }
  23409. this._effectiveMaterial = material;
  23410. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23411. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23412. return this;
  23413. }
  23414. }
  23415. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23416. return this;
  23417. }
  23418. // Alpha mode
  23419. if (enableAlphaMode) {
  23420. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23421. }
  23422. // Outline - step 1
  23423. var savedDepthWrite = engine.getDepthWrite();
  23424. if (this.renderOutline) {
  23425. engine.setDepthWrite(false);
  23426. scene.getOutlineRenderer().render(subMesh, batch);
  23427. engine.setDepthWrite(savedDepthWrite);
  23428. }
  23429. var effect;
  23430. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23431. effect = subMesh.effect;
  23432. }
  23433. else {
  23434. effect = this._effectiveMaterial.getEffect();
  23435. }
  23436. if (!effect) {
  23437. return this;
  23438. }
  23439. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23440. if (this._effectiveMaterial.forceDepthWrite) {
  23441. engine.setDepthWrite(true);
  23442. }
  23443. // Bind
  23444. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23445. if (!hardwareInstancedRendering) {
  23446. this._bind(subMesh, effect, fillMode);
  23447. }
  23448. var world = this.getWorldMatrix();
  23449. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23450. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23451. }
  23452. else {
  23453. this._effectiveMaterial.bind(world, this);
  23454. }
  23455. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23456. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23457. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23458. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23459. }
  23460. // Draw
  23461. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23462. // Unbind
  23463. this._effectiveMaterial.unbind();
  23464. // Outline - step 2
  23465. if (this.renderOutline && savedDepthWrite) {
  23466. engine.setDepthWrite(true);
  23467. engine.setColorWrite(false);
  23468. scene.getOutlineRenderer().render(subMesh, batch);
  23469. engine.setColorWrite(true);
  23470. }
  23471. // Overlay
  23472. if (this.renderOverlay) {
  23473. var currentMode = engine.getAlphaMode();
  23474. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23475. scene.getOutlineRenderer().render(subMesh, batch, true);
  23476. engine.setAlphaMode(currentMode);
  23477. }
  23478. this.onAfterRenderObservable.notifyObservers(this);
  23479. return this;
  23480. };
  23481. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23482. if (isInstance) {
  23483. effectiveMaterial.bindOnlyWorldMatrix(world);
  23484. }
  23485. return this;
  23486. };
  23487. /**
  23488. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23489. */
  23490. Mesh.prototype.getEmittedParticleSystems = function () {
  23491. var results = new Array();
  23492. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23493. var particleSystem = this.getScene().particleSystems[index];
  23494. if (particleSystem.emitter === this) {
  23495. results.push(particleSystem);
  23496. }
  23497. }
  23498. return results;
  23499. };
  23500. /**
  23501. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23502. */
  23503. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23504. var results = new Array();
  23505. var descendants = this.getDescendants();
  23506. descendants.push(this);
  23507. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23508. var particleSystem = this.getScene().particleSystems[index];
  23509. var emitter = particleSystem.emitter;
  23510. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23511. results.push(particleSystem);
  23512. }
  23513. }
  23514. return results;
  23515. };
  23516. Mesh.prototype._checkDelayState = function () {
  23517. var scene = this.getScene();
  23518. if (this._geometry) {
  23519. this._geometry.load(scene);
  23520. }
  23521. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23522. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23523. this._queueLoad(this, scene);
  23524. }
  23525. return this;
  23526. };
  23527. Mesh.prototype._queueLoad = function (mesh, scene) {
  23528. var _this = this;
  23529. scene._addPendingData(mesh);
  23530. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23531. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23532. if (data instanceof ArrayBuffer) {
  23533. _this._delayLoadingFunction(data, _this);
  23534. }
  23535. else {
  23536. _this._delayLoadingFunction(JSON.parse(data), _this);
  23537. }
  23538. _this.instances.forEach(function (instance) {
  23539. instance._syncSubMeshes();
  23540. });
  23541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23542. scene._removePendingData(_this);
  23543. }, function () { }, scene.database, getBinaryData);
  23544. return this;
  23545. };
  23546. /**
  23547. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23548. */
  23549. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23550. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23551. return false;
  23552. }
  23553. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23554. return false;
  23555. }
  23556. this._checkDelayState();
  23557. return true;
  23558. };
  23559. /**
  23560. * Sets the mesh material by the material or multiMaterial `id` property.
  23561. * The material `id` is a string identifying the material or the multiMaterial.
  23562. * This method returns the Mesh.
  23563. */
  23564. Mesh.prototype.setMaterialByID = function (id) {
  23565. var materials = this.getScene().materials;
  23566. var index;
  23567. for (index = materials.length - 1; index > -1; index--) {
  23568. if (materials[index].id === id) {
  23569. this.material = materials[index];
  23570. return this;
  23571. }
  23572. }
  23573. // Multi
  23574. var multiMaterials = this.getScene().multiMaterials;
  23575. for (index = multiMaterials.length - 1; index > -1; index--) {
  23576. if (multiMaterials[index].id === id) {
  23577. this.material = multiMaterials[index];
  23578. return this;
  23579. }
  23580. }
  23581. return this;
  23582. };
  23583. /**
  23584. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23585. */
  23586. Mesh.prototype.getAnimatables = function () {
  23587. var results = new Array();
  23588. if (this.material) {
  23589. results.push(this.material);
  23590. }
  23591. if (this.skeleton) {
  23592. results.push(this.skeleton);
  23593. }
  23594. return results;
  23595. };
  23596. /**
  23597. * Modifies the mesh geometry according to the passed transformation matrix.
  23598. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23599. * The mesh normals are modified accordingly the same transformation.
  23600. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23601. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23602. * Returns the Mesh.
  23603. */
  23604. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23605. // Position
  23606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23607. return this;
  23608. }
  23609. var submeshes = this.subMeshes.splice(0);
  23610. this._resetPointsArrayCache();
  23611. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23612. var temp = new Array();
  23613. var index;
  23614. for (index = 0; index < data.length; index += 3) {
  23615. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23616. }
  23617. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23618. // Normals
  23619. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23620. return this;
  23621. }
  23622. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23623. temp = [];
  23624. for (index = 0; index < data.length; index += 3) {
  23625. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23626. }
  23627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23628. // flip faces?
  23629. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23630. this.flipFaces();
  23631. }
  23632. // Restore submeshes
  23633. this.releaseSubMeshes();
  23634. this.subMeshes = submeshes;
  23635. return this;
  23636. };
  23637. /**
  23638. * Modifies the mesh geometry according to its own current World Matrix.
  23639. * The mesh World Matrix is then reset.
  23640. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23641. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23642. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23643. * Returns the Mesh.
  23644. */
  23645. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23646. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23647. this.scaling.copyFromFloats(1, 1, 1);
  23648. this.position.copyFromFloats(0, 0, 0);
  23649. this.rotation.copyFromFloats(0, 0, 0);
  23650. //only if quaternion is already set
  23651. if (this.rotationQuaternion) {
  23652. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23653. }
  23654. this._worldMatrix = BABYLON.Matrix.Identity();
  23655. return this;
  23656. };
  23657. Object.defineProperty(Mesh.prototype, "_positions", {
  23658. // Cache
  23659. get: function () {
  23660. if (this._geometry) {
  23661. return this._geometry._positions;
  23662. }
  23663. return null;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. Mesh.prototype._resetPointsArrayCache = function () {
  23669. if (this._geometry) {
  23670. this._geometry._resetPointsArrayCache();
  23671. }
  23672. return this;
  23673. };
  23674. Mesh.prototype._generatePointsArray = function () {
  23675. if (this._geometry) {
  23676. return this._geometry._generatePointsArray();
  23677. }
  23678. return false;
  23679. };
  23680. /**
  23681. * Returns a new Mesh object generated from the current mesh properties.
  23682. * This method must not get confused with createInstance().
  23683. * The parameter `name` is a string, the name given to the new mesh.
  23684. * The optional parameter `newParent` can be any Node object (default `null`).
  23685. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23686. * 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.
  23687. */
  23688. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23689. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23690. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23691. };
  23692. /**
  23693. * Disposes the mesh.
  23694. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23695. */
  23696. Mesh.prototype.dispose = function (doNotRecurse) {
  23697. var _this = this;
  23698. this.morphTargetManager = null;
  23699. if (this._geometry) {
  23700. this._geometry.releaseForMesh(this, true);
  23701. }
  23702. // Sources
  23703. var meshes = this.getScene().meshes;
  23704. meshes.forEach(function (mesh) {
  23705. if (mesh._source && mesh._source === _this) {
  23706. mesh._source = null;
  23707. }
  23708. });
  23709. this._source = null;
  23710. // Instances
  23711. if (this._instancesBuffer) {
  23712. this._instancesBuffer.dispose();
  23713. this._instancesBuffer = null;
  23714. }
  23715. while (this.instances.length) {
  23716. this.instances[0].dispose();
  23717. }
  23718. // Highlight layers.
  23719. var highlightLayers = this.getScene().highlightLayers;
  23720. for (var i = 0; i < highlightLayers.length; i++) {
  23721. var highlightLayer = highlightLayers[i];
  23722. if (highlightLayer) {
  23723. highlightLayer.removeMesh(this);
  23724. highlightLayer.removeExcludedMesh(this);
  23725. }
  23726. }
  23727. _super.prototype.dispose.call(this, doNotRecurse);
  23728. };
  23729. /**
  23730. * Modifies the mesh geometry according to a displacement map.
  23731. * 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.
  23732. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23733. * This method returns nothing.
  23734. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23735. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23736. * 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.
  23737. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23738. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23739. *
  23740. * Returns the Mesh.
  23741. */
  23742. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23743. var _this = this;
  23744. var scene = this.getScene();
  23745. var onload = function (img) {
  23746. // Getting height map data
  23747. var canvas = document.createElement("canvas");
  23748. var context = canvas.getContext("2d");
  23749. var heightMapWidth = img.width;
  23750. var heightMapHeight = img.height;
  23751. canvas.width = heightMapWidth;
  23752. canvas.height = heightMapHeight;
  23753. context.drawImage(img, 0, 0);
  23754. // Create VertexData from map data
  23755. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23756. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23757. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23758. //execute success callback, if set
  23759. if (onSuccess) {
  23760. onSuccess(_this);
  23761. }
  23762. };
  23763. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23764. return this;
  23765. };
  23766. /**
  23767. * Modifies the mesh geometry according to a displacementMap buffer.
  23768. * 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.
  23769. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23770. * This method returns nothing.
  23771. * 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.
  23772. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23773. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23774. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23775. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23776. *
  23777. * Returns the Mesh.
  23778. */
  23779. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23780. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23781. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23782. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23783. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23784. return this;
  23785. }
  23786. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23787. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23788. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23789. var position = BABYLON.Vector3.Zero();
  23790. var normal = BABYLON.Vector3.Zero();
  23791. var uv = BABYLON.Vector2.Zero();
  23792. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23793. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23794. for (var index = 0; index < positions.length; index += 3) {
  23795. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23796. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23797. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23798. // Compute height
  23799. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23800. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23801. var pos = (u + v * heightMapWidth) * 4;
  23802. var r = buffer[pos] / 255.0;
  23803. var g = buffer[pos + 1] / 255.0;
  23804. var b = buffer[pos + 2] / 255.0;
  23805. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23806. normal.normalize();
  23807. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23808. position = position.add(normal);
  23809. position.toArray(positions, index);
  23810. }
  23811. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23812. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23813. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23814. return this;
  23815. };
  23816. /**
  23817. * Modify the mesh to get a flat shading rendering.
  23818. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23819. * This method returns the Mesh.
  23820. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23821. */
  23822. Mesh.prototype.convertToFlatShadedMesh = function () {
  23823. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23824. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23825. var kinds = this.getVerticesDataKinds();
  23826. var vbs = {};
  23827. var data = {};
  23828. var newdata = {};
  23829. var updatableNormals = false;
  23830. var kindIndex;
  23831. var kind;
  23832. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23833. kind = kinds[kindIndex];
  23834. var vertexBuffer = this.getVertexBuffer(kind);
  23835. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23836. updatableNormals = vertexBuffer.isUpdatable();
  23837. kinds.splice(kindIndex, 1);
  23838. kindIndex--;
  23839. continue;
  23840. }
  23841. vbs[kind] = vertexBuffer;
  23842. data[kind] = vbs[kind].getData();
  23843. newdata[kind] = [];
  23844. }
  23845. // Save previous submeshes
  23846. var previousSubmeshes = this.subMeshes.slice(0);
  23847. var indices = this.getIndices();
  23848. var totalIndices = this.getTotalIndices();
  23849. // Generating unique vertices per face
  23850. var index;
  23851. for (index = 0; index < totalIndices; index++) {
  23852. var vertexIndex = indices[index];
  23853. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23854. kind = kinds[kindIndex];
  23855. var stride = vbs[kind].getStrideSize();
  23856. for (var offset = 0; offset < stride; offset++) {
  23857. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23858. }
  23859. }
  23860. }
  23861. // Updating faces & normal
  23862. var normals = [];
  23863. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23864. for (index = 0; index < totalIndices; index += 3) {
  23865. indices[index] = index;
  23866. indices[index + 1] = index + 1;
  23867. indices[index + 2] = index + 2;
  23868. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23869. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23870. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23871. var p1p2 = p1.subtract(p2);
  23872. var p3p2 = p3.subtract(p2);
  23873. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23874. // Store same normals for every vertex
  23875. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23876. normals.push(normal.x);
  23877. normals.push(normal.y);
  23878. normals.push(normal.z);
  23879. }
  23880. }
  23881. this.setIndices(indices);
  23882. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23883. // Updating vertex buffers
  23884. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23885. kind = kinds[kindIndex];
  23886. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23887. }
  23888. // Updating submeshes
  23889. this.releaseSubMeshes();
  23890. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23891. var previousOne = previousSubmeshes[submeshIndex];
  23892. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23893. }
  23894. this.synchronizeInstances();
  23895. return this;
  23896. };
  23897. /**
  23898. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23899. * In other words, more vertices, no more indices and a single bigger VBO.
  23900. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23901. * Returns the Mesh.
  23902. */
  23903. Mesh.prototype.convertToUnIndexedMesh = function () {
  23904. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23905. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23906. var kinds = this.getVerticesDataKinds();
  23907. var vbs = {};
  23908. var data = {};
  23909. var newdata = {};
  23910. var kindIndex;
  23911. var kind;
  23912. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23913. kind = kinds[kindIndex];
  23914. var vertexBuffer = this.getVertexBuffer(kind);
  23915. vbs[kind] = vertexBuffer;
  23916. data[kind] = vbs[kind].getData();
  23917. newdata[kind] = [];
  23918. }
  23919. // Save previous submeshes
  23920. var previousSubmeshes = this.subMeshes.slice(0);
  23921. var indices = this.getIndices();
  23922. var totalIndices = this.getTotalIndices();
  23923. // Generating unique vertices per face
  23924. var index;
  23925. for (index = 0; index < totalIndices; index++) {
  23926. var vertexIndex = indices[index];
  23927. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23928. kind = kinds[kindIndex];
  23929. var stride = vbs[kind].getStrideSize();
  23930. for (var offset = 0; offset < stride; offset++) {
  23931. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23932. }
  23933. }
  23934. }
  23935. // Updating indices
  23936. for (index = 0; index < totalIndices; index += 3) {
  23937. indices[index] = index;
  23938. indices[index + 1] = index + 1;
  23939. indices[index + 2] = index + 2;
  23940. }
  23941. this.setIndices(indices);
  23942. // Updating vertex buffers
  23943. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23944. kind = kinds[kindIndex];
  23945. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23946. }
  23947. // Updating submeshes
  23948. this.releaseSubMeshes();
  23949. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23950. var previousOne = previousSubmeshes[submeshIndex];
  23951. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23952. }
  23953. this._unIndexed = true;
  23954. this.synchronizeInstances();
  23955. return this;
  23956. };
  23957. /**
  23958. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23959. * This method returns the Mesh.
  23960. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23961. */
  23962. Mesh.prototype.flipFaces = function (flipNormals) {
  23963. if (flipNormals === void 0) { flipNormals = false; }
  23964. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23965. var i;
  23966. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  23967. for (i = 0; i < vertex_data.normals.length; i++) {
  23968. vertex_data.normals[i] *= -1;
  23969. }
  23970. }
  23971. if (vertex_data.indices) {
  23972. var temp;
  23973. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23974. // reassign indices
  23975. temp = vertex_data.indices[i + 1];
  23976. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23977. vertex_data.indices[i + 2] = temp;
  23978. }
  23979. }
  23980. vertex_data.applyToMesh(this);
  23981. return this;
  23982. };
  23983. // Instances
  23984. /**
  23985. * Creates a new InstancedMesh object from the mesh model.
  23986. * An instance shares the same properties and the same material than its model.
  23987. * Only these properties of each instance can then be set individually :
  23988. * - position
  23989. * - rotation
  23990. * - rotationQuaternion
  23991. * - setPivotMatrix
  23992. * - scaling
  23993. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23994. * Warning : this method is not supported for Line mesh and LineSystem
  23995. */
  23996. Mesh.prototype.createInstance = function (name) {
  23997. return new BABYLON.InstancedMesh(name, this);
  23998. };
  23999. /**
  24000. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24001. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24002. * This method returns the Mesh.
  24003. */
  24004. Mesh.prototype.synchronizeInstances = function () {
  24005. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24006. var instance = this.instances[instanceIndex];
  24007. instance._syncSubMeshes();
  24008. }
  24009. return this;
  24010. };
  24011. /**
  24012. * Simplify the mesh according to the given array of settings.
  24013. * Function will return immediately and will simplify async. It returns the Mesh.
  24014. * @param settings a collection of simplification settings.
  24015. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24016. * @param type the type of simplification to run.
  24017. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24018. */
  24019. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24020. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24021. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24022. this.getScene().simplificationQueue.addTask({
  24023. settings: settings,
  24024. parallelProcessing: parallelProcessing,
  24025. mesh: this,
  24026. simplificationType: simplificationType,
  24027. successCallback: successCallback
  24028. });
  24029. return this;
  24030. };
  24031. /**
  24032. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24033. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24034. * This should be used together with the simplification to avoid disappearing triangles.
  24035. * Returns the Mesh.
  24036. * @param successCallback an optional success callback to be called after the optimization finished.
  24037. */
  24038. Mesh.prototype.optimizeIndices = function (successCallback) {
  24039. var _this = this;
  24040. var indices = this.getIndices();
  24041. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24042. if (!positions || !indices) {
  24043. return this;
  24044. }
  24045. var vectorPositions = new Array();
  24046. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24047. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24048. }
  24049. var dupes = new Array();
  24050. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24051. var realPos = vectorPositions.length - 1 - iteration;
  24052. var testedPosition = vectorPositions[realPos];
  24053. for (var j = 0; j < realPos; ++j) {
  24054. var againstPosition = vectorPositions[j];
  24055. if (testedPosition.equals(againstPosition)) {
  24056. dupes[realPos] = j;
  24057. break;
  24058. }
  24059. }
  24060. }, function () {
  24061. for (var i = 0; i < indices.length; ++i) {
  24062. indices[i] = dupes[indices[i]] || indices[i];
  24063. }
  24064. //indices are now reordered
  24065. var originalSubMeshes = _this.subMeshes.slice(0);
  24066. _this.setIndices(indices);
  24067. _this.subMeshes = originalSubMeshes;
  24068. if (successCallback) {
  24069. successCallback(_this);
  24070. }
  24071. });
  24072. return this;
  24073. };
  24074. Mesh.prototype.serialize = function (serializationObject) {
  24075. serializationObject.name = this.name;
  24076. serializationObject.id = this.id;
  24077. serializationObject.type = this.getClassName();
  24078. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24079. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24080. }
  24081. serializationObject.position = this.position.asArray();
  24082. if (this.rotationQuaternion) {
  24083. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24084. }
  24085. else if (this.rotation) {
  24086. serializationObject.rotation = this.rotation.asArray();
  24087. }
  24088. serializationObject.scaling = this.scaling.asArray();
  24089. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24090. serializationObject.isEnabled = this.isEnabled();
  24091. serializationObject.isVisible = this.isVisible;
  24092. serializationObject.infiniteDistance = this.infiniteDistance;
  24093. serializationObject.pickable = this.isPickable;
  24094. serializationObject.receiveShadows = this.receiveShadows;
  24095. serializationObject.billboardMode = this.billboardMode;
  24096. serializationObject.visibility = this.visibility;
  24097. serializationObject.checkCollisions = this.checkCollisions;
  24098. serializationObject.isBlocker = this.isBlocker;
  24099. // Parent
  24100. if (this.parent) {
  24101. serializationObject.parentId = this.parent.id;
  24102. }
  24103. // Geometry
  24104. var geometry = this._geometry;
  24105. if (geometry) {
  24106. var geometryId = geometry.id;
  24107. serializationObject.geometryId = geometryId;
  24108. // SubMeshes
  24109. serializationObject.subMeshes = [];
  24110. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24111. var subMesh = this.subMeshes[subIndex];
  24112. serializationObject.subMeshes.push({
  24113. materialIndex: subMesh.materialIndex,
  24114. verticesStart: subMesh.verticesStart,
  24115. verticesCount: subMesh.verticesCount,
  24116. indexStart: subMesh.indexStart,
  24117. indexCount: subMesh.indexCount
  24118. });
  24119. }
  24120. }
  24121. // Material
  24122. if (this.material) {
  24123. serializationObject.materialId = this.material.id;
  24124. }
  24125. else {
  24126. this.material = null;
  24127. }
  24128. // Morph targets
  24129. if (this.morphTargetManager) {
  24130. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24131. }
  24132. // Skeleton
  24133. if (this.skeleton) {
  24134. serializationObject.skeletonId = this.skeleton.id;
  24135. }
  24136. // Physics
  24137. //TODO implement correct serialization for physics impostors.
  24138. var impostor = this.getPhysicsImpostor();
  24139. if (impostor) {
  24140. serializationObject.physicsMass = impostor.getParam("mass");
  24141. serializationObject.physicsFriction = impostor.getParam("friction");
  24142. serializationObject.physicsRestitution = impostor.getParam("mass");
  24143. serializationObject.physicsImpostor = impostor.type;
  24144. }
  24145. // Metadata
  24146. if (this.metadata) {
  24147. serializationObject.metadata = this.metadata;
  24148. }
  24149. // Instances
  24150. serializationObject.instances = [];
  24151. for (var index = 0; index < this.instances.length; index++) {
  24152. var instance = this.instances[index];
  24153. var serializationInstance = {
  24154. name: instance.name,
  24155. position: instance.position.asArray(),
  24156. scaling: instance.scaling.asArray()
  24157. };
  24158. if (instance.rotationQuaternion) {
  24159. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24160. }
  24161. else if (instance.rotation) {
  24162. serializationInstance.rotation = instance.rotation.asArray();
  24163. }
  24164. serializationObject.instances.push(serializationInstance);
  24165. // Animations
  24166. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24167. serializationInstance.ranges = instance.serializeAnimationRanges();
  24168. }
  24169. //
  24170. // Animations
  24171. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24172. serializationObject.ranges = this.serializeAnimationRanges();
  24173. // Layer mask
  24174. serializationObject.layerMask = this.layerMask;
  24175. // Alpha
  24176. serializationObject.alphaIndex = this.alphaIndex;
  24177. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24178. // Overlay
  24179. serializationObject.overlayAlpha = this.overlayAlpha;
  24180. serializationObject.overlayColor = this.overlayColor.asArray();
  24181. serializationObject.renderOverlay = this.renderOverlay;
  24182. // Fog
  24183. serializationObject.applyFog = this.applyFog;
  24184. // Action Manager
  24185. if (this.actionManager) {
  24186. serializationObject.actions = this.actionManager.serialize(this.name);
  24187. }
  24188. };
  24189. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24190. if (!this.geometry) {
  24191. return;
  24192. }
  24193. this._markSubMeshesAsAttributesDirty();
  24194. var morphTargetManager = this._morphTargetManager;
  24195. if (morphTargetManager && morphTargetManager.vertexCount) {
  24196. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24197. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24198. this.morphTargetManager = null;
  24199. return;
  24200. }
  24201. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24202. var morphTarget = morphTargetManager.getActiveTarget(index);
  24203. var positions = morphTarget.getPositions();
  24204. if (!positions) {
  24205. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24206. return;
  24207. }
  24208. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24209. var normals = morphTarget.getNormals();
  24210. if (normals) {
  24211. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24212. }
  24213. var tangents = morphTarget.getTangents();
  24214. if (tangents) {
  24215. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24216. }
  24217. }
  24218. }
  24219. else {
  24220. var index = 0;
  24221. // Positions
  24222. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24223. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24224. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24225. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24226. }
  24227. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24228. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24229. }
  24230. index++;
  24231. }
  24232. }
  24233. };
  24234. // Statics
  24235. /**
  24236. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24237. * The parameter `parsedMesh` is the mesh to be copied.
  24238. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24239. */
  24240. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24241. var mesh;
  24242. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24243. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24244. }
  24245. else {
  24246. mesh = new Mesh(parsedMesh.name, scene);
  24247. }
  24248. mesh.id = parsedMesh.id;
  24249. if (BABYLON.Tags) {
  24250. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24251. }
  24252. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24253. if (parsedMesh.metadata !== undefined) {
  24254. mesh.metadata = parsedMesh.metadata;
  24255. }
  24256. if (parsedMesh.rotationQuaternion) {
  24257. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24258. }
  24259. else if (parsedMesh.rotation) {
  24260. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24261. }
  24262. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24263. if (parsedMesh.localMatrix) {
  24264. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24265. }
  24266. else if (parsedMesh.pivotMatrix) {
  24267. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24268. }
  24269. mesh.setEnabled(parsedMesh.isEnabled);
  24270. mesh.isVisible = parsedMesh.isVisible;
  24271. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24272. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24273. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24274. if (parsedMesh.applyFog !== undefined) {
  24275. mesh.applyFog = parsedMesh.applyFog;
  24276. }
  24277. if (parsedMesh.pickable !== undefined) {
  24278. mesh.isPickable = parsedMesh.pickable;
  24279. }
  24280. if (parsedMesh.alphaIndex !== undefined) {
  24281. mesh.alphaIndex = parsedMesh.alphaIndex;
  24282. }
  24283. mesh.receiveShadows = parsedMesh.receiveShadows;
  24284. mesh.billboardMode = parsedMesh.billboardMode;
  24285. if (parsedMesh.visibility !== undefined) {
  24286. mesh.visibility = parsedMesh.visibility;
  24287. }
  24288. mesh.checkCollisions = parsedMesh.checkCollisions;
  24289. if (parsedMesh.isBlocker !== undefined) {
  24290. mesh.isBlocker = parsedMesh.isBlocker;
  24291. }
  24292. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24293. // freezeWorldMatrix
  24294. if (parsedMesh.freezeWorldMatrix) {
  24295. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24296. }
  24297. // Parent
  24298. if (parsedMesh.parentId) {
  24299. mesh._waitingParentId = parsedMesh.parentId;
  24300. }
  24301. // Actions
  24302. if (parsedMesh.actions !== undefined) {
  24303. mesh._waitingActions = parsedMesh.actions;
  24304. }
  24305. // Overlay
  24306. if (parsedMesh.overlayAlpha !== undefined) {
  24307. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24308. }
  24309. if (parsedMesh.overlayColor !== undefined) {
  24310. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24311. }
  24312. if (parsedMesh.renderOverlay !== undefined) {
  24313. mesh.renderOverlay = parsedMesh.renderOverlay;
  24314. }
  24315. // Geometry
  24316. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24317. if (parsedMesh.delayLoadingFile) {
  24318. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24319. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24320. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24321. if (parsedMesh._binaryInfo) {
  24322. mesh._binaryInfo = parsedMesh._binaryInfo;
  24323. }
  24324. mesh._delayInfo = [];
  24325. if (parsedMesh.hasUVs) {
  24326. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24327. }
  24328. if (parsedMesh.hasUVs2) {
  24329. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24330. }
  24331. if (parsedMesh.hasUVs3) {
  24332. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24333. }
  24334. if (parsedMesh.hasUVs4) {
  24335. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24336. }
  24337. if (parsedMesh.hasUVs5) {
  24338. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24339. }
  24340. if (parsedMesh.hasUVs6) {
  24341. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24342. }
  24343. if (parsedMesh.hasColors) {
  24344. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24345. }
  24346. if (parsedMesh.hasMatricesIndices) {
  24347. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24348. }
  24349. if (parsedMesh.hasMatricesWeights) {
  24350. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24351. }
  24352. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24353. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24354. mesh._checkDelayState();
  24355. }
  24356. }
  24357. else {
  24358. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24359. }
  24360. // Material
  24361. if (parsedMesh.materialId) {
  24362. mesh.setMaterialByID(parsedMesh.materialId);
  24363. }
  24364. else {
  24365. mesh.material = null;
  24366. }
  24367. // Morph targets
  24368. if (parsedMesh.morphTargetManagerId > -1) {
  24369. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24370. }
  24371. // Skeleton
  24372. if (parsedMesh.skeletonId > -1) {
  24373. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24374. if (parsedMesh.numBoneInfluencers) {
  24375. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24376. }
  24377. }
  24378. // Animations
  24379. if (parsedMesh.animations) {
  24380. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24381. var parsedAnimation = parsedMesh.animations[animationIndex];
  24382. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24383. }
  24384. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24385. }
  24386. if (parsedMesh.autoAnimate) {
  24387. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24388. }
  24389. // Layer Mask
  24390. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24391. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24392. }
  24393. else {
  24394. mesh.layerMask = 0x0FFFFFFF;
  24395. }
  24396. // Physics
  24397. if (parsedMesh.physicsImpostor) {
  24398. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24399. mass: parsedMesh.physicsMass,
  24400. friction: parsedMesh.physicsFriction,
  24401. restitution: parsedMesh.physicsRestitution
  24402. }, scene);
  24403. }
  24404. // Instances
  24405. if (parsedMesh.instances) {
  24406. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24407. var parsedInstance = parsedMesh.instances[index];
  24408. var instance = mesh.createInstance(parsedInstance.name);
  24409. if (BABYLON.Tags) {
  24410. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24411. }
  24412. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24413. if (parsedInstance.parentId) {
  24414. instance._waitingParentId = parsedInstance.parentId;
  24415. }
  24416. if (parsedInstance.rotationQuaternion) {
  24417. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24418. }
  24419. else if (parsedInstance.rotation) {
  24420. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24421. }
  24422. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24423. instance.checkCollisions = mesh.checkCollisions;
  24424. if (parsedMesh.animations) {
  24425. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24426. parsedAnimation = parsedMesh.animations[animationIndex];
  24427. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24428. }
  24429. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24430. }
  24431. }
  24432. }
  24433. return mesh;
  24434. };
  24435. /**
  24436. * Creates a ribbon mesh.
  24437. * Please consider using the same method from the MeshBuilder class instead.
  24438. * 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.
  24439. *
  24440. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24441. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24442. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24443. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24444. * 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.
  24445. * 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.
  24446. * 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
  24447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24450. */
  24451. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24452. if (closeArray === void 0) { closeArray = false; }
  24453. if (updatable === void 0) { updatable = false; }
  24454. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24455. pathArray: pathArray,
  24456. closeArray: closeArray,
  24457. closePath: closePath,
  24458. offset: offset,
  24459. updatable: updatable,
  24460. sideOrientation: sideOrientation,
  24461. instance: instance
  24462. }, scene);
  24463. };
  24464. /**
  24465. * Creates a plane polygonal mesh. By default, this is a disc.
  24466. * Please consider using the same method from the MeshBuilder class instead.
  24467. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24468. * 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.
  24469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24472. */
  24473. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24474. if (scene === void 0) { scene = null; }
  24475. var options = {
  24476. radius: radius,
  24477. tessellation: tessellation,
  24478. sideOrientation: sideOrientation,
  24479. updatable: updatable
  24480. };
  24481. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24482. };
  24483. /**
  24484. * Creates a box mesh.
  24485. * Please consider using the same method from the MeshBuilder class instead.
  24486. * The parameter `size` sets the size (float) of each box side (default 1).
  24487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24490. */
  24491. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24492. if (scene === void 0) { scene = null; }
  24493. var options = {
  24494. size: size,
  24495. sideOrientation: sideOrientation,
  24496. updatable: updatable
  24497. };
  24498. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24499. };
  24500. /**
  24501. * Creates a sphere mesh.
  24502. * Please consider using the same method from the MeshBuilder class instead.
  24503. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24504. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24508. */
  24509. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24510. var options = {
  24511. segments: segments,
  24512. diameterX: diameter,
  24513. diameterY: diameter,
  24514. diameterZ: diameter,
  24515. sideOrientation: sideOrientation,
  24516. updatable: updatable
  24517. };
  24518. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24519. };
  24520. /**
  24521. * Creates a cylinder or a cone mesh.
  24522. * Please consider using the same method from the MeshBuilder class instead.
  24523. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24524. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24525. * 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.
  24526. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24527. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24528. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24529. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24531. */
  24532. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24533. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24534. if (scene !== undefined) {
  24535. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24536. updatable = scene;
  24537. }
  24538. scene = subdivisions;
  24539. subdivisions = 1;
  24540. }
  24541. var options = {
  24542. height: height,
  24543. diameterTop: diameterTop,
  24544. diameterBottom: diameterBottom,
  24545. tessellation: tessellation,
  24546. subdivisions: subdivisions,
  24547. sideOrientation: sideOrientation,
  24548. updatable: updatable
  24549. };
  24550. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24551. };
  24552. // Torus (Code from SharpDX.org)
  24553. /**
  24554. * Creates a torus mesh.
  24555. * Please consider using the same method from the MeshBuilder class instead.
  24556. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24557. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24558. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24562. */
  24563. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24564. var options = {
  24565. diameter: diameter,
  24566. thickness: thickness,
  24567. tessellation: tessellation,
  24568. sideOrientation: sideOrientation,
  24569. updatable: updatable
  24570. };
  24571. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24572. };
  24573. /**
  24574. * Creates a torus knot mesh.
  24575. * Please consider using the same method from the MeshBuilder class instead.
  24576. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24577. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24578. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24579. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24581. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24583. */
  24584. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24585. var options = {
  24586. radius: radius,
  24587. tube: tube,
  24588. radialSegments: radialSegments,
  24589. tubularSegments: tubularSegments,
  24590. p: p,
  24591. q: q,
  24592. sideOrientation: sideOrientation,
  24593. updatable: updatable
  24594. };
  24595. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24596. };
  24597. /**
  24598. * Creates a line mesh.
  24599. * Please consider using the same method from the MeshBuilder class instead.
  24600. * 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.
  24601. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24602. * The parameter `points` is an array successive Vector3.
  24603. * 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
  24604. * When updating an instance, remember that only point positions can change, not the number of points.
  24605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24606. */
  24607. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24608. if (scene === void 0) { scene = null; }
  24609. if (updatable === void 0) { updatable = false; }
  24610. if (instance === void 0) { instance = null; }
  24611. var options = {
  24612. points: points,
  24613. updatable: updatable,
  24614. instance: instance
  24615. };
  24616. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24617. };
  24618. /**
  24619. * Creates a dashed line mesh.
  24620. * Please consider using the same method from the MeshBuilder class instead.
  24621. * 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.
  24622. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24623. * The parameter `points` is an array successive Vector3.
  24624. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24625. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24626. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24627. * 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
  24628. * When updating an instance, remember that only point positions can change, not the number of points.
  24629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24630. */
  24631. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24632. if (scene === void 0) { scene = null; }
  24633. var options = {
  24634. points: points,
  24635. dashSize: dashSize,
  24636. gapSize: gapSize,
  24637. dashNb: dashNb,
  24638. updatable: updatable,
  24639. instance: instance
  24640. };
  24641. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24642. };
  24643. /**
  24644. * Creates a polygon mesh.
  24645. * Please consider using the same method from the MeshBuilder class instead.
  24646. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24647. * 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.
  24648. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24650. * Remember you can only change the shape positions, not their number when updating a polygon.
  24651. */
  24652. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24653. var options = {
  24654. shape: shape,
  24655. holes: holes,
  24656. updatable: updatable,
  24657. sideOrientation: sideOrientation
  24658. };
  24659. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24660. };
  24661. /**
  24662. * Creates an extruded polygon mesh, with depth in the Y direction.
  24663. * Please consider using the same method from the MeshBuilder class instead.
  24664. */
  24665. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24666. var options = {
  24667. shape: shape,
  24668. holes: holes,
  24669. depth: depth,
  24670. updatable: updatable,
  24671. sideOrientation: sideOrientation
  24672. };
  24673. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24674. };
  24675. /**
  24676. * Creates an extruded shape mesh.
  24677. * 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.
  24678. * Please consider using the same method from the MeshBuilder class instead.
  24679. *
  24680. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24681. * 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
  24682. * extruded along the Z axis.
  24683. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24684. * 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.
  24685. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24686. * 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
  24687. * 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
  24688. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24690. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24692. */
  24693. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24694. if (scene === void 0) { scene = null; }
  24695. var options = {
  24696. shape: shape,
  24697. path: path,
  24698. scale: scale,
  24699. rotation: rotation,
  24700. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24701. sideOrientation: sideOrientation,
  24702. instance: instance,
  24703. updatable: updatable
  24704. };
  24705. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24706. };
  24707. /**
  24708. * Creates an custom extruded shape mesh.
  24709. * 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.
  24710. * Please consider using the same method from the MeshBuilder class instead.
  24711. *
  24712. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24713. * 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
  24714. * extruded along the Z axis.
  24715. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24716. * 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
  24717. * and the distance of this point from the begining of the path :
  24718. * ```javascript
  24719. * var rotationFunction = function(i, distance) {
  24720. * // do things
  24721. * return rotationValue; }
  24722. * ```
  24723. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24724. * 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
  24725. * and the distance of this point from the begining of the path :
  24726. * ```javascript
  24727. * var scaleFunction = function(i, distance) {
  24728. * // do things
  24729. * return scaleValue;}
  24730. * ```
  24731. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24732. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24733. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24734. * 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
  24735. * 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
  24736. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24740. */
  24741. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24742. var options = {
  24743. shape: shape,
  24744. path: path,
  24745. scaleFunction: scaleFunction,
  24746. rotationFunction: rotationFunction,
  24747. ribbonCloseArray: ribbonCloseArray,
  24748. ribbonClosePath: ribbonClosePath,
  24749. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24750. sideOrientation: sideOrientation,
  24751. instance: instance,
  24752. updatable: updatable
  24753. };
  24754. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24755. };
  24756. /**
  24757. * Creates lathe mesh.
  24758. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24759. * Please consider using the same method from the MeshBuilder class instead.
  24760. * 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
  24761. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24762. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24763. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24765. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24767. */
  24768. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24769. var options = {
  24770. shape: shape,
  24771. radius: radius,
  24772. tessellation: tessellation,
  24773. sideOrientation: sideOrientation,
  24774. updatable: updatable
  24775. };
  24776. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24777. };
  24778. /**
  24779. * Creates a plane mesh.
  24780. * Please consider using the same method from the MeshBuilder class instead.
  24781. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24785. */
  24786. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24787. var options = {
  24788. size: size,
  24789. width: size,
  24790. height: size,
  24791. sideOrientation: sideOrientation,
  24792. updatable: updatable
  24793. };
  24794. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24795. };
  24796. /**
  24797. * Creates a ground mesh.
  24798. * Please consider using the same method from the MeshBuilder class instead.
  24799. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24800. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24802. */
  24803. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24804. var options = {
  24805. width: width,
  24806. height: height,
  24807. subdivisions: subdivisions,
  24808. updatable: updatable
  24809. };
  24810. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24811. };
  24812. /**
  24813. * Creates a tiled ground mesh.
  24814. * Please consider using the same method from the MeshBuilder class instead.
  24815. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24816. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24817. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24818. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24819. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24820. * numbers of subdivisions on the ground width and height of each tile.
  24821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24822. */
  24823. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24824. var options = {
  24825. xmin: xmin,
  24826. zmin: zmin,
  24827. xmax: xmax,
  24828. zmax: zmax,
  24829. subdivisions: subdivisions,
  24830. precision: precision,
  24831. updatable: updatable
  24832. };
  24833. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24834. };
  24835. /**
  24836. * Creates a ground mesh from a height map.
  24837. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24838. * Please consider using the same method from the MeshBuilder class instead.
  24839. * The parameter `url` sets the URL of the height map image resource.
  24840. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24841. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24842. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24843. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24844. * 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).
  24845. * This function is passed the newly built mesh :
  24846. * ```javascript
  24847. * function(mesh) { // do things
  24848. * return; }
  24849. * ```
  24850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24851. */
  24852. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24853. var options = {
  24854. width: width,
  24855. height: height,
  24856. subdivisions: subdivisions,
  24857. minHeight: minHeight,
  24858. maxHeight: maxHeight,
  24859. updatable: updatable,
  24860. onReady: onReady
  24861. };
  24862. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24863. };
  24864. /**
  24865. * Creates a tube mesh.
  24866. * 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.
  24867. * Please consider using the same method from the MeshBuilder class instead.
  24868. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24869. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24870. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24871. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24872. * 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.
  24873. * It must return a radius value (positive float) :
  24874. * ```javascript
  24875. * var radiusFunction = function(i, distance) {
  24876. * // do things
  24877. * return radius; }
  24878. * ```
  24879. * 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
  24880. * 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
  24881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24884. */
  24885. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24886. var options = {
  24887. path: path,
  24888. radius: radius,
  24889. tessellation: tessellation,
  24890. radiusFunction: radiusFunction,
  24891. arc: 1,
  24892. cap: cap,
  24893. updatable: updatable,
  24894. sideOrientation: sideOrientation,
  24895. instance: instance
  24896. };
  24897. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24898. };
  24899. /**
  24900. * Creates a polyhedron mesh.
  24901. * Please consider using the same method from the MeshBuilder class instead.
  24902. * 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
  24903. * to choose the wanted type.
  24904. * The parameter `size` (positive float, default 1) sets the polygon size.
  24905. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24906. * 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`.
  24907. * 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
  24908. * 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)`).
  24909. * 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
  24910. * 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.
  24911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24912. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24914. */
  24915. Mesh.CreatePolyhedron = function (name, options, scene) {
  24916. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24917. };
  24918. /**
  24919. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24920. * Please consider using the same method from the MeshBuilder class instead.
  24921. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24922. * 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`).
  24923. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24924. * 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.
  24925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24928. */
  24929. Mesh.CreateIcoSphere = function (name, options, scene) {
  24930. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24931. };
  24932. /**
  24933. * Creates a decal mesh.
  24934. * Please consider using the same method from the MeshBuilder class instead.
  24935. * 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.
  24936. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24937. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24938. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24939. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24940. */
  24941. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24942. var options = {
  24943. position: position,
  24944. normal: normal,
  24945. size: size,
  24946. angle: angle
  24947. };
  24948. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24949. };
  24950. // Skeletons
  24951. /**
  24952. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24953. */
  24954. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24955. if (!this._sourcePositions) {
  24956. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24957. if (!source) {
  24958. return this._sourcePositions;
  24959. }
  24960. this._sourcePositions = new Float32Array(source);
  24961. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  24962. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24963. }
  24964. }
  24965. return this._sourcePositions;
  24966. };
  24967. /**
  24968. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24969. */
  24970. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24971. if (!this._sourceNormals) {
  24972. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24973. if (!source) {
  24974. return this._sourceNormals;
  24975. }
  24976. this._sourceNormals = new Float32Array(source);
  24977. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  24978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24979. }
  24980. }
  24981. return this._sourceNormals;
  24982. };
  24983. /**
  24984. * Updates the vertex buffer by applying transformation from the bones.
  24985. * Returns the Mesh.
  24986. *
  24987. * @param {skeleton} skeleton to apply
  24988. */
  24989. Mesh.prototype.applySkeleton = function (skeleton) {
  24990. if (!this.geometry) {
  24991. return this;
  24992. }
  24993. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24994. return this;
  24995. }
  24996. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24997. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24998. return this;
  24999. }
  25000. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25001. return this;
  25002. }
  25003. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25004. return this;
  25005. }
  25006. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25007. return this;
  25008. }
  25009. if (!this._sourcePositions) {
  25010. var submeshes = this.subMeshes.slice();
  25011. this.setPositionsForCPUSkinning();
  25012. this.subMeshes = submeshes;
  25013. }
  25014. if (!this._sourceNormals) {
  25015. this.setNormalsForCPUSkinning();
  25016. }
  25017. // positionsData checks for not being Float32Array will only pass at most once
  25018. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25019. if (!positionsData) {
  25020. return this;
  25021. }
  25022. if (!(positionsData instanceof Float32Array)) {
  25023. positionsData = new Float32Array(positionsData);
  25024. }
  25025. // normalsData checks for not being Float32Array will only pass at most once
  25026. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25027. if (!normalsData) {
  25028. return this;
  25029. }
  25030. if (!(normalsData instanceof Float32Array)) {
  25031. normalsData = new Float32Array(normalsData);
  25032. }
  25033. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25034. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25035. if (!matricesWeightsData || !matricesIndicesData) {
  25036. return this;
  25037. }
  25038. var needExtras = this.numBoneInfluencers > 4;
  25039. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25040. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25041. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25042. return this;
  25043. }
  25044. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25045. var tempVector3 = BABYLON.Vector3.Zero();
  25046. var finalMatrix = new BABYLON.Matrix();
  25047. var tempMatrix = new BABYLON.Matrix();
  25048. var matWeightIdx = 0;
  25049. var inf;
  25050. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25051. var weight;
  25052. for (inf = 0; inf < 4; inf++) {
  25053. weight = matricesWeightsData[matWeightIdx + inf];
  25054. if (weight > 0) {
  25055. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25056. finalMatrix.addToSelf(tempMatrix);
  25057. }
  25058. else
  25059. break;
  25060. }
  25061. if (needExtras) {
  25062. for (inf = 0; inf < 4; inf++) {
  25063. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25064. if (weight > 0) {
  25065. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25066. finalMatrix.addToSelf(tempMatrix);
  25067. }
  25068. else
  25069. break;
  25070. }
  25071. }
  25072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25073. tempVector3.toArray(positionsData, index);
  25074. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25075. tempVector3.toArray(normalsData, index);
  25076. finalMatrix.reset();
  25077. }
  25078. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25079. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25080. return this;
  25081. };
  25082. // Tools
  25083. /**
  25084. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25085. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25086. */
  25087. Mesh.MinMax = function (meshes) {
  25088. var minVector = null;
  25089. var maxVector = null;
  25090. meshes.forEach(function (mesh, index, array) {
  25091. var boundingInfo = mesh.getBoundingInfo();
  25092. if (!boundingInfo) {
  25093. return;
  25094. }
  25095. var boundingBox = boundingInfo.boundingBox;
  25096. if (!minVector || !maxVector) {
  25097. minVector = boundingBox.minimumWorld;
  25098. maxVector = boundingBox.maximumWorld;
  25099. }
  25100. else {
  25101. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25102. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25103. }
  25104. });
  25105. if (!minVector || !maxVector) {
  25106. return {
  25107. min: BABYLON.Vector3.Zero(),
  25108. max: BABYLON.Vector3.Zero()
  25109. };
  25110. }
  25111. return {
  25112. min: minVector,
  25113. max: maxVector
  25114. };
  25115. };
  25116. /**
  25117. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25118. */
  25119. Mesh.Center = function (meshesOrMinMaxVector) {
  25120. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25121. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25122. };
  25123. /**
  25124. * Merge the array of meshes into a single mesh for performance reasons.
  25125. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25126. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25127. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25128. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25129. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25130. */
  25131. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25132. if (disposeSource === void 0) { disposeSource = true; }
  25133. var index;
  25134. if (!allow32BitsIndices) {
  25135. var totalVertices = 0;
  25136. // Counting vertices
  25137. for (index = 0; index < meshes.length; index++) {
  25138. if (meshes[index]) {
  25139. totalVertices += meshes[index].getTotalVertices();
  25140. if (totalVertices > 65536) {
  25141. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25142. return null;
  25143. }
  25144. }
  25145. }
  25146. }
  25147. // Merge
  25148. var vertexData = null;
  25149. var otherVertexData;
  25150. var indiceArray = new Array();
  25151. var source = null;
  25152. for (index = 0; index < meshes.length; index++) {
  25153. if (meshes[index]) {
  25154. meshes[index].computeWorldMatrix(true);
  25155. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25156. otherVertexData.transform(meshes[index].getWorldMatrix());
  25157. if (vertexData) {
  25158. vertexData.merge(otherVertexData);
  25159. }
  25160. else {
  25161. vertexData = otherVertexData;
  25162. source = meshes[index];
  25163. }
  25164. if (subdivideWithSubMeshes) {
  25165. indiceArray.push(meshes[index].getTotalIndices());
  25166. }
  25167. }
  25168. }
  25169. source = source;
  25170. if (!meshSubclass) {
  25171. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25172. }
  25173. vertexData.applyToMesh(meshSubclass);
  25174. // Setting properties
  25175. meshSubclass.material = source.material;
  25176. meshSubclass.checkCollisions = source.checkCollisions;
  25177. // Cleaning
  25178. if (disposeSource) {
  25179. for (index = 0; index < meshes.length; index++) {
  25180. if (meshes[index]) {
  25181. meshes[index].dispose();
  25182. }
  25183. }
  25184. }
  25185. // Subdivide
  25186. if (subdivideWithSubMeshes) {
  25187. //-- Suppresions du submesh global
  25188. meshSubclass.releaseSubMeshes();
  25189. index = 0;
  25190. var offset = 0;
  25191. //-- aplique la subdivision en fonction du tableau d'indices
  25192. while (index < indiceArray.length) {
  25193. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25194. offset += indiceArray[index];
  25195. index++;
  25196. }
  25197. }
  25198. return meshSubclass;
  25199. };
  25200. // Consts
  25201. Mesh._FRONTSIDE = 0;
  25202. Mesh._BACKSIDE = 1;
  25203. Mesh._DOUBLESIDE = 2;
  25204. Mesh._DEFAULTSIDE = 0;
  25205. Mesh._NO_CAP = 0;
  25206. Mesh._CAP_START = 1;
  25207. Mesh._CAP_END = 2;
  25208. Mesh._CAP_ALL = 3;
  25209. return Mesh;
  25210. }(BABYLON.AbstractMesh));
  25211. BABYLON.Mesh = Mesh;
  25212. })(BABYLON || (BABYLON = {}));
  25213. //# sourceMappingURL=babylon.mesh.js.map
  25214. var BABYLON;
  25215. (function (BABYLON) {
  25216. var BaseSubMesh = /** @class */ (function () {
  25217. function BaseSubMesh() {
  25218. }
  25219. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25220. get: function () {
  25221. return this._materialEffect;
  25222. },
  25223. enumerable: true,
  25224. configurable: true
  25225. });
  25226. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25227. if (defines === void 0) { defines = null; }
  25228. if (this._materialEffect === effect) {
  25229. if (!effect) {
  25230. this._materialDefines = null;
  25231. }
  25232. return;
  25233. }
  25234. this._materialDefines = defines;
  25235. this._materialEffect = effect;
  25236. };
  25237. return BaseSubMesh;
  25238. }());
  25239. BABYLON.BaseSubMesh = BaseSubMesh;
  25240. var SubMesh = /** @class */ (function (_super) {
  25241. __extends(SubMesh, _super);
  25242. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25243. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25244. var _this = _super.call(this) || this;
  25245. _this.materialIndex = materialIndex;
  25246. _this.verticesStart = verticesStart;
  25247. _this.verticesCount = verticesCount;
  25248. _this.indexStart = indexStart;
  25249. _this.indexCount = indexCount;
  25250. _this._renderId = 0;
  25251. _this._mesh = mesh;
  25252. _this._renderingMesh = renderingMesh || mesh;
  25253. mesh.subMeshes.push(_this);
  25254. _this._trianglePlanes = [];
  25255. _this._id = mesh.subMeshes.length - 1;
  25256. if (createBoundingBox) {
  25257. _this.refreshBoundingInfo();
  25258. mesh.computeWorldMatrix(true);
  25259. }
  25260. return _this;
  25261. }
  25262. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25263. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25264. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25265. };
  25266. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25267. get: function () {
  25268. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. /**
  25274. * Returns the submesh BoudingInfo object.
  25275. */
  25276. SubMesh.prototype.getBoundingInfo = function () {
  25277. if (this.IsGlobal) {
  25278. return this._mesh.getBoundingInfo();
  25279. }
  25280. return this._boundingInfo;
  25281. };
  25282. /**
  25283. * Sets the submesh BoundingInfo.
  25284. * Return the SubMesh.
  25285. */
  25286. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25287. this._boundingInfo = boundingInfo;
  25288. return this;
  25289. };
  25290. /**
  25291. * Returns the mesh of the current submesh.
  25292. */
  25293. SubMesh.prototype.getMesh = function () {
  25294. return this._mesh;
  25295. };
  25296. /**
  25297. * Returns the rendering mesh of the submesh.
  25298. */
  25299. SubMesh.prototype.getRenderingMesh = function () {
  25300. return this._renderingMesh;
  25301. };
  25302. /**
  25303. * Returns the submesh material.
  25304. */
  25305. SubMesh.prototype.getMaterial = function () {
  25306. var rootMaterial = this._renderingMesh.material;
  25307. if (rootMaterial && rootMaterial.getSubMaterial) {
  25308. var multiMaterial = rootMaterial;
  25309. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25310. if (this._currentMaterial !== effectiveMaterial) {
  25311. this._currentMaterial = effectiveMaterial;
  25312. this._materialDefines = null;
  25313. }
  25314. return effectiveMaterial;
  25315. }
  25316. if (!rootMaterial) {
  25317. return this._mesh.getScene().defaultMaterial;
  25318. }
  25319. return rootMaterial;
  25320. };
  25321. // Methods
  25322. /**
  25323. * Sets a new updated BoundingInfo object to the submesh.
  25324. * Returns the SubMesh.
  25325. */
  25326. SubMesh.prototype.refreshBoundingInfo = function () {
  25327. this._lastColliderWorldVertices = null;
  25328. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25329. return this;
  25330. }
  25331. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25332. if (!data) {
  25333. this._boundingInfo = this._mesh._boundingInfo;
  25334. return this;
  25335. }
  25336. var indices = this._renderingMesh.getIndices();
  25337. var extend;
  25338. //is this the only submesh?
  25339. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25340. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25341. if (!boundingInfo) {
  25342. return this;
  25343. }
  25344. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25345. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25346. }
  25347. else {
  25348. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25349. }
  25350. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25351. return this;
  25352. };
  25353. SubMesh.prototype._checkCollision = function (collider) {
  25354. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25355. if (!boundingInfo) {
  25356. return false;
  25357. }
  25358. return boundingInfo._checkCollision(collider);
  25359. };
  25360. /**
  25361. * Updates the submesh BoundingInfo.
  25362. * Returns the Submesh.
  25363. */
  25364. SubMesh.prototype.updateBoundingInfo = function (world) {
  25365. var boundingInfo = this.getBoundingInfo();
  25366. if (!boundingInfo) {
  25367. this.refreshBoundingInfo();
  25368. }
  25369. boundingInfo.update(world);
  25370. return this;
  25371. };
  25372. /**
  25373. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25374. * Boolean returned.
  25375. */
  25376. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25377. var boundingInfo = this.getBoundingInfo();
  25378. if (!boundingInfo) {
  25379. return false;
  25380. }
  25381. return boundingInfo.isInFrustum(frustumPlanes);
  25382. };
  25383. /**
  25384. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25385. * Boolean returned.
  25386. */
  25387. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25388. var boundingInfo = this.getBoundingInfo();
  25389. if (!boundingInfo) {
  25390. return false;
  25391. }
  25392. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25393. };
  25394. /**
  25395. * Renders the submesh.
  25396. * Returns it.
  25397. */
  25398. SubMesh.prototype.render = function (enableAlphaMode) {
  25399. this._renderingMesh.render(this, enableAlphaMode);
  25400. return this;
  25401. };
  25402. /**
  25403. * Returns a new Index Buffer.
  25404. * Type returned : WebGLBuffer.
  25405. */
  25406. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25407. if (!this._linesIndexBuffer) {
  25408. var linesIndices = [];
  25409. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25410. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25411. }
  25412. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25413. this.linesIndexCount = linesIndices.length;
  25414. }
  25415. return this._linesIndexBuffer;
  25416. };
  25417. /**
  25418. * True is the passed Ray intersects the submesh bounding box.
  25419. * Boolean returned.
  25420. */
  25421. SubMesh.prototype.canIntersects = function (ray) {
  25422. var boundingInfo = this.getBoundingInfo();
  25423. if (!boundingInfo) {
  25424. return false;
  25425. }
  25426. return ray.intersectsBox(boundingInfo.boundingBox);
  25427. };
  25428. /**
  25429. * Returns an object IntersectionInfo.
  25430. */
  25431. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25432. var intersectInfo = null;
  25433. // LineMesh first as it's also a Mesh...
  25434. if (this._mesh instanceof BABYLON.LinesMesh) {
  25435. var lineMesh = this._mesh;
  25436. // Line test
  25437. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25438. var p0 = positions[indices[index]];
  25439. var p1 = positions[indices[index + 1]];
  25440. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25441. if (length < 0) {
  25442. continue;
  25443. }
  25444. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25445. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25446. if (fastCheck) {
  25447. break;
  25448. }
  25449. }
  25450. }
  25451. }
  25452. else {
  25453. // Triangles test
  25454. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25455. var p0 = positions[indices[index]];
  25456. var p1 = positions[indices[index + 1]];
  25457. var p2 = positions[indices[index + 2]];
  25458. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25459. if (currentIntersectInfo) {
  25460. if (currentIntersectInfo.distance < 0) {
  25461. continue;
  25462. }
  25463. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25464. intersectInfo = currentIntersectInfo;
  25465. intersectInfo.faceId = index / 3;
  25466. if (fastCheck) {
  25467. break;
  25468. }
  25469. }
  25470. }
  25471. }
  25472. }
  25473. return intersectInfo;
  25474. };
  25475. SubMesh.prototype._rebuild = function () {
  25476. if (this._linesIndexBuffer) {
  25477. this._linesIndexBuffer = null;
  25478. }
  25479. };
  25480. // Clone
  25481. /**
  25482. * Creates a new Submesh from the passed Mesh.
  25483. */
  25484. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25485. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25486. if (!this.IsGlobal) {
  25487. var boundingInfo = this.getBoundingInfo();
  25488. if (!boundingInfo) {
  25489. return result;
  25490. }
  25491. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25492. }
  25493. return result;
  25494. };
  25495. // Dispose
  25496. /**
  25497. * Disposes the Submesh.
  25498. * Returns nothing.
  25499. */
  25500. SubMesh.prototype.dispose = function () {
  25501. if (this._linesIndexBuffer) {
  25502. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25503. this._linesIndexBuffer = null;
  25504. }
  25505. // Remove from mesh
  25506. var index = this._mesh.subMeshes.indexOf(this);
  25507. this._mesh.subMeshes.splice(index, 1);
  25508. };
  25509. // Statics
  25510. /**
  25511. * Creates a new Submesh from the passed parameters :
  25512. * - materialIndex (integer) : the index of the main mesh material.
  25513. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25514. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25515. * - mesh (Mesh) : the main mesh to create the submesh from.
  25516. * - renderingMesh (optional Mesh) : rendering mesh.
  25517. */
  25518. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25519. var minVertexIndex = Number.MAX_VALUE;
  25520. var maxVertexIndex = -Number.MAX_VALUE;
  25521. renderingMesh = (renderingMesh || mesh);
  25522. var indices = renderingMesh.getIndices();
  25523. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25524. var vertexIndex = indices[index];
  25525. if (vertexIndex < minVertexIndex)
  25526. minVertexIndex = vertexIndex;
  25527. if (vertexIndex > maxVertexIndex)
  25528. maxVertexIndex = vertexIndex;
  25529. }
  25530. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25531. };
  25532. return SubMesh;
  25533. }(BaseSubMesh));
  25534. BABYLON.SubMesh = SubMesh;
  25535. })(BABYLON || (BABYLON = {}));
  25536. //# sourceMappingURL=babylon.subMesh.js.map
  25537. var BABYLON;
  25538. (function (BABYLON) {
  25539. var EffectFallbacks = /** @class */ (function () {
  25540. function EffectFallbacks() {
  25541. this._defines = {};
  25542. this._currentRank = 32;
  25543. this._maxRank = -1;
  25544. }
  25545. EffectFallbacks.prototype.unBindMesh = function () {
  25546. this._mesh = null;
  25547. };
  25548. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25549. if (!this._defines[rank]) {
  25550. if (rank < this._currentRank) {
  25551. this._currentRank = rank;
  25552. }
  25553. if (rank > this._maxRank) {
  25554. this._maxRank = rank;
  25555. }
  25556. this._defines[rank] = new Array();
  25557. }
  25558. this._defines[rank].push(define);
  25559. };
  25560. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25561. this._meshRank = rank;
  25562. this._mesh = mesh;
  25563. if (rank < this._currentRank) {
  25564. this._currentRank = rank;
  25565. }
  25566. if (rank > this._maxRank) {
  25567. this._maxRank = rank;
  25568. }
  25569. };
  25570. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25571. get: function () {
  25572. return this._currentRank <= this._maxRank;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25578. // First we try to switch to CPU skinning
  25579. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25580. this._mesh.computeBonesUsingShaders = false;
  25581. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25582. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25583. var scene = this._mesh.getScene();
  25584. for (var index = 0; index < scene.meshes.length; index++) {
  25585. var otherMesh = scene.meshes[index];
  25586. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25587. otherMesh.computeBonesUsingShaders = false;
  25588. }
  25589. }
  25590. }
  25591. else {
  25592. var currentFallbacks = this._defines[this._currentRank];
  25593. if (currentFallbacks) {
  25594. for (var index = 0; index < currentFallbacks.length; index++) {
  25595. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25596. }
  25597. }
  25598. this._currentRank++;
  25599. }
  25600. return currentDefines;
  25601. };
  25602. return EffectFallbacks;
  25603. }());
  25604. BABYLON.EffectFallbacks = EffectFallbacks;
  25605. var EffectCreationOptions = /** @class */ (function () {
  25606. function EffectCreationOptions() {
  25607. }
  25608. return EffectCreationOptions;
  25609. }());
  25610. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25611. var Effect = /** @class */ (function () {
  25612. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25613. if (samplers === void 0) { samplers = null; }
  25614. if (defines === void 0) { defines = null; }
  25615. if (fallbacks === void 0) { fallbacks = null; }
  25616. if (onCompiled === void 0) { onCompiled = null; }
  25617. if (onError === void 0) { onError = null; }
  25618. var _this = this;
  25619. this.uniqueId = 0;
  25620. this.onCompileObservable = new BABYLON.Observable();
  25621. this.onErrorObservable = new BABYLON.Observable();
  25622. this.onBindObservable = new BABYLON.Observable();
  25623. this._uniformBuffersNames = {};
  25624. this._isReady = false;
  25625. this._compilationError = "";
  25626. this.name = baseName;
  25627. if (attributesNamesOrOptions.attributes) {
  25628. var options = attributesNamesOrOptions;
  25629. this._engine = uniformsNamesOrEngine;
  25630. this._attributesNames = options.attributes;
  25631. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25632. this._samplers = options.samplers;
  25633. this.defines = options.defines;
  25634. this.onError = options.onError;
  25635. this.onCompiled = options.onCompiled;
  25636. this._fallbacks = options.fallbacks;
  25637. this._indexParameters = options.indexParameters;
  25638. if (options.uniformBuffersNames) {
  25639. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25640. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25641. }
  25642. }
  25643. }
  25644. else {
  25645. this._engine = engine;
  25646. this.defines = defines;
  25647. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25648. this._samplers = samplers;
  25649. this._attributesNames = attributesNamesOrOptions;
  25650. this.onError = onError;
  25651. this.onCompiled = onCompiled;
  25652. this._indexParameters = indexParameters;
  25653. this._fallbacks = fallbacks;
  25654. }
  25655. this.uniqueId = Effect._uniqueIdSeed++;
  25656. var vertexSource;
  25657. var fragmentSource;
  25658. if (baseName.vertexElement) {
  25659. vertexSource = document.getElementById(baseName.vertexElement);
  25660. if (!vertexSource) {
  25661. vertexSource = baseName.vertexElement;
  25662. }
  25663. }
  25664. else {
  25665. vertexSource = baseName.vertex || baseName;
  25666. }
  25667. if (baseName.fragmentElement) {
  25668. fragmentSource = document.getElementById(baseName.fragmentElement);
  25669. if (!fragmentSource) {
  25670. fragmentSource = baseName.fragmentElement;
  25671. }
  25672. }
  25673. else {
  25674. fragmentSource = baseName.fragment || baseName;
  25675. }
  25676. this._loadVertexShader(vertexSource, function (vertexCode) {
  25677. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25678. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25679. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25680. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25681. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25682. if (baseName) {
  25683. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25684. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25685. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25686. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25687. }
  25688. else {
  25689. _this._vertexSourceCode = migratedVertexCode;
  25690. _this._fragmentSourceCode = migratedFragmentCode;
  25691. }
  25692. _this._prepareEffect();
  25693. });
  25694. });
  25695. });
  25696. });
  25697. });
  25698. });
  25699. }
  25700. Object.defineProperty(Effect.prototype, "key", {
  25701. get: function () {
  25702. return this._key;
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. // Properties
  25708. Effect.prototype.isReady = function () {
  25709. return this._isReady;
  25710. };
  25711. Effect.prototype.getEngine = function () {
  25712. return this._engine;
  25713. };
  25714. Effect.prototype.getProgram = function () {
  25715. return this._program;
  25716. };
  25717. Effect.prototype.getAttributesNames = function () {
  25718. return this._attributesNames;
  25719. };
  25720. Effect.prototype.getAttributeLocation = function (index) {
  25721. return this._attributes[index];
  25722. };
  25723. Effect.prototype.getAttributeLocationByName = function (name) {
  25724. var index = this._attributesNames.indexOf(name);
  25725. return this._attributes[index];
  25726. };
  25727. Effect.prototype.getAttributesCount = function () {
  25728. return this._attributes.length;
  25729. };
  25730. Effect.prototype.getUniformIndex = function (uniformName) {
  25731. return this._uniformsNames.indexOf(uniformName);
  25732. };
  25733. Effect.prototype.getUniform = function (uniformName) {
  25734. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25735. };
  25736. Effect.prototype.getSamplers = function () {
  25737. return this._samplers;
  25738. };
  25739. Effect.prototype.getCompilationError = function () {
  25740. return this._compilationError;
  25741. };
  25742. // Methods
  25743. Effect.prototype.executeWhenCompiled = function (func) {
  25744. if (this.isReady()) {
  25745. func(this);
  25746. return;
  25747. }
  25748. this.onCompileObservable.add(function (effect) {
  25749. func(effect);
  25750. });
  25751. };
  25752. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25753. if (BABYLON.Tools.IsWindowObjectExist()) {
  25754. // DOM element ?
  25755. if (vertex instanceof HTMLElement) {
  25756. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25757. callback(vertexCode);
  25758. return;
  25759. }
  25760. }
  25761. // Base64 encoded ?
  25762. if (vertex.substr(0, 7) === "base64:") {
  25763. var vertexBinary = window.atob(vertex.substr(7));
  25764. callback(vertexBinary);
  25765. return;
  25766. }
  25767. // Is in local store ?
  25768. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25769. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25770. return;
  25771. }
  25772. var vertexShaderUrl;
  25773. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25774. vertexShaderUrl = vertex;
  25775. }
  25776. else {
  25777. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25778. }
  25779. // Vertex shader
  25780. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25781. };
  25782. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25783. if (BABYLON.Tools.IsWindowObjectExist()) {
  25784. // DOM element ?
  25785. if (fragment instanceof HTMLElement) {
  25786. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25787. callback(fragmentCode);
  25788. return;
  25789. }
  25790. }
  25791. // Base64 encoded ?
  25792. if (fragment.substr(0, 7) === "base64:") {
  25793. var fragmentBinary = window.atob(fragment.substr(7));
  25794. callback(fragmentBinary);
  25795. return;
  25796. }
  25797. // Is in local store ?
  25798. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25799. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25800. return;
  25801. }
  25802. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25803. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25804. return;
  25805. }
  25806. var fragmentShaderUrl;
  25807. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25808. fragmentShaderUrl = fragment;
  25809. }
  25810. else {
  25811. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25812. }
  25813. // Fragment shader
  25814. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25815. };
  25816. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25817. // Rebuild shaders source code
  25818. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25819. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25820. vertexCode = prefix + vertexCode;
  25821. fragmentCode = prefix + fragmentCode;
  25822. // Number lines of shaders source code
  25823. var i = 2;
  25824. var regex = /\n/gm;
  25825. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25826. i = 2;
  25827. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25828. // Dump shaders name and formatted source code
  25829. if (this.name.vertexElement) {
  25830. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25831. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25832. }
  25833. else if (this.name.vertex) {
  25834. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25835. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25836. }
  25837. else {
  25838. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25839. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25840. }
  25841. };
  25842. ;
  25843. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25844. var preparedSourceCode = this._processPrecision(sourceCode);
  25845. if (this._engine.webGLVersion == 1) {
  25846. callback(preparedSourceCode);
  25847. return;
  25848. }
  25849. // Already converted
  25850. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25851. callback(preparedSourceCode.replace("#version 300 es", ""));
  25852. return;
  25853. }
  25854. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25855. // Remove extensions
  25856. // #extension GL_OES_standard_derivatives : enable
  25857. // #extension GL_EXT_shader_texture_lod : enable
  25858. // #extension GL_EXT_frag_depth : enable
  25859. // #extension GL_EXT_draw_buffers : require
  25860. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25861. var result = preparedSourceCode.replace(regex, "");
  25862. // Migrate to GLSL v300
  25863. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25864. result = result.replace(/attribute[ \t]/g, "in ");
  25865. result = result.replace(/[ \t]attribute/g, " in");
  25866. if (isFragment) {
  25867. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25868. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25869. result = result.replace(/texture2D\s*\(/g, "texture(");
  25870. result = result.replace(/textureCube\s*\(/g, "texture(");
  25871. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25872. result = result.replace(/gl_FragColor/g, "glFragColor");
  25873. result = result.replace(/gl_FragData/g, "glFragData");
  25874. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25875. }
  25876. callback(result);
  25877. };
  25878. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25879. var _this = this;
  25880. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25881. var match = regex.exec(sourceCode);
  25882. var returnValue = new String(sourceCode);
  25883. while (match != null) {
  25884. var includeFile = match[1];
  25885. // Uniform declaration
  25886. if (includeFile.indexOf("__decl__") !== -1) {
  25887. includeFile = includeFile.replace(/__decl__/, "");
  25888. if (this._engine.supportsUniformBuffers) {
  25889. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25890. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25891. }
  25892. includeFile = includeFile + "Declaration";
  25893. }
  25894. if (Effect.IncludesShadersStore[includeFile]) {
  25895. // Substitution
  25896. var includeContent = Effect.IncludesShadersStore[includeFile];
  25897. if (match[2]) {
  25898. var splits = match[3].split(",");
  25899. for (var index = 0; index < splits.length; index += 2) {
  25900. var source = new RegExp(splits[index], "g");
  25901. var dest = splits[index + 1];
  25902. includeContent = includeContent.replace(source, dest);
  25903. }
  25904. }
  25905. if (match[4]) {
  25906. var indexString = match[5];
  25907. if (indexString.indexOf("..") !== -1) {
  25908. var indexSplits = indexString.split("..");
  25909. var minIndex = parseInt(indexSplits[0]);
  25910. var maxIndex = parseInt(indexSplits[1]);
  25911. var sourceIncludeContent = includeContent.slice(0);
  25912. includeContent = "";
  25913. if (isNaN(maxIndex)) {
  25914. maxIndex = this._indexParameters[indexSplits[1]];
  25915. }
  25916. for (var i = minIndex; i < maxIndex; i++) {
  25917. if (!this._engine.supportsUniformBuffers) {
  25918. // Ubo replacement
  25919. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25920. return p1 + "{X}";
  25921. });
  25922. }
  25923. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25924. }
  25925. }
  25926. else {
  25927. if (!this._engine.supportsUniformBuffers) {
  25928. // Ubo replacement
  25929. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25930. return p1 + "{X}";
  25931. });
  25932. }
  25933. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25934. }
  25935. }
  25936. // Replace
  25937. returnValue = returnValue.replace(match[0], includeContent);
  25938. }
  25939. else {
  25940. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25941. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25942. Effect.IncludesShadersStore[includeFile] = fileContent;
  25943. _this._processIncludes(returnValue, callback);
  25944. });
  25945. return;
  25946. }
  25947. match = regex.exec(sourceCode);
  25948. }
  25949. callback(returnValue);
  25950. };
  25951. Effect.prototype._processPrecision = function (source) {
  25952. if (source.indexOf("precision highp float") === -1) {
  25953. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25954. source = "precision mediump float;\n" + source;
  25955. }
  25956. else {
  25957. source = "precision highp float;\n" + source;
  25958. }
  25959. }
  25960. else {
  25961. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25962. source = source.replace("precision highp float", "precision mediump float");
  25963. }
  25964. }
  25965. return source;
  25966. };
  25967. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25968. var _this = this;
  25969. this._isReady = false;
  25970. this._vertexSourceCodeOverride = vertexSourceCode;
  25971. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25972. this.onError = function (effect, error) {
  25973. if (onError) {
  25974. onError(error);
  25975. }
  25976. };
  25977. this.onCompiled = function () {
  25978. var scenes = _this.getEngine().scenes;
  25979. for (var i = 0; i < scenes.length; i++) {
  25980. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25981. }
  25982. if (onCompiled) {
  25983. onCompiled(_this._program);
  25984. }
  25985. };
  25986. this._fallbacks = null;
  25987. this._prepareEffect();
  25988. };
  25989. Effect.prototype._prepareEffect = function () {
  25990. var attributesNames = this._attributesNames;
  25991. var defines = this.defines;
  25992. var fallbacks = this._fallbacks;
  25993. this._valueCache = {};
  25994. var previousProgram = this._program;
  25995. try {
  25996. var engine = this._engine;
  25997. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25998. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25999. }
  26000. else {
  26001. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26002. }
  26003. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26004. if (engine.webGLVersion > 1) {
  26005. for (var name in this._uniformBuffersNames) {
  26006. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26007. }
  26008. }
  26009. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26010. this._attributes = engine.getAttributes(this._program, attributesNames);
  26011. var index;
  26012. for (index = 0; index < this._samplers.length; index++) {
  26013. var sampler = this.getUniform(this._samplers[index]);
  26014. if (sampler == null) {
  26015. this._samplers.splice(index, 1);
  26016. index--;
  26017. }
  26018. }
  26019. engine.bindSamplers(this);
  26020. this._compilationError = "";
  26021. this._isReady = true;
  26022. if (this.onCompiled) {
  26023. this.onCompiled(this);
  26024. }
  26025. this.onCompileObservable.notifyObservers(this);
  26026. this.onCompileObservable.clear();
  26027. // Unbind mesh reference in fallbacks
  26028. if (this._fallbacks) {
  26029. this._fallbacks.unBindMesh();
  26030. }
  26031. if (previousProgram) {
  26032. this.getEngine()._deleteProgram(previousProgram);
  26033. }
  26034. }
  26035. catch (e) {
  26036. this._compilationError = e.message;
  26037. // Let's go through fallbacks then
  26038. BABYLON.Tools.Error("Unable to compile effect:");
  26039. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26040. return " " + uniform;
  26041. }));
  26042. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26043. return " " + attribute;
  26044. }));
  26045. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26046. BABYLON.Tools.Error("Error: " + this._compilationError);
  26047. if (previousProgram) {
  26048. this._program = previousProgram;
  26049. this._isReady = true;
  26050. if (this.onError) {
  26051. this.onError(this, this._compilationError);
  26052. }
  26053. this.onErrorObservable.notifyObservers(this);
  26054. }
  26055. if (fallbacks && fallbacks.isMoreFallbacks) {
  26056. BABYLON.Tools.Error("Trying next fallback.");
  26057. this.defines = fallbacks.reduce(this.defines);
  26058. this._prepareEffect();
  26059. }
  26060. else {
  26061. if (this.onError) {
  26062. this.onError(this, this._compilationError);
  26063. }
  26064. this.onErrorObservable.notifyObservers(this);
  26065. this.onErrorObservable.clear();
  26066. // Unbind mesh reference in fallbacks
  26067. if (this._fallbacks) {
  26068. this._fallbacks.unBindMesh();
  26069. }
  26070. }
  26071. }
  26072. };
  26073. Object.defineProperty(Effect.prototype, "isSupported", {
  26074. get: function () {
  26075. return this._compilationError === "";
  26076. },
  26077. enumerable: true,
  26078. configurable: true
  26079. });
  26080. Effect.prototype._bindTexture = function (channel, texture) {
  26081. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26082. };
  26083. Effect.prototype.setTexture = function (channel, texture) {
  26084. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26085. };
  26086. Effect.prototype.setTextureArray = function (channel, textures) {
  26087. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26088. var initialPos = this._samplers.indexOf(channel);
  26089. for (var index = 1; index < textures.length; index++) {
  26090. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26091. }
  26092. }
  26093. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26094. };
  26095. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26096. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26097. };
  26098. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26099. var cache = this._valueCache[uniformName];
  26100. var flag = matrix.updateFlag;
  26101. if (cache !== undefined && cache === flag) {
  26102. return false;
  26103. }
  26104. this._valueCache[uniformName] = flag;
  26105. return true;
  26106. };
  26107. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26108. var cache = this._valueCache[uniformName];
  26109. if (!cache) {
  26110. cache = [x, y];
  26111. this._valueCache[uniformName] = cache;
  26112. return true;
  26113. }
  26114. var changed = false;
  26115. if (cache[0] !== x) {
  26116. cache[0] = x;
  26117. changed = true;
  26118. }
  26119. if (cache[1] !== y) {
  26120. cache[1] = y;
  26121. changed = true;
  26122. }
  26123. return changed;
  26124. };
  26125. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26126. var cache = this._valueCache[uniformName];
  26127. if (!cache) {
  26128. cache = [x, y, z];
  26129. this._valueCache[uniformName] = cache;
  26130. return true;
  26131. }
  26132. var changed = false;
  26133. if (cache[0] !== x) {
  26134. cache[0] = x;
  26135. changed = true;
  26136. }
  26137. if (cache[1] !== y) {
  26138. cache[1] = y;
  26139. changed = true;
  26140. }
  26141. if (cache[2] !== z) {
  26142. cache[2] = z;
  26143. changed = true;
  26144. }
  26145. return changed;
  26146. };
  26147. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26148. var cache = this._valueCache[uniformName];
  26149. if (!cache) {
  26150. cache = [x, y, z, w];
  26151. this._valueCache[uniformName] = cache;
  26152. return true;
  26153. }
  26154. var changed = false;
  26155. if (cache[0] !== x) {
  26156. cache[0] = x;
  26157. changed = true;
  26158. }
  26159. if (cache[1] !== y) {
  26160. cache[1] = y;
  26161. changed = true;
  26162. }
  26163. if (cache[2] !== z) {
  26164. cache[2] = z;
  26165. changed = true;
  26166. }
  26167. if (cache[3] !== w) {
  26168. cache[3] = w;
  26169. changed = true;
  26170. }
  26171. return changed;
  26172. };
  26173. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26174. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26175. return;
  26176. }
  26177. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26178. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26179. };
  26180. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26181. this._engine.bindUniformBlock(this._program, blockName, index);
  26182. };
  26183. Effect.prototype.setIntArray = function (uniformName, array) {
  26184. this._valueCache[uniformName] = null;
  26185. this._engine.setIntArray(this.getUniform(uniformName), array);
  26186. return this;
  26187. };
  26188. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26189. this._valueCache[uniformName] = null;
  26190. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26191. return this;
  26192. };
  26193. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26194. this._valueCache[uniformName] = null;
  26195. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26196. return this;
  26197. };
  26198. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26199. this._valueCache[uniformName] = null;
  26200. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26201. return this;
  26202. };
  26203. Effect.prototype.setFloatArray = function (uniformName, array) {
  26204. this._valueCache[uniformName] = null;
  26205. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26206. return this;
  26207. };
  26208. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26209. this._valueCache[uniformName] = null;
  26210. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26211. return this;
  26212. };
  26213. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26214. this._valueCache[uniformName] = null;
  26215. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26216. return this;
  26217. };
  26218. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26219. this._valueCache[uniformName] = null;
  26220. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26221. return this;
  26222. };
  26223. Effect.prototype.setArray = function (uniformName, array) {
  26224. this._valueCache[uniformName] = null;
  26225. this._engine.setArray(this.getUniform(uniformName), array);
  26226. return this;
  26227. };
  26228. Effect.prototype.setArray2 = function (uniformName, array) {
  26229. this._valueCache[uniformName] = null;
  26230. this._engine.setArray2(this.getUniform(uniformName), array);
  26231. return this;
  26232. };
  26233. Effect.prototype.setArray3 = function (uniformName, array) {
  26234. this._valueCache[uniformName] = null;
  26235. this._engine.setArray3(this.getUniform(uniformName), array);
  26236. return this;
  26237. };
  26238. Effect.prototype.setArray4 = function (uniformName, array) {
  26239. this._valueCache[uniformName] = null;
  26240. this._engine.setArray4(this.getUniform(uniformName), array);
  26241. return this;
  26242. };
  26243. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26244. if (!matrices) {
  26245. return this;
  26246. }
  26247. this._valueCache[uniformName] = null;
  26248. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26249. return this;
  26250. };
  26251. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26252. if (this._cacheMatrix(uniformName, matrix)) {
  26253. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26254. }
  26255. return this;
  26256. };
  26257. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26258. this._valueCache[uniformName] = null;
  26259. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26260. return this;
  26261. };
  26262. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26263. this._valueCache[uniformName] = null;
  26264. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26265. return this;
  26266. };
  26267. Effect.prototype.setFloat = function (uniformName, value) {
  26268. var cache = this._valueCache[uniformName];
  26269. if (cache !== undefined && cache === value)
  26270. return this;
  26271. this._valueCache[uniformName] = value;
  26272. this._engine.setFloat(this.getUniform(uniformName), value);
  26273. return this;
  26274. };
  26275. Effect.prototype.setBool = function (uniformName, bool) {
  26276. var cache = this._valueCache[uniformName];
  26277. if (cache !== undefined && cache === bool)
  26278. return this;
  26279. this._valueCache[uniformName] = bool;
  26280. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26281. return this;
  26282. };
  26283. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26284. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26285. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26286. }
  26287. return this;
  26288. };
  26289. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26290. if (this._cacheFloat2(uniformName, x, y)) {
  26291. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26292. }
  26293. return this;
  26294. };
  26295. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26296. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26297. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26298. }
  26299. return this;
  26300. };
  26301. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26302. if (this._cacheFloat3(uniformName, x, y, z)) {
  26303. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26304. }
  26305. return this;
  26306. };
  26307. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26308. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26309. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26310. }
  26311. return this;
  26312. };
  26313. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26314. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26315. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26316. }
  26317. return this;
  26318. };
  26319. Effect.prototype.setColor3 = function (uniformName, color3) {
  26320. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26321. this._engine.setColor3(this.getUniform(uniformName), color3);
  26322. }
  26323. return this;
  26324. };
  26325. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26326. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26327. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26328. }
  26329. return this;
  26330. };
  26331. Effect.ResetCache = function () {
  26332. Effect._baseCache = {};
  26333. };
  26334. Effect._uniqueIdSeed = 0;
  26335. Effect._baseCache = {};
  26336. // Statics
  26337. Effect.ShadersStore = {};
  26338. Effect.IncludesShadersStore = {};
  26339. return Effect;
  26340. }());
  26341. BABYLON.Effect = Effect;
  26342. })(BABYLON || (BABYLON = {}));
  26343. //# sourceMappingURL=babylon.effect.js.map
  26344. var BABYLON;
  26345. (function (BABYLON) {
  26346. var MaterialHelper = /** @class */ (function () {
  26347. function MaterialHelper() {
  26348. }
  26349. MaterialHelper.BindEyePosition = function (effect, scene) {
  26350. if (scene._forcedViewPosition) {
  26351. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26352. return;
  26353. }
  26354. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26355. };
  26356. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26357. defines._needUVs = true;
  26358. defines[key] = true;
  26359. if (texture.getTextureMatrix().isIdentity(true)) {
  26360. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26361. if (texture.coordinatesIndex === 0) {
  26362. defines["MAINUV1"] = true;
  26363. }
  26364. else {
  26365. defines["MAINUV2"] = true;
  26366. }
  26367. }
  26368. else {
  26369. defines[key + "DIRECTUV"] = 0;
  26370. }
  26371. };
  26372. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26373. var matrix = texture.getTextureMatrix();
  26374. if (!matrix.isIdentity(true)) {
  26375. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26376. }
  26377. };
  26378. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26379. if (defines._areMiscDirty) {
  26380. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26381. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26382. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26383. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26384. }
  26385. };
  26386. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26387. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26388. var changed = false;
  26389. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26390. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26391. changed = true;
  26392. }
  26393. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26394. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26395. changed = true;
  26396. }
  26397. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26398. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26399. changed = true;
  26400. }
  26401. if (defines["INSTANCES"] !== useInstances) {
  26402. defines["INSTANCES"] = useInstances;
  26403. changed = true;
  26404. }
  26405. if (changed) {
  26406. defines.markAsUnprocessed();
  26407. }
  26408. };
  26409. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26410. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26411. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26412. return false;
  26413. }
  26414. defines._normals = defines._needNormals;
  26415. defines._uvs = defines._needUVs;
  26416. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26417. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26418. defines["TANGENT"] = true;
  26419. }
  26420. if (defines._needUVs) {
  26421. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26422. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26423. }
  26424. else {
  26425. defines["UV1"] = false;
  26426. defines["UV2"] = false;
  26427. }
  26428. if (useVertexColor) {
  26429. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26430. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26431. }
  26432. if (useBones) {
  26433. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26434. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26435. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26436. }
  26437. else {
  26438. defines["NUM_BONE_INFLUENCERS"] = 0;
  26439. defines["BonesPerMesh"] = 0;
  26440. }
  26441. }
  26442. if (useMorphTargets) {
  26443. var manager = mesh.morphTargetManager;
  26444. if (manager) {
  26445. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26446. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26447. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26448. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26449. }
  26450. else {
  26451. defines["MORPHTARGETS_TANGENT"] = false;
  26452. defines["MORPHTARGETS_NORMAL"] = false;
  26453. defines["MORPHTARGETS"] = false;
  26454. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26455. }
  26456. }
  26457. return true;
  26458. };
  26459. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26460. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26461. if (disableLighting === void 0) { disableLighting = false; }
  26462. if (!defines._areLightsDirty) {
  26463. return defines._needNormals;
  26464. }
  26465. var lightIndex = 0;
  26466. var needNormals = false;
  26467. var needRebuild = false;
  26468. var lightmapMode = false;
  26469. var shadowEnabled = false;
  26470. var specularEnabled = false;
  26471. if (scene.lightsEnabled && !disableLighting) {
  26472. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26473. var light = _a[_i];
  26474. needNormals = true;
  26475. if (defines["LIGHT" + lightIndex] === undefined) {
  26476. needRebuild = true;
  26477. }
  26478. defines["LIGHT" + lightIndex] = true;
  26479. defines["SPOTLIGHT" + lightIndex] = false;
  26480. defines["HEMILIGHT" + lightIndex] = false;
  26481. defines["POINTLIGHT" + lightIndex] = false;
  26482. defines["DIRLIGHT" + lightIndex] = false;
  26483. var type;
  26484. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26485. type = "SPOTLIGHT" + lightIndex;
  26486. }
  26487. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26488. type = "HEMILIGHT" + lightIndex;
  26489. }
  26490. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26491. type = "POINTLIGHT" + lightIndex;
  26492. }
  26493. else {
  26494. type = "DIRLIGHT" + lightIndex;
  26495. }
  26496. defines[type] = true;
  26497. // Specular
  26498. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26499. specularEnabled = true;
  26500. }
  26501. // Shadows
  26502. defines["SHADOW" + lightIndex] = false;
  26503. defines["SHADOWPCF" + lightIndex] = false;
  26504. defines["SHADOWESM" + lightIndex] = false;
  26505. defines["SHADOWCUBE" + lightIndex] = false;
  26506. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26507. var shadowGenerator = light.getShadowGenerator();
  26508. if (shadowGenerator) {
  26509. shadowEnabled = true;
  26510. shadowGenerator.prepareDefines(defines, lightIndex);
  26511. }
  26512. }
  26513. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26514. lightmapMode = true;
  26515. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26516. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26517. }
  26518. else {
  26519. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26520. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26521. }
  26522. lightIndex++;
  26523. if (lightIndex === maxSimultaneousLights)
  26524. break;
  26525. }
  26526. }
  26527. defines["SPECULARTERM"] = specularEnabled;
  26528. defines["SHADOWS"] = shadowEnabled;
  26529. // Resetting all other lights if any
  26530. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26531. if (defines["LIGHT" + index] !== undefined) {
  26532. defines["LIGHT" + index] = false;
  26533. defines["HEMILIGHT" + lightIndex] = false;
  26534. defines["POINTLIGHT" + lightIndex] = false;
  26535. defines["DIRLIGHT" + lightIndex] = false;
  26536. defines["SPOTLIGHT" + lightIndex] = false;
  26537. defines["SHADOW" + lightIndex] = false;
  26538. }
  26539. }
  26540. var caps = scene.getEngine().getCaps();
  26541. if (defines["SHADOWFLOAT"] === undefined) {
  26542. needRebuild = true;
  26543. }
  26544. defines["SHADOWFLOAT"] = shadowEnabled &&
  26545. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26546. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26547. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26548. if (needRebuild) {
  26549. defines.rebuild();
  26550. }
  26551. return needNormals;
  26552. };
  26553. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26554. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26555. var uniformsList;
  26556. var uniformBuffersList = null;
  26557. if (uniformsListOrOptions.uniformsNames) {
  26558. var options = uniformsListOrOptions;
  26559. uniformsList = options.uniformsNames;
  26560. uniformBuffersList = options.uniformBuffersNames;
  26561. samplersList = options.samplers;
  26562. defines = options.defines;
  26563. maxSimultaneousLights = options.maxSimultaneousLights;
  26564. }
  26565. else {
  26566. uniformsList = uniformsListOrOptions;
  26567. if (!samplersList) {
  26568. samplersList = [];
  26569. }
  26570. }
  26571. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26572. if (!defines["LIGHT" + lightIndex]) {
  26573. break;
  26574. }
  26575. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26576. if (uniformBuffersList) {
  26577. uniformBuffersList.push("Light" + lightIndex);
  26578. }
  26579. samplersList.push("shadowSampler" + lightIndex);
  26580. }
  26581. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26582. uniformsList.push("morphTargetInfluences");
  26583. }
  26584. };
  26585. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26586. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26587. if (!defines["SHADOWS"]) {
  26588. return;
  26589. }
  26590. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26591. if (!defines["LIGHT" + lightIndex]) {
  26592. break;
  26593. }
  26594. if (lightIndex > 0) {
  26595. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26596. }
  26597. if (defines["SHADOW" + lightIndex]) {
  26598. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26599. }
  26600. if (defines["SHADOWPCF" + lightIndex]) {
  26601. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26602. }
  26603. if (defines["SHADOWESM" + lightIndex]) {
  26604. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26605. }
  26606. }
  26607. };
  26608. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26609. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26610. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26611. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26612. var manager = mesh.morphTargetManager;
  26613. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26614. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26615. for (var index = 0; index < influencers; index++) {
  26616. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26617. if (normal) {
  26618. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26619. }
  26620. if (tangent) {
  26621. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26622. }
  26623. if (attribs.length > maxAttributesCount) {
  26624. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26625. }
  26626. }
  26627. }
  26628. };
  26629. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26630. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26631. fallbacks.addCPUSkinningFallback(0, mesh);
  26632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26634. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26637. }
  26638. }
  26639. };
  26640. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26641. if (defines["INSTANCES"]) {
  26642. attribs.push("world0");
  26643. attribs.push("world1");
  26644. attribs.push("world2");
  26645. attribs.push("world3");
  26646. }
  26647. };
  26648. // Bindings
  26649. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26650. if (light.shadowEnabled && mesh.receiveShadows) {
  26651. var shadowGenerator = light.getShadowGenerator();
  26652. if (shadowGenerator) {
  26653. shadowGenerator.bindShadowLight(lightIndex, effect);
  26654. }
  26655. }
  26656. };
  26657. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26658. light.transferToEffect(effect, lightIndex + "");
  26659. };
  26660. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26661. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26662. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26663. var lightIndex = 0;
  26664. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26665. var light = _a[_i];
  26666. var scaledIntensity = light.getScaledIntensity();
  26667. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26668. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26669. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26670. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26671. if (defines["SPECULARTERM"]) {
  26672. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26673. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26674. }
  26675. // Shadows
  26676. if (scene.shadowsEnabled) {
  26677. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26678. }
  26679. light._uniformBuffer.update();
  26680. lightIndex++;
  26681. if (lightIndex === maxSimultaneousLights)
  26682. break;
  26683. }
  26684. };
  26685. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26686. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26687. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26688. effect.setColor3("vFogColor", scene.fogColor);
  26689. }
  26690. };
  26691. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26692. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26693. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26694. if (matrices && effect) {
  26695. effect.setMatrices("mBones", matrices);
  26696. }
  26697. }
  26698. };
  26699. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26700. var manager = abstractMesh.morphTargetManager;
  26701. if (!abstractMesh || !manager) {
  26702. return;
  26703. }
  26704. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26705. };
  26706. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26707. if (defines["LOGARITHMICDEPTH"]) {
  26708. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26709. }
  26710. };
  26711. MaterialHelper.BindClipPlane = function (effect, scene) {
  26712. if (scene.clipPlane) {
  26713. var clipPlane = scene.clipPlane;
  26714. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26715. }
  26716. };
  26717. return MaterialHelper;
  26718. }());
  26719. BABYLON.MaterialHelper = MaterialHelper;
  26720. })(BABYLON || (BABYLON = {}));
  26721. //# sourceMappingURL=babylon.materialHelper.js.map
  26722. var BABYLON;
  26723. (function (BABYLON) {
  26724. var MaterialDefines = /** @class */ (function () {
  26725. function MaterialDefines() {
  26726. this._isDirty = true;
  26727. this._areLightsDirty = true;
  26728. this._areAttributesDirty = true;
  26729. this._areTexturesDirty = true;
  26730. this._areFresnelDirty = true;
  26731. this._areMiscDirty = true;
  26732. this._areImageProcessingDirty = true;
  26733. this._normals = false;
  26734. this._uvs = false;
  26735. this._needNormals = false;
  26736. this._needUVs = false;
  26737. }
  26738. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26739. get: function () {
  26740. return this._isDirty;
  26741. },
  26742. enumerable: true,
  26743. configurable: true
  26744. });
  26745. MaterialDefines.prototype.markAsProcessed = function () {
  26746. this._isDirty = false;
  26747. this._areAttributesDirty = false;
  26748. this._areTexturesDirty = false;
  26749. this._areFresnelDirty = false;
  26750. this._areLightsDirty = false;
  26751. this._areMiscDirty = false;
  26752. this._areImageProcessingDirty = false;
  26753. };
  26754. MaterialDefines.prototype.markAsUnprocessed = function () {
  26755. this._isDirty = true;
  26756. };
  26757. MaterialDefines.prototype.markAllAsDirty = function () {
  26758. this._areTexturesDirty = true;
  26759. this._areAttributesDirty = true;
  26760. this._areLightsDirty = true;
  26761. this._areFresnelDirty = true;
  26762. this._areMiscDirty = true;
  26763. this._areImageProcessingDirty = true;
  26764. this._isDirty = true;
  26765. };
  26766. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26767. this._areImageProcessingDirty = true;
  26768. this._isDirty = true;
  26769. };
  26770. MaterialDefines.prototype.markAsLightDirty = function () {
  26771. this._areLightsDirty = true;
  26772. this._isDirty = true;
  26773. };
  26774. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26775. this._areAttributesDirty = true;
  26776. this._isDirty = true;
  26777. };
  26778. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26779. this._areTexturesDirty = true;
  26780. this._isDirty = true;
  26781. };
  26782. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26783. this._areFresnelDirty = true;
  26784. this._isDirty = true;
  26785. };
  26786. MaterialDefines.prototype.markAsMiscDirty = function () {
  26787. this._areMiscDirty = true;
  26788. this._isDirty = true;
  26789. };
  26790. MaterialDefines.prototype.rebuild = function () {
  26791. if (this._keys) {
  26792. delete this._keys;
  26793. }
  26794. this._keys = [];
  26795. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26796. var key = _a[_i];
  26797. if (key[0] === "_") {
  26798. continue;
  26799. }
  26800. this._keys.push(key);
  26801. }
  26802. };
  26803. MaterialDefines.prototype.isEqual = function (other) {
  26804. if (this._keys.length !== other._keys.length) {
  26805. return false;
  26806. }
  26807. for (var index = 0; index < this._keys.length; index++) {
  26808. var prop = this._keys[index];
  26809. if (this[prop] !== other[prop]) {
  26810. return false;
  26811. }
  26812. }
  26813. return true;
  26814. };
  26815. MaterialDefines.prototype.cloneTo = function (other) {
  26816. if (this._keys.length !== other._keys.length) {
  26817. other._keys = this._keys.slice(0);
  26818. }
  26819. for (var index = 0; index < this._keys.length; index++) {
  26820. var prop = this._keys[index];
  26821. other[prop] = this[prop];
  26822. }
  26823. };
  26824. MaterialDefines.prototype.reset = function () {
  26825. for (var index = 0; index < this._keys.length; index++) {
  26826. var prop = this._keys[index];
  26827. if (typeof (this[prop]) === "number") {
  26828. this[prop] = 0;
  26829. }
  26830. else {
  26831. this[prop] = false;
  26832. }
  26833. }
  26834. };
  26835. MaterialDefines.prototype.toString = function () {
  26836. var result = "";
  26837. for (var index = 0; index < this._keys.length; index++) {
  26838. var prop = this._keys[index];
  26839. var value = this[prop];
  26840. if (typeof (value) === "number") {
  26841. result += "#define " + prop + " " + this[prop] + "\n";
  26842. }
  26843. else if (value) {
  26844. result += "#define " + prop + "\n";
  26845. }
  26846. }
  26847. return result;
  26848. };
  26849. return MaterialDefines;
  26850. }());
  26851. BABYLON.MaterialDefines = MaterialDefines;
  26852. var Material = /** @class */ (function () {
  26853. function Material(name, scene, doNotAdd) {
  26854. this.checkReadyOnEveryCall = false;
  26855. this.checkReadyOnlyOnce = false;
  26856. this.state = "";
  26857. this.alpha = 1.0;
  26858. this._backFaceCulling = true;
  26859. this.doNotSerialize = false;
  26860. this.storeEffectOnSubMeshes = false;
  26861. /**
  26862. * An event triggered when the material is disposed.
  26863. * @type {BABYLON.Observable}
  26864. */
  26865. this.onDisposeObservable = new BABYLON.Observable();
  26866. /**
  26867. * An event triggered when the material is bound.
  26868. * @type {BABYLON.Observable}
  26869. */
  26870. this.onBindObservable = new BABYLON.Observable();
  26871. /**
  26872. * An event triggered when the material is unbound.
  26873. * @type {BABYLON.Observable}
  26874. */
  26875. this.onUnBindObservable = new BABYLON.Observable();
  26876. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26877. this._needDepthPrePass = false;
  26878. this.disableDepthWrite = false;
  26879. this.forceDepthWrite = false;
  26880. this.separateCullingPass = false;
  26881. this._fogEnabled = true;
  26882. this.pointSize = 1.0;
  26883. this.zOffset = 0;
  26884. this._wasPreviouslyReady = false;
  26885. this._fillMode = Material.TriangleFillMode;
  26886. this.name = name;
  26887. this.id = name || BABYLON.Tools.RandomId();
  26888. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26889. if (this._scene.useRightHandedSystem) {
  26890. this.sideOrientation = Material.ClockWiseSideOrientation;
  26891. }
  26892. else {
  26893. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26894. }
  26895. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26896. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26897. if (!doNotAdd) {
  26898. this._scene.materials.push(this);
  26899. }
  26900. }
  26901. Object.defineProperty(Material, "TriangleFillMode", {
  26902. get: function () {
  26903. return Material._TriangleFillMode;
  26904. },
  26905. enumerable: true,
  26906. configurable: true
  26907. });
  26908. Object.defineProperty(Material, "WireFrameFillMode", {
  26909. get: function () {
  26910. return Material._WireFrameFillMode;
  26911. },
  26912. enumerable: true,
  26913. configurable: true
  26914. });
  26915. Object.defineProperty(Material, "PointFillMode", {
  26916. get: function () {
  26917. return Material._PointFillMode;
  26918. },
  26919. enumerable: true,
  26920. configurable: true
  26921. });
  26922. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26923. get: function () {
  26924. return Material._ClockWiseSideOrientation;
  26925. },
  26926. enumerable: true,
  26927. configurable: true
  26928. });
  26929. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26930. get: function () {
  26931. return Material._CounterClockWiseSideOrientation;
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Object.defineProperty(Material, "TextureDirtyFlag", {
  26937. get: function () {
  26938. return Material._TextureDirtyFlag;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. Object.defineProperty(Material, "LightDirtyFlag", {
  26944. get: function () {
  26945. return Material._LightDirtyFlag;
  26946. },
  26947. enumerable: true,
  26948. configurable: true
  26949. });
  26950. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26951. get: function () {
  26952. return Material._FresnelDirtyFlag;
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26958. get: function () {
  26959. return Material._AttributesDirtyFlag;
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(Material, "MiscDirtyFlag", {
  26965. get: function () {
  26966. return Material._MiscDirtyFlag;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26972. get: function () {
  26973. return this._backFaceCulling;
  26974. },
  26975. set: function (value) {
  26976. if (this._backFaceCulling === value) {
  26977. return;
  26978. }
  26979. this._backFaceCulling = value;
  26980. this.markAsDirty(Material.TextureDirtyFlag);
  26981. },
  26982. enumerable: true,
  26983. configurable: true
  26984. });
  26985. Object.defineProperty(Material.prototype, "onDispose", {
  26986. set: function (callback) {
  26987. if (this._onDisposeObserver) {
  26988. this.onDisposeObservable.remove(this._onDisposeObserver);
  26989. }
  26990. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26991. },
  26992. enumerable: true,
  26993. configurable: true
  26994. });
  26995. Object.defineProperty(Material.prototype, "onBind", {
  26996. set: function (callback) {
  26997. if (this._onBindObserver) {
  26998. this.onBindObservable.remove(this._onBindObserver);
  26999. }
  27000. this._onBindObserver = this.onBindObservable.add(callback);
  27001. },
  27002. enumerable: true,
  27003. configurable: true
  27004. });
  27005. Object.defineProperty(Material.prototype, "alphaMode", {
  27006. get: function () {
  27007. return this._alphaMode;
  27008. },
  27009. set: function (value) {
  27010. if (this._alphaMode === value) {
  27011. return;
  27012. }
  27013. this._alphaMode = value;
  27014. this.markAsDirty(Material.TextureDirtyFlag);
  27015. },
  27016. enumerable: true,
  27017. configurable: true
  27018. });
  27019. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27020. get: function () {
  27021. return this._needDepthPrePass;
  27022. },
  27023. set: function (value) {
  27024. if (this._needDepthPrePass === value) {
  27025. return;
  27026. }
  27027. this._needDepthPrePass = value;
  27028. if (this._needDepthPrePass) {
  27029. this.checkReadyOnEveryCall = true;
  27030. }
  27031. },
  27032. enumerable: true,
  27033. configurable: true
  27034. });
  27035. Object.defineProperty(Material.prototype, "fogEnabled", {
  27036. get: function () {
  27037. return this._fogEnabled;
  27038. },
  27039. set: function (value) {
  27040. if (this._fogEnabled === value) {
  27041. return;
  27042. }
  27043. this._fogEnabled = value;
  27044. this.markAsDirty(Material.MiscDirtyFlag);
  27045. },
  27046. enumerable: true,
  27047. configurable: true
  27048. });
  27049. Object.defineProperty(Material.prototype, "wireframe", {
  27050. get: function () {
  27051. return this._fillMode === Material.WireFrameFillMode;
  27052. },
  27053. set: function (value) {
  27054. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27055. },
  27056. enumerable: true,
  27057. configurable: true
  27058. });
  27059. Object.defineProperty(Material.prototype, "pointsCloud", {
  27060. get: function () {
  27061. return this._fillMode === Material.PointFillMode;
  27062. },
  27063. set: function (value) {
  27064. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27065. },
  27066. enumerable: true,
  27067. configurable: true
  27068. });
  27069. Object.defineProperty(Material.prototype, "fillMode", {
  27070. get: function () {
  27071. return this._fillMode;
  27072. },
  27073. set: function (value) {
  27074. if (this._fillMode === value) {
  27075. return;
  27076. }
  27077. this._fillMode = value;
  27078. this.markAsDirty(Material.MiscDirtyFlag);
  27079. },
  27080. enumerable: true,
  27081. configurable: true
  27082. });
  27083. /**
  27084. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27085. * subclasses should override adding information pertainent to themselves
  27086. */
  27087. Material.prototype.toString = function (fullDetails) {
  27088. var ret = "Name: " + this.name;
  27089. if (fullDetails) {
  27090. }
  27091. return ret;
  27092. };
  27093. /**
  27094. * Child classes can use it to update shaders
  27095. */
  27096. Material.prototype.getClassName = function () {
  27097. return "Material";
  27098. };
  27099. Object.defineProperty(Material.prototype, "isFrozen", {
  27100. get: function () {
  27101. return this.checkReadyOnlyOnce;
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. Material.prototype.freeze = function () {
  27107. this.checkReadyOnlyOnce = true;
  27108. };
  27109. Material.prototype.unfreeze = function () {
  27110. this.checkReadyOnlyOnce = false;
  27111. };
  27112. Material.prototype.isReady = function (mesh, useInstances) {
  27113. return true;
  27114. };
  27115. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27116. return false;
  27117. };
  27118. Material.prototype.getEffect = function () {
  27119. return this._effect;
  27120. };
  27121. Material.prototype.getScene = function () {
  27122. return this._scene;
  27123. };
  27124. Material.prototype.needAlphaBlending = function () {
  27125. return (this.alpha < 1.0);
  27126. };
  27127. Material.prototype.needAlphaTesting = function () {
  27128. return false;
  27129. };
  27130. Material.prototype.getAlphaTestTexture = function () {
  27131. return null;
  27132. };
  27133. Material.prototype.markDirty = function () {
  27134. this._wasPreviouslyReady = false;
  27135. };
  27136. Material.prototype._preBind = function (effect, overrideOrientation) {
  27137. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27138. var engine = this._scene.getEngine();
  27139. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27140. var reverse = orientation === Material.ClockWiseSideOrientation;
  27141. engine.enableEffect(effect ? effect : this._effect);
  27142. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27143. return reverse;
  27144. };
  27145. Material.prototype.bind = function (world, mesh) {
  27146. };
  27147. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27148. };
  27149. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27150. };
  27151. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27152. sceneUbo.bindToEffect(effect, "Scene");
  27153. };
  27154. Material.prototype.bindView = function (effect) {
  27155. if (!this._useUBO) {
  27156. effect.setMatrix("view", this.getScene().getViewMatrix());
  27157. }
  27158. else {
  27159. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27160. }
  27161. };
  27162. Material.prototype.bindViewProjection = function (effect) {
  27163. if (!this._useUBO) {
  27164. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27165. }
  27166. else {
  27167. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27168. }
  27169. };
  27170. Material.prototype._afterBind = function (mesh) {
  27171. this._scene._cachedMaterial = this;
  27172. if (mesh) {
  27173. this._scene._cachedVisibility = mesh.visibility;
  27174. }
  27175. else {
  27176. this._scene._cachedVisibility = 1;
  27177. }
  27178. if (mesh) {
  27179. this.onBindObservable.notifyObservers(mesh);
  27180. }
  27181. if (this.disableDepthWrite) {
  27182. var engine = this._scene.getEngine();
  27183. this._cachedDepthWriteState = engine.getDepthWrite();
  27184. engine.setDepthWrite(false);
  27185. }
  27186. };
  27187. Material.prototype.unbind = function () {
  27188. this.onUnBindObservable.notifyObservers(this);
  27189. if (this.disableDepthWrite) {
  27190. var engine = this._scene.getEngine();
  27191. engine.setDepthWrite(this._cachedDepthWriteState);
  27192. }
  27193. };
  27194. Material.prototype.getActiveTextures = function () {
  27195. return [];
  27196. };
  27197. Material.prototype.hasTexture = function (texture) {
  27198. return false;
  27199. };
  27200. Material.prototype.clone = function (name) {
  27201. return null;
  27202. };
  27203. Material.prototype.getBindedMeshes = function () {
  27204. var result = new Array();
  27205. for (var index = 0; index < this._scene.meshes.length; index++) {
  27206. var mesh = this._scene.meshes[index];
  27207. if (mesh.material === this) {
  27208. result.push(mesh);
  27209. }
  27210. }
  27211. return result;
  27212. };
  27213. /**
  27214. * Force shader compilation including textures ready check
  27215. */
  27216. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27217. var _this = this;
  27218. var subMesh = new BABYLON.BaseSubMesh();
  27219. var scene = this.getScene();
  27220. var engine = scene.getEngine();
  27221. var checkReady = function () {
  27222. if (!_this._scene || !_this._scene.getEngine()) {
  27223. return;
  27224. }
  27225. if (subMesh._materialDefines) {
  27226. subMesh._materialDefines._renderId = -1;
  27227. }
  27228. var alphaTestState = engine.getAlphaTesting();
  27229. var clipPlaneState = scene.clipPlane;
  27230. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27231. if (options && options.clipPlane) {
  27232. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27233. }
  27234. if (_this.storeEffectOnSubMeshes) {
  27235. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27236. if (onCompiled) {
  27237. onCompiled(_this);
  27238. }
  27239. }
  27240. else {
  27241. setTimeout(checkReady, 16);
  27242. }
  27243. }
  27244. else {
  27245. if (_this.isReady(mesh)) {
  27246. if (onCompiled) {
  27247. onCompiled(_this);
  27248. }
  27249. }
  27250. else {
  27251. setTimeout(checkReady, 16);
  27252. }
  27253. }
  27254. engine.setAlphaTesting(alphaTestState);
  27255. if (options && options.clipPlane) {
  27256. scene.clipPlane = clipPlaneState;
  27257. }
  27258. };
  27259. checkReady();
  27260. };
  27261. Material.prototype.markAsDirty = function (flag) {
  27262. if (flag & Material.TextureDirtyFlag) {
  27263. this._markAllSubMeshesAsTexturesDirty();
  27264. }
  27265. if (flag & Material.LightDirtyFlag) {
  27266. this._markAllSubMeshesAsLightsDirty();
  27267. }
  27268. if (flag & Material.FresnelDirtyFlag) {
  27269. this._markAllSubMeshesAsFresnelDirty();
  27270. }
  27271. if (flag & Material.AttributesDirtyFlag) {
  27272. this._markAllSubMeshesAsAttributesDirty();
  27273. }
  27274. if (flag & Material.MiscDirtyFlag) {
  27275. this._markAllSubMeshesAsMiscDirty();
  27276. }
  27277. this.getScene().resetCachedMaterial();
  27278. };
  27279. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27280. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27281. var mesh = _a[_i];
  27282. if (!mesh.subMeshes) {
  27283. continue;
  27284. }
  27285. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27286. var subMesh = _c[_b];
  27287. if (subMesh.getMaterial() !== this) {
  27288. continue;
  27289. }
  27290. if (!subMesh._materialDefines) {
  27291. continue;
  27292. }
  27293. func(subMesh._materialDefines);
  27294. }
  27295. }
  27296. };
  27297. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27298. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27299. };
  27300. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27301. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27302. };
  27303. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27304. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27305. };
  27306. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27307. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27308. };
  27309. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27310. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27311. };
  27312. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27313. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27314. };
  27315. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27316. // Animations
  27317. this.getScene().stopAnimation(this);
  27318. // Remove from scene
  27319. var index = this._scene.materials.indexOf(this);
  27320. if (index >= 0) {
  27321. this._scene.materials.splice(index, 1);
  27322. }
  27323. // Remove from meshes
  27324. for (index = 0; index < this._scene.meshes.length; index++) {
  27325. var mesh = this._scene.meshes[index];
  27326. if (mesh.material === this) {
  27327. mesh.material = null;
  27328. if (mesh.geometry) {
  27329. var geometry = (mesh.geometry);
  27330. if (this.storeEffectOnSubMeshes) {
  27331. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27332. var subMesh = _a[_i];
  27333. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27334. if (forceDisposeEffect && subMesh._materialEffect) {
  27335. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27336. }
  27337. }
  27338. }
  27339. else {
  27340. geometry._releaseVertexArrayObject(this._effect);
  27341. }
  27342. }
  27343. }
  27344. }
  27345. this._uniformBuffer.dispose();
  27346. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27347. if (forceDisposeEffect && this._effect) {
  27348. if (!this.storeEffectOnSubMeshes) {
  27349. this._scene.getEngine()._releaseEffect(this._effect);
  27350. }
  27351. this._effect = null;
  27352. }
  27353. // Callback
  27354. this.onDisposeObservable.notifyObservers(this);
  27355. this.onDisposeObservable.clear();
  27356. this.onBindObservable.clear();
  27357. this.onUnBindObservable.clear();
  27358. };
  27359. Material.prototype.serialize = function () {
  27360. return BABYLON.SerializationHelper.Serialize(this);
  27361. };
  27362. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27363. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27364. multiMaterial.id = parsedMultiMaterial.id;
  27365. if (BABYLON.Tags) {
  27366. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27367. }
  27368. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27369. var subMatId = parsedMultiMaterial.materials[matIndex];
  27370. if (subMatId) {
  27371. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27372. }
  27373. else {
  27374. multiMaterial.subMaterials.push(null);
  27375. }
  27376. }
  27377. return multiMaterial;
  27378. };
  27379. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27380. if (!parsedMaterial.customType) {
  27381. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27382. }
  27383. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27384. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27385. if (!BABYLON.LegacyPBRMaterial) {
  27386. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27387. return;
  27388. }
  27389. }
  27390. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27391. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27392. ;
  27393. };
  27394. Material._TriangleFillMode = 0;
  27395. Material._WireFrameFillMode = 1;
  27396. Material._PointFillMode = 2;
  27397. Material._ClockWiseSideOrientation = 0;
  27398. Material._CounterClockWiseSideOrientation = 1;
  27399. Material._TextureDirtyFlag = 1;
  27400. Material._LightDirtyFlag = 2;
  27401. Material._FresnelDirtyFlag = 4;
  27402. Material._AttributesDirtyFlag = 8;
  27403. Material._MiscDirtyFlag = 16;
  27404. __decorate([
  27405. BABYLON.serialize()
  27406. ], Material.prototype, "id", void 0);
  27407. __decorate([
  27408. BABYLON.serialize()
  27409. ], Material.prototype, "name", void 0);
  27410. __decorate([
  27411. BABYLON.serialize()
  27412. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27413. __decorate([
  27414. BABYLON.serialize()
  27415. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27416. __decorate([
  27417. BABYLON.serialize()
  27418. ], Material.prototype, "state", void 0);
  27419. __decorate([
  27420. BABYLON.serialize()
  27421. ], Material.prototype, "alpha", void 0);
  27422. __decorate([
  27423. BABYLON.serialize("backFaceCulling")
  27424. ], Material.prototype, "_backFaceCulling", void 0);
  27425. __decorate([
  27426. BABYLON.serialize()
  27427. ], Material.prototype, "sideOrientation", void 0);
  27428. __decorate([
  27429. BABYLON.serialize("alphaMode")
  27430. ], Material.prototype, "_alphaMode", void 0);
  27431. __decorate([
  27432. BABYLON.serialize()
  27433. ], Material.prototype, "_needDepthPrePass", void 0);
  27434. __decorate([
  27435. BABYLON.serialize()
  27436. ], Material.prototype, "disableDepthWrite", void 0);
  27437. __decorate([
  27438. BABYLON.serialize()
  27439. ], Material.prototype, "forceDepthWrite", void 0);
  27440. __decorate([
  27441. BABYLON.serialize()
  27442. ], Material.prototype, "separateCullingPass", void 0);
  27443. __decorate([
  27444. BABYLON.serialize("fogEnabled")
  27445. ], Material.prototype, "_fogEnabled", void 0);
  27446. __decorate([
  27447. BABYLON.serialize()
  27448. ], Material.prototype, "pointSize", void 0);
  27449. __decorate([
  27450. BABYLON.serialize()
  27451. ], Material.prototype, "zOffset", void 0);
  27452. __decorate([
  27453. BABYLON.serialize()
  27454. ], Material.prototype, "wireframe", null);
  27455. __decorate([
  27456. BABYLON.serialize()
  27457. ], Material.prototype, "pointsCloud", null);
  27458. __decorate([
  27459. BABYLON.serialize()
  27460. ], Material.prototype, "fillMode", null);
  27461. return Material;
  27462. }());
  27463. BABYLON.Material = Material;
  27464. })(BABYLON || (BABYLON = {}));
  27465. //# sourceMappingURL=babylon.material.js.map
  27466. var BABYLON;
  27467. (function (BABYLON) {
  27468. var UniformBuffer = /** @class */ (function () {
  27469. /**
  27470. * Uniform buffer objects.
  27471. *
  27472. * Handles blocks of uniform on the GPU.
  27473. *
  27474. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27475. *
  27476. * For more information, please refer to :
  27477. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27478. */
  27479. function UniformBuffer(engine, data, dynamic) {
  27480. this._engine = engine;
  27481. this._noUBO = !engine.supportsUniformBuffers;
  27482. this._dynamic = dynamic;
  27483. this._data = data || [];
  27484. this._uniformLocations = {};
  27485. this._uniformSizes = {};
  27486. this._uniformLocationPointer = 0;
  27487. this._needSync = false;
  27488. if (this._noUBO) {
  27489. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27490. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27491. this.updateFloat = this._updateFloatForEffect;
  27492. this.updateFloat2 = this._updateFloat2ForEffect;
  27493. this.updateFloat3 = this._updateFloat3ForEffect;
  27494. this.updateFloat4 = this._updateFloat4ForEffect;
  27495. this.updateMatrix = this._updateMatrixForEffect;
  27496. this.updateVector3 = this._updateVector3ForEffect;
  27497. this.updateVector4 = this._updateVector4ForEffect;
  27498. this.updateColor3 = this._updateColor3ForEffect;
  27499. this.updateColor4 = this._updateColor4ForEffect;
  27500. }
  27501. else {
  27502. this._engine._uniformBuffers.push(this);
  27503. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27504. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27505. this.updateFloat = this._updateFloatForUniform;
  27506. this.updateFloat2 = this._updateFloat2ForUniform;
  27507. this.updateFloat3 = this._updateFloat3ForUniform;
  27508. this.updateFloat4 = this._updateFloat4ForUniform;
  27509. this.updateMatrix = this._updateMatrixForUniform;
  27510. this.updateVector3 = this._updateVector3ForUniform;
  27511. this.updateVector4 = this._updateVector4ForUniform;
  27512. this.updateColor3 = this._updateColor3ForUniform;
  27513. this.updateColor4 = this._updateColor4ForUniform;
  27514. }
  27515. }
  27516. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27517. // Properties
  27518. /**
  27519. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27520. * or just falling back on setUniformXXX calls.
  27521. */
  27522. get: function () {
  27523. return !this._noUBO;
  27524. },
  27525. enumerable: true,
  27526. configurable: true
  27527. });
  27528. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27529. /**
  27530. * Indicates if the WebGL underlying uniform buffer is in sync
  27531. * with the javascript cache data.
  27532. */
  27533. get: function () {
  27534. return !this._needSync;
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. /**
  27540. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27541. * Also, a dynamic UniformBuffer will disable cache verification and always
  27542. * update the underlying WebGL uniform buffer to the GPU.
  27543. */
  27544. UniformBuffer.prototype.isDynamic = function () {
  27545. return this._dynamic !== undefined;
  27546. };
  27547. /**
  27548. * The data cache on JS side.
  27549. */
  27550. UniformBuffer.prototype.getData = function () {
  27551. return this._bufferData;
  27552. };
  27553. /**
  27554. * The underlying WebGL Uniform buffer.
  27555. */
  27556. UniformBuffer.prototype.getBuffer = function () {
  27557. return this._buffer;
  27558. };
  27559. /**
  27560. * std140 layout specifies how to align data within an UBO structure.
  27561. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27562. * for specs.
  27563. */
  27564. UniformBuffer.prototype._fillAlignment = function (size) {
  27565. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27566. // and 4x4 matrices
  27567. // TODO : change if other types are used
  27568. var alignment;
  27569. if (size <= 2) {
  27570. alignment = size;
  27571. }
  27572. else {
  27573. alignment = 4;
  27574. }
  27575. if ((this._uniformLocationPointer % alignment) !== 0) {
  27576. var oldPointer = this._uniformLocationPointer;
  27577. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27578. var diff = this._uniformLocationPointer - oldPointer;
  27579. for (var i = 0; i < diff; i++) {
  27580. this._data.push(0);
  27581. }
  27582. }
  27583. };
  27584. /**
  27585. * Adds an uniform in the buffer.
  27586. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27587. * for the layout to be correct !
  27588. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27589. * @param {number|number[]} size Data size, or data directly.
  27590. */
  27591. UniformBuffer.prototype.addUniform = function (name, size) {
  27592. if (this._noUBO) {
  27593. return;
  27594. }
  27595. if (this._uniformLocations[name] !== undefined) {
  27596. // Already existing uniform
  27597. return;
  27598. }
  27599. // This function must be called in the order of the shader layout !
  27600. // size can be the size of the uniform, or data directly
  27601. var data;
  27602. if (size instanceof Array) {
  27603. data = size;
  27604. size = data.length;
  27605. }
  27606. else {
  27607. size = size;
  27608. data = [];
  27609. // Fill with zeros
  27610. for (var i = 0; i < size; i++) {
  27611. data.push(0);
  27612. }
  27613. }
  27614. this._fillAlignment(size);
  27615. this._uniformSizes[name] = size;
  27616. this._uniformLocations[name] = this._uniformLocationPointer;
  27617. this._uniformLocationPointer += size;
  27618. for (var i = 0; i < size; i++) {
  27619. this._data.push(data[i]);
  27620. }
  27621. this._needSync = true;
  27622. };
  27623. /**
  27624. * Wrapper for addUniform.
  27625. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27626. * @param {Matrix} mat A 4x4 matrix.
  27627. */
  27628. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27629. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27630. };
  27631. /**
  27632. * Wrapper for addUniform.
  27633. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27634. * @param {number} x
  27635. * @param {number} y
  27636. */
  27637. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27638. var temp = [x, y];
  27639. this.addUniform(name, temp);
  27640. };
  27641. /**
  27642. * Wrapper for addUniform.
  27643. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27644. * @param {number} x
  27645. * @param {number} y
  27646. * @param {number} z
  27647. */
  27648. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27649. var temp = [x, y, z];
  27650. this.addUniform(name, temp);
  27651. };
  27652. /**
  27653. * Wrapper for addUniform.
  27654. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27655. * @param {Color3} color
  27656. */
  27657. UniformBuffer.prototype.addColor3 = function (name, color) {
  27658. var temp = new Array();
  27659. color.toArray(temp);
  27660. this.addUniform(name, temp);
  27661. };
  27662. /**
  27663. * Wrapper for addUniform.
  27664. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27665. * @param {Color3} color
  27666. * @param {number} alpha
  27667. */
  27668. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27669. var temp = new Array();
  27670. color.toArray(temp);
  27671. temp.push(alpha);
  27672. this.addUniform(name, temp);
  27673. };
  27674. /**
  27675. * Wrapper for addUniform.
  27676. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27677. * @param {Vector3} vector
  27678. */
  27679. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27680. var temp = new Array();
  27681. vector.toArray(temp);
  27682. this.addUniform(name, temp);
  27683. };
  27684. /**
  27685. * Wrapper for addUniform.
  27686. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27687. */
  27688. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27689. this.addUniform(name, 12);
  27690. };
  27691. /**
  27692. * Wrapper for addUniform.
  27693. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27694. */
  27695. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27696. this.addUniform(name, 8);
  27697. };
  27698. /**
  27699. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27700. */
  27701. UniformBuffer.prototype.create = function () {
  27702. if (this._noUBO) {
  27703. return;
  27704. }
  27705. if (this._buffer) {
  27706. return; // nothing to do
  27707. }
  27708. // See spec, alignment must be filled as a vec4
  27709. this._fillAlignment(4);
  27710. this._bufferData = new Float32Array(this._data);
  27711. this._rebuild();
  27712. this._needSync = true;
  27713. };
  27714. UniformBuffer.prototype._rebuild = function () {
  27715. if (this._noUBO) {
  27716. return;
  27717. }
  27718. if (this._dynamic) {
  27719. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27720. }
  27721. else {
  27722. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27723. }
  27724. };
  27725. /**
  27726. * Updates the WebGL Uniform Buffer on the GPU.
  27727. * If the `dynamic` flag is set to true, no cache comparison is done.
  27728. * Otherwise, the buffer will be updated only if the cache differs.
  27729. */
  27730. UniformBuffer.prototype.update = function () {
  27731. if (!this._buffer) {
  27732. this.create();
  27733. return;
  27734. }
  27735. if (!this._dynamic && !this._needSync) {
  27736. return;
  27737. }
  27738. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27739. this._needSync = false;
  27740. };
  27741. /**
  27742. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27743. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27744. * @param {number[]|Float32Array} data Flattened data
  27745. * @param {number} size Size of the data.
  27746. */
  27747. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27748. var location = this._uniformLocations[uniformName];
  27749. if (location === undefined) {
  27750. if (this._buffer) {
  27751. // Cannot add an uniform if the buffer is already created
  27752. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27753. return;
  27754. }
  27755. this.addUniform(uniformName, size);
  27756. location = this._uniformLocations[uniformName];
  27757. }
  27758. if (!this._buffer) {
  27759. this.create();
  27760. }
  27761. if (!this._dynamic) {
  27762. // Cache for static uniform buffers
  27763. var changed = false;
  27764. for (var i = 0; i < size; i++) {
  27765. if (this._bufferData[location + i] !== data[i]) {
  27766. changed = true;
  27767. this._bufferData[location + i] = data[i];
  27768. }
  27769. }
  27770. this._needSync = this._needSync || changed;
  27771. }
  27772. else {
  27773. // No cache for dynamic
  27774. for (var i = 0; i < size; i++) {
  27775. this._bufferData[location + i] = data[i];
  27776. }
  27777. }
  27778. };
  27779. // Update methods
  27780. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27781. // To match std140, matrix must be realigned
  27782. for (var i = 0; i < 3; i++) {
  27783. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27784. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27785. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27786. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27787. }
  27788. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27789. };
  27790. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27791. this._currentEffect.setMatrix3x3(name, matrix);
  27792. };
  27793. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27794. this._currentEffect.setMatrix2x2(name, matrix);
  27795. };
  27796. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27797. // To match std140, matrix must be realigned
  27798. for (var i = 0; i < 2; i++) {
  27799. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27800. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27801. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27802. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27803. }
  27804. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27805. };
  27806. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27807. this._currentEffect.setFloat(name, x);
  27808. };
  27809. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27810. UniformBuffer._tempBuffer[0] = x;
  27811. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27812. };
  27813. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27814. if (suffix === void 0) { suffix = ""; }
  27815. this._currentEffect.setFloat2(name + suffix, x, y);
  27816. };
  27817. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27818. if (suffix === void 0) { suffix = ""; }
  27819. UniformBuffer._tempBuffer[0] = x;
  27820. UniformBuffer._tempBuffer[1] = y;
  27821. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27822. };
  27823. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27824. if (suffix === void 0) { suffix = ""; }
  27825. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27826. };
  27827. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27828. if (suffix === void 0) { suffix = ""; }
  27829. UniformBuffer._tempBuffer[0] = x;
  27830. UniformBuffer._tempBuffer[1] = y;
  27831. UniformBuffer._tempBuffer[2] = z;
  27832. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27833. };
  27834. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27835. if (suffix === void 0) { suffix = ""; }
  27836. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27837. };
  27838. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27839. if (suffix === void 0) { suffix = ""; }
  27840. UniformBuffer._tempBuffer[0] = x;
  27841. UniformBuffer._tempBuffer[1] = y;
  27842. UniformBuffer._tempBuffer[2] = z;
  27843. UniformBuffer._tempBuffer[3] = w;
  27844. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27845. };
  27846. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27847. this._currentEffect.setMatrix(name, mat);
  27848. };
  27849. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27850. this.updateUniform(name, mat.toArray(), 16);
  27851. };
  27852. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27853. this._currentEffect.setVector3(name, vector);
  27854. };
  27855. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27856. vector.toArray(UniformBuffer._tempBuffer);
  27857. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27858. };
  27859. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27860. this._currentEffect.setVector4(name, vector);
  27861. };
  27862. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27863. vector.toArray(UniformBuffer._tempBuffer);
  27864. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27865. };
  27866. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27867. if (suffix === void 0) { suffix = ""; }
  27868. this._currentEffect.setColor3(name + suffix, color);
  27869. };
  27870. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27871. if (suffix === void 0) { suffix = ""; }
  27872. color.toArray(UniformBuffer._tempBuffer);
  27873. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27874. };
  27875. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27876. if (suffix === void 0) { suffix = ""; }
  27877. this._currentEffect.setColor4(name + suffix, color, alpha);
  27878. };
  27879. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27880. if (suffix === void 0) { suffix = ""; }
  27881. color.toArray(UniformBuffer._tempBuffer);
  27882. UniformBuffer._tempBuffer[3] = alpha;
  27883. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27884. };
  27885. /**
  27886. * Sets a sampler uniform on the effect.
  27887. * @param {string} name Name of the sampler.
  27888. * @param {Texture} texture
  27889. */
  27890. UniformBuffer.prototype.setTexture = function (name, texture) {
  27891. this._currentEffect.setTexture(name, texture);
  27892. };
  27893. /**
  27894. * Directly updates the value of the uniform in the cache AND on the GPU.
  27895. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27896. * @param {number[]|Float32Array} data Flattened data
  27897. */
  27898. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27899. this.updateUniform(uniformName, data, data.length);
  27900. this.update();
  27901. };
  27902. /**
  27903. * Binds this uniform buffer to an effect.
  27904. * @param {Effect} effect
  27905. * @param {string} name Name of the uniform block in the shader.
  27906. */
  27907. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27908. this._currentEffect = effect;
  27909. if (this._noUBO || !this._buffer) {
  27910. return;
  27911. }
  27912. effect.bindUniformBuffer(this._buffer, name);
  27913. };
  27914. /**
  27915. * Disposes the uniform buffer.
  27916. */
  27917. UniformBuffer.prototype.dispose = function () {
  27918. if (this._noUBO) {
  27919. return;
  27920. }
  27921. var index = this._engine._uniformBuffers.indexOf(this);
  27922. if (index !== -1) {
  27923. this._engine._uniformBuffers.splice(index, 1);
  27924. }
  27925. if (!this._buffer) {
  27926. return;
  27927. }
  27928. if (this._engine._releaseBuffer(this._buffer)) {
  27929. this._buffer = null;
  27930. }
  27931. };
  27932. // Pool for avoiding memory leaks
  27933. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27934. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27935. return UniformBuffer;
  27936. }());
  27937. BABYLON.UniformBuffer = UniformBuffer;
  27938. })(BABYLON || (BABYLON = {}));
  27939. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27940. var BABYLON;
  27941. (function (BABYLON) {
  27942. var PushMaterial = /** @class */ (function (_super) {
  27943. __extends(PushMaterial, _super);
  27944. function PushMaterial(name, scene) {
  27945. var _this = _super.call(this, name, scene) || this;
  27946. _this.storeEffectOnSubMeshes = true;
  27947. return _this;
  27948. }
  27949. PushMaterial.prototype.getEffect = function () {
  27950. return this._activeEffect;
  27951. };
  27952. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27953. if (!mesh) {
  27954. return false;
  27955. }
  27956. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27957. return true;
  27958. }
  27959. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27960. };
  27961. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27962. this._activeEffect.setMatrix("world", world);
  27963. };
  27964. PushMaterial.prototype.bind = function (world, mesh) {
  27965. if (!mesh) {
  27966. return;
  27967. }
  27968. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27969. };
  27970. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27971. if (effect === void 0) { effect = null; }
  27972. _super.prototype._afterBind.call(this, mesh);
  27973. this.getScene()._cachedEffect = effect;
  27974. };
  27975. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27976. if (visibility === void 0) { visibility = 1; }
  27977. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27978. };
  27979. return PushMaterial;
  27980. }(BABYLON.Material));
  27981. BABYLON.PushMaterial = PushMaterial;
  27982. })(BABYLON || (BABYLON = {}));
  27983. //# sourceMappingURL=babylon.pushMaterial.js.map
  27984. var BABYLON;
  27985. (function (BABYLON) {
  27986. var VertexData = /** @class */ (function () {
  27987. function VertexData() {
  27988. }
  27989. VertexData.prototype.set = function (data, kind) {
  27990. switch (kind) {
  27991. case BABYLON.VertexBuffer.PositionKind:
  27992. this.positions = data;
  27993. break;
  27994. case BABYLON.VertexBuffer.NormalKind:
  27995. this.normals = data;
  27996. break;
  27997. case BABYLON.VertexBuffer.TangentKind:
  27998. this.tangents = data;
  27999. break;
  28000. case BABYLON.VertexBuffer.UVKind:
  28001. this.uvs = data;
  28002. break;
  28003. case BABYLON.VertexBuffer.UV2Kind:
  28004. this.uvs2 = data;
  28005. break;
  28006. case BABYLON.VertexBuffer.UV3Kind:
  28007. this.uvs3 = data;
  28008. break;
  28009. case BABYLON.VertexBuffer.UV4Kind:
  28010. this.uvs4 = data;
  28011. break;
  28012. case BABYLON.VertexBuffer.UV5Kind:
  28013. this.uvs5 = data;
  28014. break;
  28015. case BABYLON.VertexBuffer.UV6Kind:
  28016. this.uvs6 = data;
  28017. break;
  28018. case BABYLON.VertexBuffer.ColorKind:
  28019. this.colors = data;
  28020. break;
  28021. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28022. this.matricesIndices = data;
  28023. break;
  28024. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28025. this.matricesWeights = data;
  28026. break;
  28027. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28028. this.matricesIndicesExtra = data;
  28029. break;
  28030. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28031. this.matricesWeightsExtra = data;
  28032. break;
  28033. }
  28034. };
  28035. /**
  28036. * Associates the vertexData to the passed Mesh.
  28037. * Sets it as updatable or not (default `false`).
  28038. * Returns the VertexData.
  28039. */
  28040. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28041. this._applyTo(mesh, updatable);
  28042. return this;
  28043. };
  28044. /**
  28045. * Associates the vertexData to the passed Geometry.
  28046. * Sets it as updatable or not (default `false`).
  28047. * Returns the VertexData.
  28048. */
  28049. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28050. this._applyTo(geometry, updatable);
  28051. return this;
  28052. };
  28053. /**
  28054. * Updates the associated mesh.
  28055. * Returns the VertexData.
  28056. */
  28057. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28058. this._update(mesh);
  28059. return this;
  28060. };
  28061. /**
  28062. * Updates the associated geometry.
  28063. * Returns the VertexData.
  28064. */
  28065. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28066. this._update(geometry);
  28067. return this;
  28068. };
  28069. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28070. if (updatable === void 0) { updatable = false; }
  28071. if (this.positions) {
  28072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28073. }
  28074. if (this.normals) {
  28075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28076. }
  28077. if (this.tangents) {
  28078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28079. }
  28080. if (this.uvs) {
  28081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28082. }
  28083. if (this.uvs2) {
  28084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28085. }
  28086. if (this.uvs3) {
  28087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28088. }
  28089. if (this.uvs4) {
  28090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28091. }
  28092. if (this.uvs5) {
  28093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28094. }
  28095. if (this.uvs6) {
  28096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28097. }
  28098. if (this.colors) {
  28099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28100. }
  28101. if (this.matricesIndices) {
  28102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28103. }
  28104. if (this.matricesWeights) {
  28105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28106. }
  28107. if (this.matricesIndicesExtra) {
  28108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28109. }
  28110. if (this.matricesWeightsExtra) {
  28111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28112. }
  28113. if (this.indices) {
  28114. meshOrGeometry.setIndices(this.indices, null, updatable);
  28115. }
  28116. return this;
  28117. };
  28118. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28119. if (this.positions) {
  28120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28121. }
  28122. if (this.normals) {
  28123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28124. }
  28125. if (this.tangents) {
  28126. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28127. }
  28128. if (this.uvs) {
  28129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28130. }
  28131. if (this.uvs2) {
  28132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28133. }
  28134. if (this.uvs3) {
  28135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28136. }
  28137. if (this.uvs4) {
  28138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28139. }
  28140. if (this.uvs5) {
  28141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28142. }
  28143. if (this.uvs6) {
  28144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28145. }
  28146. if (this.colors) {
  28147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28148. }
  28149. if (this.matricesIndices) {
  28150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28151. }
  28152. if (this.matricesWeights) {
  28153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28154. }
  28155. if (this.matricesIndicesExtra) {
  28156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28157. }
  28158. if (this.matricesWeightsExtra) {
  28159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28160. }
  28161. if (this.indices) {
  28162. meshOrGeometry.setIndices(this.indices, null);
  28163. }
  28164. return this;
  28165. };
  28166. /**
  28167. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28168. * Returns the VertexData.
  28169. */
  28170. VertexData.prototype.transform = function (matrix) {
  28171. var transformed = BABYLON.Vector3.Zero();
  28172. var index;
  28173. if (this.positions) {
  28174. var position = BABYLON.Vector3.Zero();
  28175. for (index = 0; index < this.positions.length; index += 3) {
  28176. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28177. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28178. this.positions[index] = transformed.x;
  28179. this.positions[index + 1] = transformed.y;
  28180. this.positions[index + 2] = transformed.z;
  28181. }
  28182. }
  28183. if (this.normals) {
  28184. var normal = BABYLON.Vector3.Zero();
  28185. for (index = 0; index < this.normals.length; index += 3) {
  28186. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28187. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28188. this.normals[index] = transformed.x;
  28189. this.normals[index + 1] = transformed.y;
  28190. this.normals[index + 2] = transformed.z;
  28191. }
  28192. }
  28193. if (this.tangents) {
  28194. var tangent = BABYLON.Vector4.Zero();
  28195. var tangentTransformed = BABYLON.Vector4.Zero();
  28196. for (index = 0; index < this.tangents.length; index += 4) {
  28197. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28198. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28199. this.tangents[index] = tangentTransformed.x;
  28200. this.tangents[index + 1] = tangentTransformed.y;
  28201. this.tangents[index + 2] = tangentTransformed.z;
  28202. this.tangents[index + 3] = tangentTransformed.w;
  28203. }
  28204. }
  28205. return this;
  28206. };
  28207. /**
  28208. * Merges the passed VertexData into the current one.
  28209. * Returns the modified VertexData.
  28210. */
  28211. VertexData.prototype.merge = function (other, options) {
  28212. options = options || {};
  28213. if (other.indices) {
  28214. if (!this.indices) {
  28215. this.indices = [];
  28216. }
  28217. var offset = this.positions ? this.positions.length / 3 : 0;
  28218. for (var index = 0; index < other.indices.length; index++) {
  28219. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28220. this.indices.push(other.indices[index] + offset);
  28221. }
  28222. }
  28223. this.positions = this._mergeElement(this.positions, other.positions);
  28224. if (!this.positions) {
  28225. return this;
  28226. }
  28227. var count = this.positions.length / 3;
  28228. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28229. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28230. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28231. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28232. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28233. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28234. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28235. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28236. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28237. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28238. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28239. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28240. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28241. return this;
  28242. };
  28243. VertexData.prototype._mergeElement = function (source, other, length) {
  28244. if (length === void 0) { length = 0; }
  28245. if (!other && !source) {
  28246. return null;
  28247. }
  28248. if (!other) {
  28249. return this._mergeElement(source, new Float32Array(source.length), length);
  28250. }
  28251. if (!source) {
  28252. if (length === 0 || length === other.length) {
  28253. return other;
  28254. }
  28255. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28256. }
  28257. var len = other.length + source.length;
  28258. var isSrcTypedArray = source instanceof Float32Array;
  28259. var isOthTypedArray = other instanceof Float32Array;
  28260. // use non-loop method when the source is Float32Array
  28261. if (isSrcTypedArray) {
  28262. var ret32 = new Float32Array(len);
  28263. ret32.set(source);
  28264. ret32.set(other, source.length);
  28265. return ret32;
  28266. // source is number[], when other is also use concat
  28267. }
  28268. else if (!isOthTypedArray) {
  28269. return source.concat(other);
  28270. // source is a number[], but other is a Float32Array, loop required
  28271. }
  28272. else {
  28273. var ret = source.slice(0); // copy source to a separate array
  28274. for (var i = 0, len = other.length; i < len; i++) {
  28275. ret.push(other[i]);
  28276. }
  28277. return ret;
  28278. }
  28279. };
  28280. /**
  28281. * Serializes the VertexData.
  28282. * Returns a serialized object.
  28283. */
  28284. VertexData.prototype.serialize = function () {
  28285. var serializationObject = this.serialize();
  28286. if (this.positions) {
  28287. serializationObject.positions = this.positions;
  28288. }
  28289. if (this.normals) {
  28290. serializationObject.normals = this.normals;
  28291. }
  28292. if (this.tangents) {
  28293. serializationObject.tangents = this.tangents;
  28294. }
  28295. if (this.uvs) {
  28296. serializationObject.uvs = this.uvs;
  28297. }
  28298. if (this.uvs2) {
  28299. serializationObject.uvs2 = this.uvs2;
  28300. }
  28301. if (this.uvs3) {
  28302. serializationObject.uvs3 = this.uvs3;
  28303. }
  28304. if (this.uvs4) {
  28305. serializationObject.uvs4 = this.uvs4;
  28306. }
  28307. if (this.uvs5) {
  28308. serializationObject.uvs5 = this.uvs5;
  28309. }
  28310. if (this.uvs6) {
  28311. serializationObject.uvs6 = this.uvs6;
  28312. }
  28313. if (this.colors) {
  28314. serializationObject.colors = this.colors;
  28315. }
  28316. if (this.matricesIndices) {
  28317. serializationObject.matricesIndices = this.matricesIndices;
  28318. serializationObject.matricesIndices._isExpanded = true;
  28319. }
  28320. if (this.matricesWeights) {
  28321. serializationObject.matricesWeights = this.matricesWeights;
  28322. }
  28323. if (this.matricesIndicesExtra) {
  28324. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28325. serializationObject.matricesIndicesExtra._isExpanded = true;
  28326. }
  28327. if (this.matricesWeightsExtra) {
  28328. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28329. }
  28330. serializationObject.indices = this.indices;
  28331. return serializationObject;
  28332. };
  28333. // Statics
  28334. /**
  28335. * Returns the object VertexData associated to the passed mesh.
  28336. */
  28337. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28338. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28339. };
  28340. /**
  28341. * Returns the object VertexData associated to the passed geometry.
  28342. */
  28343. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28344. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28345. };
  28346. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28347. var result = new VertexData();
  28348. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28349. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28350. }
  28351. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28352. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28353. }
  28354. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28355. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28356. }
  28357. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28358. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28359. }
  28360. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28361. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28362. }
  28363. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28364. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28365. }
  28366. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28367. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28368. }
  28369. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28370. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28371. }
  28372. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28373. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28374. }
  28375. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28376. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28377. }
  28378. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28379. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28380. }
  28381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28382. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28383. }
  28384. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28385. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28386. }
  28387. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28388. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28389. }
  28390. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28391. return result;
  28392. };
  28393. /**
  28394. * Creates the vertexData of the Ribbon.
  28395. */
  28396. VertexData.CreateRibbon = function (options) {
  28397. var pathArray = options.pathArray;
  28398. var closeArray = options.closeArray || false;
  28399. var closePath = options.closePath || false;
  28400. var invertUV = options.invertUV || false;
  28401. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28402. var offset = options.offset || defaultOffset;
  28403. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28404. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28405. var customUV = options.uvs;
  28406. var customColors = options.colors;
  28407. var positions = [];
  28408. var indices = [];
  28409. var normals = [];
  28410. var uvs = [];
  28411. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28412. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28413. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28414. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28415. var minlg; // minimal length among all paths from pathArray
  28416. var lg = []; // array of path lengths : nb of vertex per path
  28417. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28418. var p; // path iterator
  28419. var i; // point iterator
  28420. var j; // point iterator
  28421. // if single path in pathArray
  28422. if (pathArray.length < 2) {
  28423. var ar1 = [];
  28424. var ar2 = [];
  28425. for (i = 0; i < pathArray[0].length - offset; i++) {
  28426. ar1.push(pathArray[0][i]);
  28427. ar2.push(pathArray[0][i + offset]);
  28428. }
  28429. pathArray = [ar1, ar2];
  28430. }
  28431. // positions and horizontal distances (u)
  28432. var idc = 0;
  28433. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28434. var path;
  28435. var l;
  28436. minlg = pathArray[0].length;
  28437. var vectlg;
  28438. var dist;
  28439. for (p = 0; p < pathArray.length; p++) {
  28440. uTotalDistance[p] = 0;
  28441. us[p] = [0];
  28442. path = pathArray[p];
  28443. l = path.length;
  28444. minlg = (minlg < l) ? minlg : l;
  28445. j = 0;
  28446. while (j < l) {
  28447. positions.push(path[j].x, path[j].y, path[j].z);
  28448. if (j > 0) {
  28449. vectlg = path[j].subtract(path[j - 1]).length();
  28450. dist = vectlg + uTotalDistance[p];
  28451. us[p].push(dist);
  28452. uTotalDistance[p] = dist;
  28453. }
  28454. j++;
  28455. }
  28456. if (closePath) {
  28457. j--;
  28458. positions.push(path[0].x, path[0].y, path[0].z);
  28459. vectlg = path[j].subtract(path[0]).length();
  28460. dist = vectlg + uTotalDistance[p];
  28461. us[p].push(dist);
  28462. uTotalDistance[p] = dist;
  28463. }
  28464. lg[p] = l + closePathCorr;
  28465. idx[p] = idc;
  28466. idc += (l + closePathCorr);
  28467. }
  28468. // vertical distances (v)
  28469. var path1;
  28470. var path2;
  28471. var vertex1 = null;
  28472. var vertex2 = null;
  28473. for (i = 0; i < minlg + closePathCorr; i++) {
  28474. vTotalDistance[i] = 0;
  28475. vs[i] = [0];
  28476. for (p = 0; p < pathArray.length - 1; p++) {
  28477. path1 = pathArray[p];
  28478. path2 = pathArray[p + 1];
  28479. if (i === minlg) {
  28480. vertex1 = path1[0];
  28481. vertex2 = path2[0];
  28482. }
  28483. else {
  28484. vertex1 = path1[i];
  28485. vertex2 = path2[i];
  28486. }
  28487. vectlg = vertex2.subtract(vertex1).length();
  28488. dist = vectlg + vTotalDistance[i];
  28489. vs[i].push(dist);
  28490. vTotalDistance[i] = dist;
  28491. }
  28492. if (closeArray && vertex2 && vertex1) {
  28493. path1 = pathArray[p];
  28494. path2 = pathArray[0];
  28495. if (i === minlg) {
  28496. vertex2 = path2[0];
  28497. }
  28498. vectlg = vertex2.subtract(vertex1).length();
  28499. dist = vectlg + vTotalDistance[i];
  28500. vTotalDistance[i] = dist;
  28501. }
  28502. }
  28503. // uvs
  28504. var u;
  28505. var v;
  28506. if (customUV) {
  28507. for (p = 0; p < customUV.length; p++) {
  28508. uvs.push(customUV[p].x, customUV[p].y);
  28509. }
  28510. }
  28511. else {
  28512. for (p = 0; p < pathArray.length; p++) {
  28513. for (i = 0; i < minlg + closePathCorr; i++) {
  28514. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28515. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28516. if (invertUV) {
  28517. uvs.push(v, u);
  28518. }
  28519. else {
  28520. uvs.push(u, v);
  28521. }
  28522. }
  28523. }
  28524. }
  28525. // indices
  28526. p = 0; // path index
  28527. var pi = 0; // positions array index
  28528. var l1 = lg[p] - 1; // path1 length
  28529. var l2 = lg[p + 1] - 1; // path2 length
  28530. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28531. var shft = idx[1] - idx[0]; // shift
  28532. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28533. while (pi <= min && p < path1nb) {
  28534. // 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
  28535. indices.push(pi, pi + shft, pi + 1);
  28536. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28537. pi += 1;
  28538. if (pi === min) {
  28539. p++;
  28540. if (p === lg.length - 1) {
  28541. shft = idx[0] - idx[p];
  28542. l1 = lg[p] - 1;
  28543. l2 = lg[0] - 1;
  28544. }
  28545. else {
  28546. shft = idx[p + 1] - idx[p];
  28547. l1 = lg[p] - 1;
  28548. l2 = lg[p + 1] - 1;
  28549. }
  28550. pi = idx[p];
  28551. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28552. }
  28553. }
  28554. // normals
  28555. VertexData.ComputeNormals(positions, indices, normals);
  28556. if (closePath) {
  28557. var indexFirst = 0;
  28558. var indexLast = 0;
  28559. for (p = 0; p < pathArray.length; p++) {
  28560. indexFirst = idx[p] * 3;
  28561. if (p + 1 < pathArray.length) {
  28562. indexLast = (idx[p + 1] - 1) * 3;
  28563. }
  28564. else {
  28565. indexLast = normals.length - 3;
  28566. }
  28567. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28568. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28569. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28570. normals[indexLast] = normals[indexFirst];
  28571. normals[indexLast + 1] = normals[indexFirst + 1];
  28572. normals[indexLast + 2] = normals[indexFirst + 2];
  28573. }
  28574. }
  28575. // sides
  28576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28577. // Colors
  28578. var colors = null;
  28579. if (customColors) {
  28580. colors = new Float32Array(customColors.length * 4);
  28581. for (var c = 0; c < customColors.length; c++) {
  28582. colors[c * 4] = customColors[c].r;
  28583. colors[c * 4 + 1] = customColors[c].g;
  28584. colors[c * 4 + 2] = customColors[c].b;
  28585. colors[c * 4 + 3] = customColors[c].a;
  28586. }
  28587. }
  28588. // Result
  28589. var vertexData = new VertexData();
  28590. var positions32 = new Float32Array(positions);
  28591. var normals32 = new Float32Array(normals);
  28592. var uvs32 = new Float32Array(uvs);
  28593. vertexData.indices = indices;
  28594. vertexData.positions = positions32;
  28595. vertexData.normals = normals32;
  28596. vertexData.uvs = uvs32;
  28597. if (colors) {
  28598. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28599. }
  28600. if (closePath) {
  28601. vertexData._idx = idx;
  28602. }
  28603. return vertexData;
  28604. };
  28605. /**
  28606. * Creates the VertexData of the Box.
  28607. */
  28608. VertexData.CreateBox = function (options) {
  28609. var normalsSource = [
  28610. new BABYLON.Vector3(0, 0, 1),
  28611. new BABYLON.Vector3(0, 0, -1),
  28612. new BABYLON.Vector3(1, 0, 0),
  28613. new BABYLON.Vector3(-1, 0, 0),
  28614. new BABYLON.Vector3(0, 1, 0),
  28615. new BABYLON.Vector3(0, -1, 0)
  28616. ];
  28617. var indices = [];
  28618. var positions = [];
  28619. var normals = [];
  28620. var uvs = [];
  28621. var width = options.width || options.size || 1;
  28622. var height = options.height || options.size || 1;
  28623. var depth = options.depth || options.size || 1;
  28624. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28625. var faceUV = options.faceUV || new Array(6);
  28626. var faceColors = options.faceColors;
  28627. var colors = [];
  28628. // default face colors and UV if undefined
  28629. for (var f = 0; f < 6; f++) {
  28630. if (faceUV[f] === undefined) {
  28631. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28632. }
  28633. if (faceColors && faceColors[f] === undefined) {
  28634. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28635. }
  28636. }
  28637. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28638. // Create each face in turn.
  28639. for (var index = 0; index < normalsSource.length; index++) {
  28640. var normal = normalsSource[index];
  28641. // Get two vectors perpendicular to the face normal and to each other.
  28642. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28643. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28644. // Six indices (two triangles) per face.
  28645. var verticesLength = positions.length / 3;
  28646. indices.push(verticesLength);
  28647. indices.push(verticesLength + 1);
  28648. indices.push(verticesLength + 2);
  28649. indices.push(verticesLength);
  28650. indices.push(verticesLength + 2);
  28651. indices.push(verticesLength + 3);
  28652. // Four vertices per face.
  28653. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28654. positions.push(vertex.x, vertex.y, vertex.z);
  28655. normals.push(normal.x, normal.y, normal.z);
  28656. uvs.push(faceUV[index].z, faceUV[index].w);
  28657. if (faceColors) {
  28658. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28659. }
  28660. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28661. positions.push(vertex.x, vertex.y, vertex.z);
  28662. normals.push(normal.x, normal.y, normal.z);
  28663. uvs.push(faceUV[index].x, faceUV[index].w);
  28664. if (faceColors) {
  28665. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28666. }
  28667. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28668. positions.push(vertex.x, vertex.y, vertex.z);
  28669. normals.push(normal.x, normal.y, normal.z);
  28670. uvs.push(faceUV[index].x, faceUV[index].y);
  28671. if (faceColors) {
  28672. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28673. }
  28674. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28675. positions.push(vertex.x, vertex.y, vertex.z);
  28676. normals.push(normal.x, normal.y, normal.z);
  28677. uvs.push(faceUV[index].z, faceUV[index].y);
  28678. if (faceColors) {
  28679. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28680. }
  28681. }
  28682. // sides
  28683. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28684. // Result
  28685. var vertexData = new VertexData();
  28686. vertexData.indices = indices;
  28687. vertexData.positions = positions;
  28688. vertexData.normals = normals;
  28689. vertexData.uvs = uvs;
  28690. if (faceColors) {
  28691. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28692. vertexData.colors = totalColors;
  28693. }
  28694. return vertexData;
  28695. };
  28696. /**
  28697. * Creates the VertexData of the Sphere.
  28698. */
  28699. VertexData.CreateSphere = function (options) {
  28700. var segments = options.segments || 32;
  28701. var diameterX = options.diameterX || options.diameter || 1;
  28702. var diameterY = options.diameterY || options.diameter || 1;
  28703. var diameterZ = options.diameterZ || options.diameter || 1;
  28704. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28705. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28706. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28707. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28708. var totalZRotationSteps = 2 + segments;
  28709. var totalYRotationSteps = 2 * totalZRotationSteps;
  28710. var indices = [];
  28711. var positions = [];
  28712. var normals = [];
  28713. var uvs = [];
  28714. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28715. var normalizedZ = zRotationStep / totalZRotationSteps;
  28716. var angleZ = normalizedZ * Math.PI * slice;
  28717. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28718. var normalizedY = yRotationStep / totalYRotationSteps;
  28719. var angleY = normalizedY * Math.PI * 2 * arc;
  28720. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28721. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28722. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28723. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28724. var vertex = complete.multiply(radius);
  28725. var normal = complete.divide(radius).normalize();
  28726. positions.push(vertex.x, vertex.y, vertex.z);
  28727. normals.push(normal.x, normal.y, normal.z);
  28728. uvs.push(normalizedY, normalizedZ);
  28729. }
  28730. if (zRotationStep > 0) {
  28731. var verticesCount = positions.length / 3;
  28732. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28733. indices.push((firstIndex));
  28734. indices.push((firstIndex + 1));
  28735. indices.push(firstIndex + totalYRotationSteps + 1);
  28736. indices.push((firstIndex + totalYRotationSteps + 1));
  28737. indices.push((firstIndex + 1));
  28738. indices.push((firstIndex + totalYRotationSteps + 2));
  28739. }
  28740. }
  28741. }
  28742. // Sides
  28743. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28744. // Result
  28745. var vertexData = new VertexData();
  28746. vertexData.indices = indices;
  28747. vertexData.positions = positions;
  28748. vertexData.normals = normals;
  28749. vertexData.uvs = uvs;
  28750. return vertexData;
  28751. };
  28752. /**
  28753. * Creates the VertexData of the Cylinder or Cone.
  28754. */
  28755. VertexData.CreateCylinder = function (options) {
  28756. var height = options.height || 2;
  28757. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28758. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28759. var tessellation = options.tessellation || 24;
  28760. var subdivisions = options.subdivisions || 1;
  28761. var hasRings = options.hasRings ? true : false;
  28762. var enclose = options.enclose ? true : false;
  28763. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28764. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28765. var faceUV = options.faceUV || new Array(3);
  28766. var faceColors = options.faceColors;
  28767. // default face colors and UV if undefined
  28768. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28769. var ringNb = (hasRings) ? subdivisions : 1;
  28770. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28771. var f;
  28772. for (f = 0; f < surfaceNb; f++) {
  28773. if (faceColors && faceColors[f] === undefined) {
  28774. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28775. }
  28776. }
  28777. for (f = 0; f < surfaceNb; f++) {
  28778. if (faceUV && faceUV[f] === undefined) {
  28779. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28780. }
  28781. }
  28782. var indices = new Array();
  28783. var positions = new Array();
  28784. var normals = new Array();
  28785. var uvs = new Array();
  28786. var colors = new Array();
  28787. var angle_step = Math.PI * 2 * arc / tessellation;
  28788. var angle;
  28789. var h;
  28790. var radius;
  28791. var tan = (diameterBottom - diameterTop) / 2 / height;
  28792. var ringVertex = BABYLON.Vector3.Zero();
  28793. var ringNormal = BABYLON.Vector3.Zero();
  28794. var ringFirstVertex = BABYLON.Vector3.Zero();
  28795. var ringFirstNormal = BABYLON.Vector3.Zero();
  28796. var quadNormal = BABYLON.Vector3.Zero();
  28797. var Y = BABYLON.Axis.Y;
  28798. // positions, normals, uvs
  28799. var i;
  28800. var j;
  28801. var r;
  28802. var ringIdx = 1;
  28803. var s = 1; // surface index
  28804. var cs = 0;
  28805. var v = 0;
  28806. for (i = 0; i <= subdivisions; i++) {
  28807. h = i / subdivisions;
  28808. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28809. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28810. for (r = 0; r < ringIdx; r++) {
  28811. if (hasRings) {
  28812. s += r;
  28813. }
  28814. if (enclose) {
  28815. s += 2 * r;
  28816. }
  28817. for (j = 0; j <= tessellation; j++) {
  28818. angle = j * angle_step;
  28819. // position
  28820. ringVertex.x = Math.cos(-angle) * radius;
  28821. ringVertex.y = -height / 2 + h * height;
  28822. ringVertex.z = Math.sin(-angle) * radius;
  28823. // normal
  28824. if (diameterTop === 0 && i === subdivisions) {
  28825. // if no top cap, reuse former normals
  28826. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28827. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28828. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28829. }
  28830. else {
  28831. ringNormal.x = ringVertex.x;
  28832. ringNormal.z = ringVertex.z;
  28833. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28834. ringNormal.normalize();
  28835. }
  28836. // keep first ring vertex values for enclose
  28837. if (j === 0) {
  28838. ringFirstVertex.copyFrom(ringVertex);
  28839. ringFirstNormal.copyFrom(ringNormal);
  28840. }
  28841. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28842. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28843. if (hasRings) {
  28844. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28845. }
  28846. else {
  28847. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28848. }
  28849. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28850. if (faceColors) {
  28851. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28852. }
  28853. }
  28854. // if enclose, add four vertices and their dedicated normals
  28855. if (arc !== 1 && enclose) {
  28856. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28857. positions.push(0, ringVertex.y, 0);
  28858. positions.push(0, ringVertex.y, 0);
  28859. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28860. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28861. quadNormal.normalize();
  28862. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28863. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28864. quadNormal.normalize();
  28865. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28866. if (hasRings) {
  28867. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28868. }
  28869. else {
  28870. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28871. }
  28872. uvs.push(faceUV[s + 1].x, v);
  28873. uvs.push(faceUV[s + 1].z, v);
  28874. if (hasRings) {
  28875. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28876. }
  28877. else {
  28878. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28879. }
  28880. uvs.push(faceUV[s + 2].x, v);
  28881. uvs.push(faceUV[s + 2].z, v);
  28882. if (faceColors) {
  28883. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28884. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28885. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28886. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28887. }
  28888. }
  28889. if (cs !== s) {
  28890. cs = s;
  28891. }
  28892. }
  28893. }
  28894. // indices
  28895. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28896. var s;
  28897. i = 0;
  28898. for (s = 0; s < subdivisions; s++) {
  28899. var i0 = 0;
  28900. var i1 = 0;
  28901. var i2 = 0;
  28902. var i3 = 0;
  28903. for (j = 0; j < tessellation; j++) {
  28904. i0 = i * (e + 1) + j;
  28905. i1 = (i + 1) * (e + 1) + j;
  28906. i2 = i * (e + 1) + (j + 1);
  28907. i3 = (i + 1) * (e + 1) + (j + 1);
  28908. indices.push(i0, i1, i2);
  28909. indices.push(i3, i2, i1);
  28910. }
  28911. if (arc !== 1 && enclose) {
  28912. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28913. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28914. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28915. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28916. }
  28917. i = (hasRings) ? (i + 2) : (i + 1);
  28918. }
  28919. // Caps
  28920. var createCylinderCap = function (isTop) {
  28921. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28922. if (radius === 0) {
  28923. return;
  28924. }
  28925. // Cap positions, normals & uvs
  28926. var angle;
  28927. var circleVector;
  28928. var i;
  28929. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28930. var c = null;
  28931. if (faceColors) {
  28932. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28933. }
  28934. // cap center
  28935. var vbase = positions.length / 3;
  28936. var offset = isTop ? height / 2 : -height / 2;
  28937. var center = new BABYLON.Vector3(0, offset, 0);
  28938. positions.push(center.x, center.y, center.z);
  28939. normals.push(0, isTop ? 1 : -1, 0);
  28940. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28941. if (c) {
  28942. colors.push(c.r, c.g, c.b, c.a);
  28943. }
  28944. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28945. for (i = 0; i <= tessellation; i++) {
  28946. angle = Math.PI * 2 * i * arc / tessellation;
  28947. var cos = Math.cos(-angle);
  28948. var sin = Math.sin(-angle);
  28949. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28950. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28951. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28952. normals.push(0, isTop ? 1 : -1, 0);
  28953. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28954. if (c) {
  28955. colors.push(c.r, c.g, c.b, c.a);
  28956. }
  28957. }
  28958. // Cap indices
  28959. for (i = 0; i < tessellation; i++) {
  28960. if (!isTop) {
  28961. indices.push(vbase);
  28962. indices.push(vbase + (i + 1));
  28963. indices.push(vbase + (i + 2));
  28964. }
  28965. else {
  28966. indices.push(vbase);
  28967. indices.push(vbase + (i + 2));
  28968. indices.push(vbase + (i + 1));
  28969. }
  28970. }
  28971. };
  28972. // add caps to geometry
  28973. createCylinderCap(false);
  28974. createCylinderCap(true);
  28975. // Sides
  28976. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28977. var vertexData = new VertexData();
  28978. vertexData.indices = indices;
  28979. vertexData.positions = positions;
  28980. vertexData.normals = normals;
  28981. vertexData.uvs = uvs;
  28982. if (faceColors) {
  28983. vertexData.colors = colors;
  28984. }
  28985. return vertexData;
  28986. };
  28987. /**
  28988. * Creates the VertexData of the Torus.
  28989. */
  28990. VertexData.CreateTorus = function (options) {
  28991. var indices = [];
  28992. var positions = [];
  28993. var normals = [];
  28994. var uvs = [];
  28995. var diameter = options.diameter || 1;
  28996. var thickness = options.thickness || 0.5;
  28997. var tessellation = options.tessellation || 16;
  28998. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28999. var stride = tessellation + 1;
  29000. for (var i = 0; i <= tessellation; i++) {
  29001. var u = i / tessellation;
  29002. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29003. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29004. for (var j = 0; j <= tessellation; j++) {
  29005. var v = 1 - j / tessellation;
  29006. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29007. var dx = Math.cos(innerAngle);
  29008. var dy = Math.sin(innerAngle);
  29009. // Create a vertex.
  29010. var normal = new BABYLON.Vector3(dx, dy, 0);
  29011. var position = normal.scale(thickness / 2);
  29012. var textureCoordinate = new BABYLON.Vector2(u, v);
  29013. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29014. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29015. positions.push(position.x, position.y, position.z);
  29016. normals.push(normal.x, normal.y, normal.z);
  29017. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29018. // And create indices for two triangles.
  29019. var nextI = (i + 1) % stride;
  29020. var nextJ = (j + 1) % stride;
  29021. indices.push(i * stride + j);
  29022. indices.push(i * stride + nextJ);
  29023. indices.push(nextI * stride + j);
  29024. indices.push(i * stride + nextJ);
  29025. indices.push(nextI * stride + nextJ);
  29026. indices.push(nextI * stride + j);
  29027. }
  29028. }
  29029. // Sides
  29030. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29031. // Result
  29032. var vertexData = new VertexData();
  29033. vertexData.indices = indices;
  29034. vertexData.positions = positions;
  29035. vertexData.normals = normals;
  29036. vertexData.uvs = uvs;
  29037. return vertexData;
  29038. };
  29039. /**
  29040. * Creates the VertexData of the LineSystem.
  29041. */
  29042. VertexData.CreateLineSystem = function (options) {
  29043. var indices = [];
  29044. var positions = [];
  29045. var lines = options.lines;
  29046. var idx = 0;
  29047. for (var l = 0; l < lines.length; l++) {
  29048. var points = lines[l];
  29049. for (var index = 0; index < points.length; index++) {
  29050. positions.push(points[index].x, points[index].y, points[index].z);
  29051. if (index > 0) {
  29052. indices.push(idx - 1);
  29053. indices.push(idx);
  29054. }
  29055. idx++;
  29056. }
  29057. }
  29058. var vertexData = new VertexData();
  29059. vertexData.indices = indices;
  29060. vertexData.positions = positions;
  29061. return vertexData;
  29062. };
  29063. /**
  29064. * Create the VertexData of the DashedLines.
  29065. */
  29066. VertexData.CreateDashedLines = function (options) {
  29067. var dashSize = options.dashSize || 3;
  29068. var gapSize = options.gapSize || 1;
  29069. var dashNb = options.dashNb || 200;
  29070. var points = options.points;
  29071. var positions = new Array();
  29072. var indices = new Array();
  29073. var curvect = BABYLON.Vector3.Zero();
  29074. var lg = 0;
  29075. var nb = 0;
  29076. var shft = 0;
  29077. var dashshft = 0;
  29078. var curshft = 0;
  29079. var idx = 0;
  29080. var i = 0;
  29081. for (i = 0; i < points.length - 1; i++) {
  29082. points[i + 1].subtractToRef(points[i], curvect);
  29083. lg += curvect.length();
  29084. }
  29085. shft = lg / dashNb;
  29086. dashshft = dashSize * shft / (dashSize + gapSize);
  29087. for (i = 0; i < points.length - 1; i++) {
  29088. points[i + 1].subtractToRef(points[i], curvect);
  29089. nb = Math.floor(curvect.length() / shft);
  29090. curvect.normalize();
  29091. for (var j = 0; j < nb; j++) {
  29092. curshft = shft * j;
  29093. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29094. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29095. indices.push(idx, idx + 1);
  29096. idx += 2;
  29097. }
  29098. }
  29099. // Result
  29100. var vertexData = new VertexData();
  29101. vertexData.positions = positions;
  29102. vertexData.indices = indices;
  29103. return vertexData;
  29104. };
  29105. /**
  29106. * Creates the VertexData of the Ground.
  29107. */
  29108. VertexData.CreateGround = function (options) {
  29109. var indices = [];
  29110. var positions = [];
  29111. var normals = [];
  29112. var uvs = [];
  29113. var row, col;
  29114. var width = options.width || 1;
  29115. var height = options.height || 1;
  29116. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29117. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29118. for (row = 0; row <= subdivisionsY; row++) {
  29119. for (col = 0; col <= subdivisionsX; col++) {
  29120. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29121. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29122. positions.push(position.x, position.y, position.z);
  29123. normals.push(normal.x, normal.y, normal.z);
  29124. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29125. }
  29126. }
  29127. for (row = 0; row < subdivisionsY; row++) {
  29128. for (col = 0; col < subdivisionsX; col++) {
  29129. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29130. indices.push(col + 1 + row * (subdivisionsX + 1));
  29131. indices.push(col + row * (subdivisionsX + 1));
  29132. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29133. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29134. indices.push(col + row * (subdivisionsX + 1));
  29135. }
  29136. }
  29137. // Result
  29138. var vertexData = new VertexData();
  29139. vertexData.indices = indices;
  29140. vertexData.positions = positions;
  29141. vertexData.normals = normals;
  29142. vertexData.uvs = uvs;
  29143. return vertexData;
  29144. };
  29145. /**
  29146. * Creates the VertexData of the TiledGround.
  29147. */
  29148. VertexData.CreateTiledGround = function (options) {
  29149. var xmin = options.xmin || -1.0;
  29150. var zmin = options.zmin || -1.0;
  29151. var xmax = options.xmax || 1.0;
  29152. var zmax = options.zmax || 1.0;
  29153. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29154. var precision = options.precision || { w: 1, h: 1 };
  29155. var indices = new Array();
  29156. var positions = new Array();
  29157. var normals = new Array();
  29158. var uvs = new Array();
  29159. var row, col, tileRow, tileCol;
  29160. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29161. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29162. precision.w = (precision.w < 1) ? 1 : precision.w;
  29163. precision.h = (precision.h < 1) ? 1 : precision.h;
  29164. var tileSize = {
  29165. 'w': (xmax - xmin) / subdivisions.w,
  29166. 'h': (zmax - zmin) / subdivisions.h
  29167. };
  29168. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29169. // Indices
  29170. var base = positions.length / 3;
  29171. var rowLength = precision.w + 1;
  29172. for (row = 0; row < precision.h; row++) {
  29173. for (col = 0; col < precision.w; col++) {
  29174. var square = [
  29175. base + col + row * rowLength,
  29176. base + (col + 1) + row * rowLength,
  29177. base + (col + 1) + (row + 1) * rowLength,
  29178. base + col + (row + 1) * rowLength
  29179. ];
  29180. indices.push(square[1]);
  29181. indices.push(square[2]);
  29182. indices.push(square[3]);
  29183. indices.push(square[0]);
  29184. indices.push(square[1]);
  29185. indices.push(square[3]);
  29186. }
  29187. }
  29188. // Position, normals and uvs
  29189. var position = BABYLON.Vector3.Zero();
  29190. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29191. for (row = 0; row <= precision.h; row++) {
  29192. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29193. for (col = 0; col <= precision.w; col++) {
  29194. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29195. position.y = 0;
  29196. positions.push(position.x, position.y, position.z);
  29197. normals.push(normal.x, normal.y, normal.z);
  29198. uvs.push(col / precision.w, row / precision.h);
  29199. }
  29200. }
  29201. }
  29202. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29203. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29204. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29205. }
  29206. }
  29207. // Result
  29208. var vertexData = new VertexData();
  29209. vertexData.indices = indices;
  29210. vertexData.positions = positions;
  29211. vertexData.normals = normals;
  29212. vertexData.uvs = uvs;
  29213. return vertexData;
  29214. };
  29215. /**
  29216. * Creates the VertexData of the Ground designed from a heightmap.
  29217. */
  29218. VertexData.CreateGroundFromHeightMap = function (options) {
  29219. var indices = [];
  29220. var positions = [];
  29221. var normals = [];
  29222. var uvs = [];
  29223. var row, col;
  29224. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29225. // Vertices
  29226. for (row = 0; row <= options.subdivisions; row++) {
  29227. for (col = 0; col <= options.subdivisions; col++) {
  29228. 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));
  29229. // Compute height
  29230. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29231. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29232. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29233. var r = options.buffer[pos] / 255.0;
  29234. var g = options.buffer[pos + 1] / 255.0;
  29235. var b = options.buffer[pos + 2] / 255.0;
  29236. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29237. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29238. // Add vertex
  29239. positions.push(position.x, position.y, position.z);
  29240. normals.push(0, 0, 0);
  29241. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29242. }
  29243. }
  29244. // Indices
  29245. for (row = 0; row < options.subdivisions; row++) {
  29246. for (col = 0; col < options.subdivisions; col++) {
  29247. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29248. indices.push(col + 1 + row * (options.subdivisions + 1));
  29249. indices.push(col + row * (options.subdivisions + 1));
  29250. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29251. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29252. indices.push(col + row * (options.subdivisions + 1));
  29253. }
  29254. }
  29255. // Normals
  29256. VertexData.ComputeNormals(positions, indices, normals);
  29257. // Result
  29258. var vertexData = new VertexData();
  29259. vertexData.indices = indices;
  29260. vertexData.positions = positions;
  29261. vertexData.normals = normals;
  29262. vertexData.uvs = uvs;
  29263. return vertexData;
  29264. };
  29265. /**
  29266. * Creates the VertexData of the Plane.
  29267. */
  29268. VertexData.CreatePlane = function (options) {
  29269. var indices = [];
  29270. var positions = [];
  29271. var normals = [];
  29272. var uvs = [];
  29273. var width = options.width || options.size || 1;
  29274. var height = options.height || options.size || 1;
  29275. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29276. // Vertices
  29277. var halfWidth = width / 2.0;
  29278. var halfHeight = height / 2.0;
  29279. positions.push(-halfWidth, -halfHeight, 0);
  29280. normals.push(0, 0, -1.0);
  29281. uvs.push(0.0, 0.0);
  29282. positions.push(halfWidth, -halfHeight, 0);
  29283. normals.push(0, 0, -1.0);
  29284. uvs.push(1.0, 0.0);
  29285. positions.push(halfWidth, halfHeight, 0);
  29286. normals.push(0, 0, -1.0);
  29287. uvs.push(1.0, 1.0);
  29288. positions.push(-halfWidth, halfHeight, 0);
  29289. normals.push(0, 0, -1.0);
  29290. uvs.push(0.0, 1.0);
  29291. // Indices
  29292. indices.push(0);
  29293. indices.push(1);
  29294. indices.push(2);
  29295. indices.push(0);
  29296. indices.push(2);
  29297. indices.push(3);
  29298. // Sides
  29299. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29300. // Result
  29301. var vertexData = new VertexData();
  29302. vertexData.indices = indices;
  29303. vertexData.positions = positions;
  29304. vertexData.normals = normals;
  29305. vertexData.uvs = uvs;
  29306. return vertexData;
  29307. };
  29308. /**
  29309. * Creates the VertexData of the Disc or regular Polygon.
  29310. */
  29311. VertexData.CreateDisc = function (options) {
  29312. var positions = new Array();
  29313. var indices = new Array();
  29314. var normals = new Array();
  29315. var uvs = new Array();
  29316. var radius = options.radius || 0.5;
  29317. var tessellation = options.tessellation || 64;
  29318. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29320. // positions and uvs
  29321. positions.push(0, 0, 0); // disc center first
  29322. uvs.push(0.5, 0.5);
  29323. var theta = Math.PI * 2 * arc;
  29324. var step = theta / tessellation;
  29325. for (var a = 0; a < theta; a += step) {
  29326. var x = Math.cos(a);
  29327. var y = Math.sin(a);
  29328. var u = (x + 1) / 2;
  29329. var v = (1 - y) / 2;
  29330. positions.push(radius * x, radius * y, 0);
  29331. uvs.push(u, v);
  29332. }
  29333. if (arc === 1) {
  29334. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29335. uvs.push(uvs[2], uvs[3]);
  29336. }
  29337. //indices
  29338. var vertexNb = positions.length / 3;
  29339. for (var i = 1; i < vertexNb - 1; i++) {
  29340. indices.push(i + 1, 0, i);
  29341. }
  29342. // result
  29343. VertexData.ComputeNormals(positions, indices, normals);
  29344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29345. var vertexData = new VertexData();
  29346. vertexData.indices = indices;
  29347. vertexData.positions = positions;
  29348. vertexData.normals = normals;
  29349. vertexData.uvs = uvs;
  29350. return vertexData;
  29351. };
  29352. /**
  29353. * Re-creates the VertexData of the Polygon for sideOrientation.
  29354. */
  29355. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29356. var faceUV = fUV || new Array(3);
  29357. var faceColors = fColors;
  29358. var colors = [];
  29359. // default face colors and UV if undefined
  29360. for (var f = 0; f < 3; f++) {
  29361. if (faceUV[f] === undefined) {
  29362. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29363. }
  29364. if (faceColors && faceColors[f] === undefined) {
  29365. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29366. }
  29367. }
  29368. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29369. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29370. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29371. var indices = polygon.getIndices();
  29372. // set face colours and textures
  29373. var idx = 0;
  29374. var face = 0;
  29375. for (var index = 0; index < normals.length; index += 3) {
  29376. //Edge Face no. 1
  29377. if (Math.abs(normals[index + 1]) < 0.001) {
  29378. face = 1;
  29379. }
  29380. //Top Face no. 0
  29381. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29382. face = 0;
  29383. }
  29384. //Bottom Face no. 2
  29385. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29386. face = 2;
  29387. }
  29388. idx = index / 3;
  29389. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29390. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29391. if (faceColors) {
  29392. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29393. }
  29394. }
  29395. // sides
  29396. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29397. // Result
  29398. var vertexData = new VertexData();
  29399. vertexData.indices = indices;
  29400. vertexData.positions = positions;
  29401. vertexData.normals = normals;
  29402. vertexData.uvs = uvs;
  29403. if (faceColors) {
  29404. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29405. vertexData.colors = totalColors;
  29406. }
  29407. return vertexData;
  29408. };
  29409. /**
  29410. * Creates the VertexData of the IcoSphere.
  29411. */
  29412. VertexData.CreateIcoSphere = function (options) {
  29413. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29414. var radius = options.radius || 1;
  29415. var flat = (options.flat === undefined) ? true : options.flat;
  29416. var subdivisions = options.subdivisions || 4;
  29417. var radiusX = options.radiusX || radius;
  29418. var radiusY = options.radiusY || radius;
  29419. var radiusZ = options.radiusZ || radius;
  29420. var t = (1 + Math.sqrt(5)) / 2;
  29421. // 12 vertex x,y,z
  29422. var ico_vertices = [
  29423. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29424. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29425. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29426. ];
  29427. // index of 3 vertex makes a face of icopshere
  29428. var ico_indices = [
  29429. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29430. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29431. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29432. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29433. ];
  29434. // vertex for uv have aliased position, not for UV
  29435. var vertices_unalias_id = [
  29436. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29437. // vertex alias
  29438. 0,
  29439. 2,
  29440. 3,
  29441. 3,
  29442. 3,
  29443. 4,
  29444. 7,
  29445. 8,
  29446. 9,
  29447. 9,
  29448. 10,
  29449. 11 // 23: B + 12
  29450. ];
  29451. // uv as integer step (not pixels !)
  29452. var ico_vertexuv = [
  29453. 5, 1, 3, 1, 6, 4, 0, 0,
  29454. 5, 3, 4, 2, 2, 2, 4, 0,
  29455. 2, 0, 1, 1, 6, 0, 6, 2,
  29456. // vertex alias (for same vertex on different faces)
  29457. 0, 4,
  29458. 3, 3,
  29459. 4, 4,
  29460. 3, 1,
  29461. 4, 2,
  29462. 4, 4,
  29463. 0, 2,
  29464. 1, 1,
  29465. 2, 2,
  29466. 3, 3,
  29467. 1, 3,
  29468. 2, 4 // 23: B + 12
  29469. ];
  29470. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29471. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29472. // First island of uv mapping
  29473. // v = 4h 3+ 2
  29474. // v = 3h 9+ 4
  29475. // v = 2h 9+ 5 B
  29476. // v = 1h 9 1 0
  29477. // v = 0h 3 8 7 A
  29478. // u = 0 1 2 3 4 5 6 *a
  29479. // Second island of uv mapping
  29480. // v = 4h 0+ B+ 4+
  29481. // v = 3h A+ 2+
  29482. // v = 2h 7+ 6 3+
  29483. // v = 1h 8+ 3+
  29484. // v = 0h
  29485. // u = 0 1 2 3 4 5 6 *a
  29486. // Face layout on texture UV mapping
  29487. // ============
  29488. // \ 4 /\ 16 / ======
  29489. // \ / \ / /\ 11 /
  29490. // \/ 7 \/ / \ /
  29491. // ======= / 10 \/
  29492. // /\ 17 /\ =======
  29493. // / \ / \ \ 15 /\
  29494. // / 8 \/ 12 \ \ / \
  29495. // ============ \/ 6 \
  29496. // \ 18 /\ ============
  29497. // \ / \ \ 5 /\ 0 /
  29498. // \/ 13 \ \ / \ /
  29499. // ======= \/ 1 \/
  29500. // =============
  29501. // /\ 19 /\ 2 /\
  29502. // / \ / \ / \
  29503. // / 14 \/ 9 \/ 3 \
  29504. // ===================
  29505. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29506. var ustep = 138 / 1024;
  29507. var vstep = 239 / 1024;
  29508. var uoffset = 60 / 1024;
  29509. var voffset = 26 / 1024;
  29510. // Second island should have margin, not to touch the first island
  29511. // avoid any borderline artefact in pixel rounding
  29512. var island_u_offset = -40 / 1024;
  29513. var island_v_offset = +20 / 1024;
  29514. // face is either island 0 or 1 :
  29515. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29516. var island = [
  29517. 0, 0, 0, 0, 1,
  29518. 0, 0, 1, 1, 0,
  29519. 0, 0, 1, 1, 0,
  29520. 0, 1, 1, 1, 0 // 15 - 19
  29521. ];
  29522. var indices = new Array();
  29523. var positions = new Array();
  29524. var normals = new Array();
  29525. var uvs = new Array();
  29526. var current_indice = 0;
  29527. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29528. var face_vertex_pos = new Array(3);
  29529. var face_vertex_uv = new Array(3);
  29530. var v012;
  29531. for (v012 = 0; v012 < 3; v012++) {
  29532. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29533. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29534. }
  29535. // create all with normals
  29536. for (var face = 0; face < 20; face++) {
  29537. // 3 vertex per face
  29538. for (v012 = 0; v012 < 3; v012++) {
  29539. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29540. var v_id = ico_indices[3 * face + v012];
  29541. // vertex have 3D position (x,y,z)
  29542. 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]);
  29543. // Normalize to get normal, then scale to radius
  29544. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29545. // uv Coordinates from vertex ID
  29546. 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);
  29547. }
  29548. // Subdivide the face (interpolate pos, norm, uv)
  29549. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29550. // - norm is linear interpolation of vertex corner normal
  29551. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29552. // - uv is linear interpolation
  29553. //
  29554. // Topology is as below for sub-divide by 2
  29555. // vertex shown as v0,v1,v2
  29556. // interp index is i1 to progress in range [v0,v1[
  29557. // interp index is i2 to progress in range [v0,v2[
  29558. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29559. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29560. //
  29561. //
  29562. // i2 v2
  29563. // ^ ^
  29564. // / / \
  29565. // / / \
  29566. // / / \
  29567. // / / (0,1) \
  29568. // / #---------\
  29569. // / / \ (0,0)'/ \
  29570. // / / \ / \
  29571. // / / \ / \
  29572. // / / (0,0) \ / (1,0) \
  29573. // / #---------#---------\
  29574. // v0 v1
  29575. //
  29576. // --------------------> i1
  29577. //
  29578. // interp of (i1,i2):
  29579. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29580. // along i1 : lerp(x0,x1, i1/(S-i2))
  29581. //
  29582. // centroid of triangle is needed to get help normal computation
  29583. // (c1,c2) are used for centroid location
  29584. var interp_vertex = function (i1, i2, c1, c2) {
  29585. // vertex is interpolated from
  29586. // - face_vertex_pos[0..2]
  29587. // - face_vertex_uv[0..2]
  29588. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29589. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29590. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29591. pos_interp.normalize();
  29592. var vertex_normal;
  29593. if (flat) {
  29594. // in flat mode, recalculate normal as face centroid normal
  29595. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29596. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29597. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29598. }
  29599. else {
  29600. // in smooth mode, recalculate normal from each single vertex position
  29601. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29602. }
  29603. // Vertex normal need correction due to X,Y,Z radius scaling
  29604. vertex_normal.x /= radiusX;
  29605. vertex_normal.y /= radiusY;
  29606. vertex_normal.z /= radiusZ;
  29607. vertex_normal.normalize();
  29608. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29609. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29610. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29611. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29612. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29613. uvs.push(uv_interp.x, uv_interp.y);
  29614. // push each vertex has member of a face
  29615. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29616. indices.push(current_indice);
  29617. current_indice++;
  29618. };
  29619. for (var i2 = 0; i2 < subdivisions; i2++) {
  29620. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29621. // face : (i1,i2) for /\ :
  29622. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29623. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29624. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29625. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29626. if (i1 + i2 + 1 < subdivisions) {
  29627. // face : (i1,i2)' for \/ :
  29628. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29629. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29630. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29631. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29632. }
  29633. }
  29634. }
  29635. }
  29636. // Sides
  29637. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29638. // Result
  29639. var vertexData = new VertexData();
  29640. vertexData.indices = indices;
  29641. vertexData.positions = positions;
  29642. vertexData.normals = normals;
  29643. vertexData.uvs = uvs;
  29644. return vertexData;
  29645. };
  29646. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29647. /**
  29648. * Creates the VertexData of the Polyhedron.
  29649. */
  29650. VertexData.CreatePolyhedron = function (options) {
  29651. // provided polyhedron types :
  29652. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29653. // 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)
  29654. var polyhedra = [];
  29655. 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]] };
  29656. 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]] };
  29657. polyhedra[2] = {
  29658. 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]],
  29659. 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]]
  29660. };
  29661. polyhedra[3] = {
  29662. 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]],
  29663. 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]]
  29664. };
  29665. polyhedra[4] = {
  29666. 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]],
  29667. 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]]
  29668. };
  29669. 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]] };
  29670. 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]] };
  29671. 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]] };
  29672. 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]] };
  29673. 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]] };
  29674. 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]] };
  29675. 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]] };
  29676. 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]] };
  29677. 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]] };
  29678. polyhedra[14] = {
  29679. 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]],
  29680. 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]]
  29681. };
  29682. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29683. var size = options.size;
  29684. var sizeX = options.sizeX || size || 1;
  29685. var sizeY = options.sizeY || size || 1;
  29686. var sizeZ = options.sizeZ || size || 1;
  29687. var data = options.custom || polyhedra[type];
  29688. var nbfaces = data.face.length;
  29689. var faceUV = options.faceUV || new Array(nbfaces);
  29690. var faceColors = options.faceColors;
  29691. var flat = (options.flat === undefined) ? true : options.flat;
  29692. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29693. var positions = new Array();
  29694. var indices = new Array();
  29695. var normals = new Array();
  29696. var uvs = new Array();
  29697. var colors = new Array();
  29698. var index = 0;
  29699. var faceIdx = 0; // face cursor in the array "indexes"
  29700. var indexes = new Array();
  29701. var i = 0;
  29702. var f = 0;
  29703. var u, v, ang, x, y, tmp;
  29704. // default face colors and UV if undefined
  29705. if (flat) {
  29706. for (f = 0; f < nbfaces; f++) {
  29707. if (faceColors && faceColors[f] === undefined) {
  29708. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29709. }
  29710. if (faceUV && faceUV[f] === undefined) {
  29711. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29712. }
  29713. }
  29714. }
  29715. if (!flat) {
  29716. for (i = 0; i < data.vertex.length; i++) {
  29717. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29718. uvs.push(0, 0);
  29719. }
  29720. for (f = 0; f < nbfaces; f++) {
  29721. for (i = 0; i < data.face[f].length - 2; i++) {
  29722. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29723. }
  29724. }
  29725. }
  29726. else {
  29727. for (f = 0; f < nbfaces; f++) {
  29728. var fl = data.face[f].length; // number of vertices of the current face
  29729. ang = 2 * Math.PI / fl;
  29730. x = 0.5 * Math.tan(ang / 2);
  29731. y = 0.5;
  29732. // positions, uvs, colors
  29733. for (i = 0; i < fl; i++) {
  29734. // positions
  29735. 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);
  29736. indexes.push(index);
  29737. index++;
  29738. // uvs
  29739. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29740. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29741. uvs.push(u, v);
  29742. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29743. y = x * Math.sin(ang) + y * Math.cos(ang);
  29744. x = tmp;
  29745. // colors
  29746. if (faceColors) {
  29747. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29748. }
  29749. }
  29750. // indices from indexes
  29751. for (i = 0; i < fl - 2; i++) {
  29752. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29753. }
  29754. faceIdx += fl;
  29755. }
  29756. }
  29757. VertexData.ComputeNormals(positions, indices, normals);
  29758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29759. var vertexData = new VertexData();
  29760. vertexData.positions = positions;
  29761. vertexData.indices = indices;
  29762. vertexData.normals = normals;
  29763. vertexData.uvs = uvs;
  29764. if (faceColors && flat) {
  29765. vertexData.colors = colors;
  29766. }
  29767. return vertexData;
  29768. };
  29769. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29770. /**
  29771. * Creates the VertexData of the Torus Knot.
  29772. */
  29773. VertexData.CreateTorusKnot = function (options) {
  29774. var indices = new Array();
  29775. var positions = new Array();
  29776. var normals = new Array();
  29777. var uvs = new Array();
  29778. var radius = options.radius || 2;
  29779. var tube = options.tube || 0.5;
  29780. var radialSegments = options.radialSegments || 32;
  29781. var tubularSegments = options.tubularSegments || 32;
  29782. var p = options.p || 2;
  29783. var q = options.q || 3;
  29784. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29785. // Helper
  29786. var getPos = function (angle) {
  29787. var cu = Math.cos(angle);
  29788. var su = Math.sin(angle);
  29789. var quOverP = q / p * angle;
  29790. var cs = Math.cos(quOverP);
  29791. var tx = radius * (2 + cs) * 0.5 * cu;
  29792. var ty = radius * (2 + cs) * su * 0.5;
  29793. var tz = radius * Math.sin(quOverP) * 0.5;
  29794. return new BABYLON.Vector3(tx, ty, tz);
  29795. };
  29796. // Vertices
  29797. var i;
  29798. var j;
  29799. for (i = 0; i <= radialSegments; i++) {
  29800. var modI = i % radialSegments;
  29801. var u = modI / radialSegments * 2 * p * Math.PI;
  29802. var p1 = getPos(u);
  29803. var p2 = getPos(u + 0.01);
  29804. var tang = p2.subtract(p1);
  29805. var n = p2.add(p1);
  29806. var bitan = BABYLON.Vector3.Cross(tang, n);
  29807. n = BABYLON.Vector3.Cross(bitan, tang);
  29808. bitan.normalize();
  29809. n.normalize();
  29810. for (j = 0; j < tubularSegments; j++) {
  29811. var modJ = j % tubularSegments;
  29812. var v = modJ / tubularSegments * 2 * Math.PI;
  29813. var cx = -tube * Math.cos(v);
  29814. var cy = tube * Math.sin(v);
  29815. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29816. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29817. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29818. uvs.push(i / radialSegments);
  29819. uvs.push(j / tubularSegments);
  29820. }
  29821. }
  29822. for (i = 0; i < radialSegments; i++) {
  29823. for (j = 0; j < tubularSegments; j++) {
  29824. var jNext = (j + 1) % tubularSegments;
  29825. var a = i * tubularSegments + j;
  29826. var b = (i + 1) * tubularSegments + j;
  29827. var c = (i + 1) * tubularSegments + jNext;
  29828. var d = i * tubularSegments + jNext;
  29829. indices.push(d);
  29830. indices.push(b);
  29831. indices.push(a);
  29832. indices.push(d);
  29833. indices.push(c);
  29834. indices.push(b);
  29835. }
  29836. }
  29837. // Normals
  29838. VertexData.ComputeNormals(positions, indices, normals);
  29839. // Sides
  29840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29841. // Result
  29842. var vertexData = new VertexData();
  29843. vertexData.indices = indices;
  29844. vertexData.positions = positions;
  29845. vertexData.normals = normals;
  29846. vertexData.uvs = uvs;
  29847. return vertexData;
  29848. };
  29849. // Tools
  29850. /**
  29851. * @param {any} - positions (number[] or Float32Array)
  29852. * @param {any} - indices (number[] or Uint16Array)
  29853. * @param {any} - normals (number[] or Float32Array)
  29854. * options (optional) :
  29855. * facetPositions : optional array of facet positions (vector3)
  29856. * facetNormals : optional array of facet normals (vector3)
  29857. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29858. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29859. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29860. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29861. * bInfo : optional bounding info, required for facetPartitioning computation
  29862. */
  29863. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29864. // temporary scalar variables
  29865. var index = 0; // facet index
  29866. var p1p2x = 0.0; // p1p2 vector x coordinate
  29867. var p1p2y = 0.0; // p1p2 vector y coordinate
  29868. var p1p2z = 0.0; // p1p2 vector z coordinate
  29869. var p3p2x = 0.0; // p3p2 vector x coordinate
  29870. var p3p2y = 0.0; // p3p2 vector y coordinate
  29871. var p3p2z = 0.0; // p3p2 vector z coordinate
  29872. var faceNormalx = 0.0; // facet normal x coordinate
  29873. var faceNormaly = 0.0; // facet normal y coordinate
  29874. var faceNormalz = 0.0; // facet normal z coordinate
  29875. var length = 0.0; // facet normal length before normalization
  29876. var v1x = 0; // vector1 x index in the positions array
  29877. var v1y = 0; // vector1 y index in the positions array
  29878. var v1z = 0; // vector1 z index in the positions array
  29879. var v2x = 0; // vector2 x index in the positions array
  29880. var v2y = 0; // vector2 y index in the positions array
  29881. var v2z = 0; // vector2 z index in the positions array
  29882. var v3x = 0; // vector3 x index in the positions array
  29883. var v3y = 0; // vector3 y index in the positions array
  29884. var v3z = 0; // vector3 z index in the positions array
  29885. var computeFacetNormals = false;
  29886. var computeFacetPositions = false;
  29887. var computeFacetPartitioning = false;
  29888. var faceNormalSign = 1;
  29889. var ratio = 0;
  29890. if (options) {
  29891. computeFacetNormals = (options.facetNormals) ? true : false;
  29892. computeFacetPositions = (options.facetPositions) ? true : false;
  29893. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29894. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29895. ratio = options.ratio || 0;
  29896. }
  29897. // facetPartitioning reinit if needed
  29898. var xSubRatio = 0;
  29899. var ySubRatio = 0;
  29900. var zSubRatio = 0;
  29901. var subSq = 0;
  29902. if (computeFacetPartitioning && options && options.bbSize) {
  29903. var ox = 0; // X partitioning index for facet position
  29904. var oy = 0; // Y partinioning index for facet position
  29905. var oz = 0; // Z partinioning index for facet position
  29906. var b1x = 0; // X partitioning index for facet v1 vertex
  29907. var b1y = 0; // Y partitioning index for facet v1 vertex
  29908. var b1z = 0; // z partitioning index for facet v1 vertex
  29909. var b2x = 0; // X partitioning index for facet v2 vertex
  29910. var b2y = 0; // Y partitioning index for facet v2 vertex
  29911. var b2z = 0; // Z partitioning index for facet v2 vertex
  29912. var b3x = 0; // X partitioning index for facet v3 vertex
  29913. var b3y = 0; // Y partitioning index for facet v3 vertex
  29914. var b3z = 0; // Z partitioning index for facet v3 vertex
  29915. var block_idx_o = 0; // facet barycenter block index
  29916. var block_idx_v1 = 0; // v1 vertex block index
  29917. var block_idx_v2 = 0; // v2 vertex block index
  29918. var block_idx_v3 = 0; // v3 vertex block index
  29919. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29920. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29921. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29922. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29923. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29924. subSq = options.subDiv.max * options.subDiv.max;
  29925. options.facetPartitioning.length = 0;
  29926. }
  29927. // reset the normals
  29928. for (index = 0; index < positions.length; index++) {
  29929. normals[index] = 0.0;
  29930. }
  29931. // Loop : 1 indice triplet = 1 facet
  29932. var nbFaces = indices.length / 3;
  29933. for (index = 0; index < nbFaces; index++) {
  29934. // get the indexes of the coordinates of each vertex of the facet
  29935. v1x = indices[index * 3] * 3;
  29936. v1y = v1x + 1;
  29937. v1z = v1x + 2;
  29938. v2x = indices[index * 3 + 1] * 3;
  29939. v2y = v2x + 1;
  29940. v2z = v2x + 2;
  29941. v3x = indices[index * 3 + 2] * 3;
  29942. v3y = v3x + 1;
  29943. v3z = v3x + 2;
  29944. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29945. p1p2y = positions[v1y] - positions[v2y];
  29946. p1p2z = positions[v1z] - positions[v2z];
  29947. p3p2x = positions[v3x] - positions[v2x];
  29948. p3p2y = positions[v3y] - positions[v2y];
  29949. p3p2z = positions[v3z] - positions[v2z];
  29950. // compute the face normal with the cross product
  29951. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29952. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29953. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29954. // normalize this normal and store it in the array facetData
  29955. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29956. length = (length === 0) ? 1.0 : length;
  29957. faceNormalx /= length;
  29958. faceNormaly /= length;
  29959. faceNormalz /= length;
  29960. if (computeFacetNormals && options) {
  29961. options.facetNormals[index].x = faceNormalx;
  29962. options.facetNormals[index].y = faceNormaly;
  29963. options.facetNormals[index].z = faceNormalz;
  29964. }
  29965. if (computeFacetPositions && options) {
  29966. // compute and the facet barycenter coordinates in the array facetPositions
  29967. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29968. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29969. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29970. }
  29971. if (computeFacetPartitioning && options) {
  29972. // store the facet indexes in arrays in the main facetPartitioning array :
  29973. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29974. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  29975. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  29976. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  29977. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29978. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29979. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29980. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29981. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29982. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29983. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29984. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29985. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29986. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29987. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29988. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29989. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29990. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29991. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29992. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29993. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29994. // push each facet index in each block containing the vertex
  29995. options.facetPartitioning[block_idx_v1].push(index);
  29996. if (block_idx_v2 != block_idx_v1) {
  29997. options.facetPartitioning[block_idx_v2].push(index);
  29998. }
  29999. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30000. options.facetPartitioning[block_idx_v3].push(index);
  30001. }
  30002. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30003. options.facetPartitioning[block_idx_o].push(index);
  30004. }
  30005. }
  30006. // compute the normals anyway
  30007. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30008. normals[v1y] += faceNormaly;
  30009. normals[v1z] += faceNormalz;
  30010. normals[v2x] += faceNormalx;
  30011. normals[v2y] += faceNormaly;
  30012. normals[v2z] += faceNormalz;
  30013. normals[v3x] += faceNormalx;
  30014. normals[v3y] += faceNormaly;
  30015. normals[v3z] += faceNormalz;
  30016. }
  30017. // last normalization of each normal
  30018. for (index = 0; index < normals.length / 3; index++) {
  30019. faceNormalx = normals[index * 3];
  30020. faceNormaly = normals[index * 3 + 1];
  30021. faceNormalz = normals[index * 3 + 2];
  30022. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30023. length = (length === 0) ? 1.0 : length;
  30024. faceNormalx /= length;
  30025. faceNormaly /= length;
  30026. faceNormalz /= length;
  30027. normals[index * 3] = faceNormalx;
  30028. normals[index * 3 + 1] = faceNormaly;
  30029. normals[index * 3 + 2] = faceNormalz;
  30030. }
  30031. };
  30032. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30033. var li = indices.length;
  30034. var ln = normals.length;
  30035. var i;
  30036. var n;
  30037. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30038. switch (sideOrientation) {
  30039. case BABYLON.Mesh.FRONTSIDE:
  30040. // nothing changed
  30041. break;
  30042. case BABYLON.Mesh.BACKSIDE:
  30043. var tmp;
  30044. // indices
  30045. for (i = 0; i < li; i += 3) {
  30046. tmp = indices[i];
  30047. indices[i] = indices[i + 2];
  30048. indices[i + 2] = tmp;
  30049. }
  30050. // normals
  30051. for (n = 0; n < ln; n++) {
  30052. normals[n] = -normals[n];
  30053. }
  30054. break;
  30055. case BABYLON.Mesh.DOUBLESIDE:
  30056. // positions
  30057. var lp = positions.length;
  30058. var l = lp / 3;
  30059. for (var p = 0; p < lp; p++) {
  30060. positions[lp + p] = positions[p];
  30061. }
  30062. // indices
  30063. for (i = 0; i < li; i += 3) {
  30064. indices[i + li] = indices[i + 2] + l;
  30065. indices[i + 1 + li] = indices[i + 1] + l;
  30066. indices[i + 2 + li] = indices[i] + l;
  30067. }
  30068. // normals
  30069. for (n = 0; n < ln; n++) {
  30070. normals[ln + n] = -normals[n];
  30071. }
  30072. // uvs
  30073. var lu = uvs.length;
  30074. var u = 0;
  30075. for (u = 0; u < lu; u++) {
  30076. uvs[u + lu] = uvs[u];
  30077. }
  30078. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30079. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30080. u = 0;
  30081. for (i = 0; i < lu / 2; i++) {
  30082. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30083. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30084. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30085. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30086. u += 2;
  30087. }
  30088. break;
  30089. }
  30090. };
  30091. /**
  30092. * Creates a new VertexData from the imported parameters.
  30093. */
  30094. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30095. var vertexData = new VertexData();
  30096. // positions
  30097. var positions = parsedVertexData.positions;
  30098. if (positions) {
  30099. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30100. }
  30101. // normals
  30102. var normals = parsedVertexData.normals;
  30103. if (normals) {
  30104. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30105. }
  30106. // tangents
  30107. var tangents = parsedVertexData.tangents;
  30108. if (tangents) {
  30109. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30110. }
  30111. // uvs
  30112. var uvs = parsedVertexData.uvs;
  30113. if (uvs) {
  30114. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30115. }
  30116. // uv2s
  30117. var uv2s = parsedVertexData.uv2s;
  30118. if (uv2s) {
  30119. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30120. }
  30121. // uv3s
  30122. var uv3s = parsedVertexData.uv3s;
  30123. if (uv3s) {
  30124. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30125. }
  30126. // uv4s
  30127. var uv4s = parsedVertexData.uv4s;
  30128. if (uv4s) {
  30129. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30130. }
  30131. // uv5s
  30132. var uv5s = parsedVertexData.uv5s;
  30133. if (uv5s) {
  30134. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30135. }
  30136. // uv6s
  30137. var uv6s = parsedVertexData.uv6s;
  30138. if (uv6s) {
  30139. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30140. }
  30141. // colors
  30142. var colors = parsedVertexData.colors;
  30143. if (colors) {
  30144. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30145. }
  30146. // matricesIndices
  30147. var matricesIndices = parsedVertexData.matricesIndices;
  30148. if (matricesIndices) {
  30149. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30150. }
  30151. // matricesWeights
  30152. var matricesWeights = parsedVertexData.matricesWeights;
  30153. if (matricesWeights) {
  30154. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30155. }
  30156. // indices
  30157. var indices = parsedVertexData.indices;
  30158. if (indices) {
  30159. vertexData.indices = indices;
  30160. }
  30161. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30162. };
  30163. return VertexData;
  30164. }());
  30165. BABYLON.VertexData = VertexData;
  30166. })(BABYLON || (BABYLON = {}));
  30167. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30168. var BABYLON;
  30169. (function (BABYLON) {
  30170. var Geometry = /** @class */ (function () {
  30171. function Geometry(id, scene, vertexData, updatable, mesh) {
  30172. if (updatable === void 0) { updatable = false; }
  30173. if (mesh === void 0) { mesh = null; }
  30174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30175. this._totalVertices = 0;
  30176. this._isDisposed = false;
  30177. this._indexBufferIsUpdatable = false;
  30178. this.id = id;
  30179. this._engine = scene.getEngine();
  30180. this._meshes = [];
  30181. this._scene = scene;
  30182. //Init vertex buffer cache
  30183. this._vertexBuffers = {};
  30184. this._indices = [];
  30185. this._updatable = updatable;
  30186. // vertexData
  30187. if (vertexData) {
  30188. this.setAllVerticesData(vertexData, updatable);
  30189. }
  30190. else {
  30191. this._totalVertices = 0;
  30192. this._indices = [];
  30193. }
  30194. if (this._engine.getCaps().vertexArrayObject) {
  30195. this._vertexArrayObjects = {};
  30196. }
  30197. // applyToMesh
  30198. if (mesh) {
  30199. if (mesh.getClassName() === "LinesMesh") {
  30200. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30201. this.updateExtend();
  30202. }
  30203. this.applyToMesh(mesh);
  30204. mesh.computeWorldMatrix(true);
  30205. }
  30206. }
  30207. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30208. /**
  30209. * 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
  30210. * @returns The Bias Vector
  30211. */
  30212. get: function () {
  30213. return this._boundingBias;
  30214. },
  30215. set: function (value) {
  30216. if (this._boundingBias && this._boundingBias.equals(value)) {
  30217. return;
  30218. }
  30219. this._boundingBias = value.clone();
  30220. this.updateBoundingInfo(true, null);
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Geometry.CreateGeometryForMesh = function (mesh) {
  30226. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30227. geometry.applyToMesh(mesh);
  30228. return geometry;
  30229. };
  30230. Object.defineProperty(Geometry.prototype, "extend", {
  30231. get: function () {
  30232. return this._extend;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. Geometry.prototype.getScene = function () {
  30238. return this._scene;
  30239. };
  30240. Geometry.prototype.getEngine = function () {
  30241. return this._engine;
  30242. };
  30243. Geometry.prototype.isReady = function () {
  30244. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30245. };
  30246. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30247. get: function () {
  30248. for (var index = 0; index < this._meshes.length; index++) {
  30249. if (!this._meshes[index].doNotSerialize) {
  30250. return false;
  30251. }
  30252. }
  30253. return true;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Geometry.prototype._rebuild = function () {
  30259. if (this._vertexArrayObjects) {
  30260. this._vertexArrayObjects = {};
  30261. }
  30262. // Index buffer
  30263. if (this._meshes.length !== 0 && this._indices) {
  30264. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30265. }
  30266. // Vertex buffers
  30267. for (var key in this._vertexBuffers) {
  30268. var vertexBuffer = this._vertexBuffers[key];
  30269. vertexBuffer._rebuild();
  30270. }
  30271. };
  30272. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30273. vertexData.applyToGeometry(this, updatable);
  30274. this.notifyUpdate();
  30275. };
  30276. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30277. if (updatable === void 0) { updatable = false; }
  30278. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30279. this.setVerticesBuffer(buffer);
  30280. };
  30281. Geometry.prototype.removeVerticesData = function (kind) {
  30282. if (this._vertexBuffers[kind]) {
  30283. this._vertexBuffers[kind].dispose();
  30284. delete this._vertexBuffers[kind];
  30285. }
  30286. };
  30287. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30288. var kind = buffer.getKind();
  30289. if (this._vertexBuffers[kind]) {
  30290. this._vertexBuffers[kind].dispose();
  30291. }
  30292. this._vertexBuffers[kind] = buffer;
  30293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30294. var data = buffer.getData();
  30295. var stride = buffer.getStrideSize();
  30296. this._totalVertices = data.length / stride;
  30297. this.updateExtend(data, stride);
  30298. this._resetPointsArrayCache();
  30299. var meshes = this._meshes;
  30300. var numOfMeshes = meshes.length;
  30301. for (var index = 0; index < numOfMeshes; index++) {
  30302. var mesh = meshes[index];
  30303. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30304. mesh._createGlobalSubMesh(false);
  30305. mesh.computeWorldMatrix(true);
  30306. }
  30307. }
  30308. this.notifyUpdate(kind);
  30309. if (this._vertexArrayObjects) {
  30310. this._disposeVertexArrayObjects();
  30311. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30312. }
  30313. };
  30314. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30315. var vertexBuffer = this.getVertexBuffer(kind);
  30316. if (!vertexBuffer) {
  30317. return;
  30318. }
  30319. vertexBuffer.updateDirectly(data, offset);
  30320. this.notifyUpdate(kind);
  30321. };
  30322. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30323. if (updateExtends === void 0) { updateExtends = false; }
  30324. var vertexBuffer = this.getVertexBuffer(kind);
  30325. if (!vertexBuffer) {
  30326. return;
  30327. }
  30328. vertexBuffer.update(data);
  30329. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30330. var stride = vertexBuffer.getStrideSize();
  30331. this._totalVertices = data.length / stride;
  30332. this.updateBoundingInfo(updateExtends, data);
  30333. }
  30334. this.notifyUpdate(kind);
  30335. };
  30336. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30337. if (updateExtends) {
  30338. this.updateExtend(data);
  30339. }
  30340. var meshes = this._meshes;
  30341. var numOfMeshes = meshes.length;
  30342. this._resetPointsArrayCache();
  30343. for (var index = 0; index < numOfMeshes; index++) {
  30344. var mesh = meshes[index];
  30345. if (updateExtends) {
  30346. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30347. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30348. var subMesh = mesh.subMeshes[subIndex];
  30349. subMesh.refreshBoundingInfo();
  30350. }
  30351. }
  30352. }
  30353. };
  30354. Geometry.prototype._bind = function (effect, indexToBind) {
  30355. if (!effect) {
  30356. return;
  30357. }
  30358. if (indexToBind === undefined) {
  30359. indexToBind = this._indexBuffer;
  30360. }
  30361. var vbs = this.getVertexBuffers();
  30362. if (!vbs) {
  30363. return;
  30364. }
  30365. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30366. this._engine.bindBuffers(vbs, indexToBind, effect);
  30367. return;
  30368. }
  30369. // Using VAO
  30370. if (!this._vertexArrayObjects[effect.key]) {
  30371. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30372. }
  30373. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30374. };
  30375. Geometry.prototype.getTotalVertices = function () {
  30376. if (!this.isReady()) {
  30377. return 0;
  30378. }
  30379. return this._totalVertices;
  30380. };
  30381. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30382. var vertexBuffer = this.getVertexBuffer(kind);
  30383. if (!vertexBuffer) {
  30384. return null;
  30385. }
  30386. var orig = vertexBuffer.getData();
  30387. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30388. return orig;
  30389. }
  30390. else {
  30391. var len = orig.length;
  30392. var copy = [];
  30393. for (var i = 0; i < len; i++) {
  30394. copy.push(orig[i]);
  30395. }
  30396. return copy;
  30397. }
  30398. };
  30399. /**
  30400. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30401. * Possible `kind` values :
  30402. * - BABYLON.VertexBuffer.PositionKind
  30403. * - BABYLON.VertexBuffer.UVKind
  30404. * - BABYLON.VertexBuffer.UV2Kind
  30405. * - BABYLON.VertexBuffer.UV3Kind
  30406. * - BABYLON.VertexBuffer.UV4Kind
  30407. * - BABYLON.VertexBuffer.UV5Kind
  30408. * - BABYLON.VertexBuffer.UV6Kind
  30409. * - BABYLON.VertexBuffer.ColorKind
  30410. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30411. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30412. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30413. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30414. */
  30415. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30416. var vb = this._vertexBuffers[kind];
  30417. if (!vb) {
  30418. return false;
  30419. }
  30420. return vb.isUpdatable();
  30421. };
  30422. Geometry.prototype.getVertexBuffer = function (kind) {
  30423. if (!this.isReady()) {
  30424. return null;
  30425. }
  30426. return this._vertexBuffers[kind];
  30427. };
  30428. Geometry.prototype.getVertexBuffers = function () {
  30429. if (!this.isReady()) {
  30430. return null;
  30431. }
  30432. return this._vertexBuffers;
  30433. };
  30434. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30435. if (!this._vertexBuffers) {
  30436. if (this._delayInfo) {
  30437. return this._delayInfo.indexOf(kind) !== -1;
  30438. }
  30439. return false;
  30440. }
  30441. return this._vertexBuffers[kind] !== undefined;
  30442. };
  30443. Geometry.prototype.getVerticesDataKinds = function () {
  30444. var result = [];
  30445. var kind;
  30446. if (!this._vertexBuffers && this._delayInfo) {
  30447. for (kind in this._delayInfo) {
  30448. result.push(kind);
  30449. }
  30450. }
  30451. else {
  30452. for (kind in this._vertexBuffers) {
  30453. result.push(kind);
  30454. }
  30455. }
  30456. return result;
  30457. };
  30458. Geometry.prototype.updateIndices = function (indices, offset) {
  30459. if (!this._indexBuffer) {
  30460. return;
  30461. }
  30462. if (!this._indexBufferIsUpdatable) {
  30463. this.setIndices(indices, null, true);
  30464. }
  30465. else {
  30466. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30467. }
  30468. };
  30469. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30470. if (totalVertices === void 0) { totalVertices = null; }
  30471. if (updatable === void 0) { updatable = false; }
  30472. if (this._indexBuffer) {
  30473. this._engine._releaseBuffer(this._indexBuffer);
  30474. }
  30475. this._disposeVertexArrayObjects();
  30476. this._indices = indices;
  30477. this._indexBufferIsUpdatable = updatable;
  30478. if (this._meshes.length !== 0 && this._indices) {
  30479. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30480. }
  30481. if (totalVertices != undefined) {
  30482. this._totalVertices = totalVertices;
  30483. }
  30484. var meshes = this._meshes;
  30485. var numOfMeshes = meshes.length;
  30486. for (var index = 0; index < numOfMeshes; index++) {
  30487. meshes[index]._createGlobalSubMesh(true);
  30488. }
  30489. this.notifyUpdate();
  30490. };
  30491. Geometry.prototype.getTotalIndices = function () {
  30492. if (!this.isReady()) {
  30493. return 0;
  30494. }
  30495. return this._indices.length;
  30496. };
  30497. Geometry.prototype.getIndices = function (copyWhenShared) {
  30498. if (!this.isReady()) {
  30499. return null;
  30500. }
  30501. var orig = this._indices;
  30502. if (!copyWhenShared || this._meshes.length === 1) {
  30503. return orig;
  30504. }
  30505. else {
  30506. var len = orig.length;
  30507. var copy = [];
  30508. for (var i = 0; i < len; i++) {
  30509. copy.push(orig[i]);
  30510. }
  30511. return copy;
  30512. }
  30513. };
  30514. Geometry.prototype.getIndexBuffer = function () {
  30515. if (!this.isReady()) {
  30516. return null;
  30517. }
  30518. return this._indexBuffer;
  30519. };
  30520. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30521. if (effect === void 0) { effect = null; }
  30522. if (!effect || !this._vertexArrayObjects) {
  30523. return;
  30524. }
  30525. if (this._vertexArrayObjects[effect.key]) {
  30526. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30527. delete this._vertexArrayObjects[effect.key];
  30528. }
  30529. };
  30530. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30531. var meshes = this._meshes;
  30532. var index = meshes.indexOf(mesh);
  30533. if (index === -1) {
  30534. return;
  30535. }
  30536. meshes.splice(index, 1);
  30537. mesh._geometry = null;
  30538. if (meshes.length === 0 && shouldDispose) {
  30539. this.dispose();
  30540. }
  30541. };
  30542. Geometry.prototype.applyToMesh = function (mesh) {
  30543. if (mesh._geometry === this) {
  30544. return;
  30545. }
  30546. var previousGeometry = mesh._geometry;
  30547. if (previousGeometry) {
  30548. previousGeometry.releaseForMesh(mesh);
  30549. }
  30550. var meshes = this._meshes;
  30551. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30552. mesh._geometry = this;
  30553. this._scene.pushGeometry(this);
  30554. meshes.push(mesh);
  30555. if (this.isReady()) {
  30556. this._applyToMesh(mesh);
  30557. }
  30558. else {
  30559. mesh._boundingInfo = this._boundingInfo;
  30560. }
  30561. };
  30562. Geometry.prototype.updateExtend = function (data, stride) {
  30563. if (data === void 0) { data = null; }
  30564. if (!data) {
  30565. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30566. }
  30567. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30568. };
  30569. Geometry.prototype._applyToMesh = function (mesh) {
  30570. var numOfMeshes = this._meshes.length;
  30571. // vertexBuffers
  30572. for (var kind in this._vertexBuffers) {
  30573. if (numOfMeshes === 1) {
  30574. this._vertexBuffers[kind].create();
  30575. }
  30576. var buffer = this._vertexBuffers[kind].getBuffer();
  30577. if (buffer)
  30578. buffer.references = numOfMeshes;
  30579. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30580. if (!this._extend) {
  30581. this.updateExtend(this._vertexBuffers[kind].getData());
  30582. }
  30583. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30584. mesh._createGlobalSubMesh(false);
  30585. //bounding info was just created again, world matrix should be applied again.
  30586. mesh._updateBoundingInfo();
  30587. }
  30588. }
  30589. // indexBuffer
  30590. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30591. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30592. }
  30593. if (this._indexBuffer) {
  30594. this._indexBuffer.references = numOfMeshes;
  30595. }
  30596. };
  30597. Geometry.prototype.notifyUpdate = function (kind) {
  30598. if (this.onGeometryUpdated) {
  30599. this.onGeometryUpdated(this, kind);
  30600. }
  30601. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30602. var mesh = _a[_i];
  30603. mesh._markSubMeshesAsAttributesDirty();
  30604. }
  30605. };
  30606. Geometry.prototype.load = function (scene, onLoaded) {
  30607. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30608. return;
  30609. }
  30610. if (this.isReady()) {
  30611. if (onLoaded) {
  30612. onLoaded();
  30613. }
  30614. return;
  30615. }
  30616. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30617. this._queueLoad(scene, onLoaded);
  30618. };
  30619. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30620. var _this = this;
  30621. if (!this.delayLoadingFile) {
  30622. return;
  30623. }
  30624. scene._addPendingData(this);
  30625. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30626. if (!_this._delayLoadingFunction) {
  30627. return;
  30628. }
  30629. _this._delayLoadingFunction(JSON.parse(data), _this);
  30630. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30631. _this._delayInfo = [];
  30632. scene._removePendingData(_this);
  30633. var meshes = _this._meshes;
  30634. var numOfMeshes = meshes.length;
  30635. for (var index = 0; index < numOfMeshes; index++) {
  30636. _this._applyToMesh(meshes[index]);
  30637. }
  30638. if (onLoaded) {
  30639. onLoaded();
  30640. }
  30641. }, function () { }, scene.database);
  30642. };
  30643. /**
  30644. * Invert the geometry to move from a right handed system to a left handed one.
  30645. */
  30646. Geometry.prototype.toLeftHanded = function () {
  30647. // Flip faces
  30648. var tIndices = this.getIndices(false);
  30649. if (tIndices != null && tIndices.length > 0) {
  30650. for (var i = 0; i < tIndices.length; i += 3) {
  30651. var tTemp = tIndices[i + 0];
  30652. tIndices[i + 0] = tIndices[i + 2];
  30653. tIndices[i + 2] = tTemp;
  30654. }
  30655. this.setIndices(tIndices);
  30656. }
  30657. // Negate position.z
  30658. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30659. if (tPositions != null && tPositions.length > 0) {
  30660. for (var i = 0; i < tPositions.length; i += 3) {
  30661. tPositions[i + 2] = -tPositions[i + 2];
  30662. }
  30663. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30664. }
  30665. // Negate normal.z
  30666. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30667. if (tNormals != null && tNormals.length > 0) {
  30668. for (var i = 0; i < tNormals.length; i += 3) {
  30669. tNormals[i + 2] = -tNormals[i + 2];
  30670. }
  30671. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30672. }
  30673. };
  30674. // Cache
  30675. Geometry.prototype._resetPointsArrayCache = function () {
  30676. this._positions = null;
  30677. };
  30678. Geometry.prototype._generatePointsArray = function () {
  30679. if (this._positions)
  30680. return true;
  30681. this._positions = [];
  30682. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30683. if (!data) {
  30684. return false;
  30685. }
  30686. for (var index = 0; index < data.length; index += 3) {
  30687. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30688. }
  30689. return true;
  30690. };
  30691. Geometry.prototype.isDisposed = function () {
  30692. return this._isDisposed;
  30693. };
  30694. Geometry.prototype._disposeVertexArrayObjects = function () {
  30695. if (this._vertexArrayObjects) {
  30696. for (var kind in this._vertexArrayObjects) {
  30697. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30698. }
  30699. this._vertexArrayObjects = {};
  30700. }
  30701. };
  30702. Geometry.prototype.dispose = function () {
  30703. var meshes = this._meshes;
  30704. var numOfMeshes = meshes.length;
  30705. var index;
  30706. for (index = 0; index < numOfMeshes; index++) {
  30707. this.releaseForMesh(meshes[index]);
  30708. }
  30709. this._meshes = [];
  30710. this._disposeVertexArrayObjects();
  30711. for (var kind in this._vertexBuffers) {
  30712. this._vertexBuffers[kind].dispose();
  30713. }
  30714. this._vertexBuffers = {};
  30715. this._totalVertices = 0;
  30716. if (this._indexBuffer) {
  30717. this._engine._releaseBuffer(this._indexBuffer);
  30718. }
  30719. this._indexBuffer = null;
  30720. this._indices = [];
  30721. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30722. this.delayLoadingFile = null;
  30723. this._delayLoadingFunction = null;
  30724. this._delayInfo = [];
  30725. this._boundingInfo = null;
  30726. this._scene.removeGeometry(this);
  30727. this._isDisposed = true;
  30728. };
  30729. Geometry.prototype.copy = function (id) {
  30730. var vertexData = new BABYLON.VertexData();
  30731. vertexData.indices = [];
  30732. var indices = this.getIndices();
  30733. if (indices) {
  30734. for (var index = 0; index < indices.length; index++) {
  30735. vertexData.indices.push(indices[index]);
  30736. }
  30737. }
  30738. var updatable = false;
  30739. var stopChecking = false;
  30740. var kind;
  30741. for (kind in this._vertexBuffers) {
  30742. // using slice() to make a copy of the array and not just reference it
  30743. var data = this.getVerticesData(kind);
  30744. if (data instanceof Float32Array) {
  30745. vertexData.set(new Float32Array(data), kind);
  30746. }
  30747. else {
  30748. vertexData.set(data.slice(0), kind);
  30749. }
  30750. if (!stopChecking) {
  30751. var vb = this.getVertexBuffer(kind);
  30752. if (vb) {
  30753. updatable = vb.isUpdatable();
  30754. stopChecking = !updatable;
  30755. }
  30756. }
  30757. }
  30758. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30759. geometry.delayLoadState = this.delayLoadState;
  30760. geometry.delayLoadingFile = this.delayLoadingFile;
  30761. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30762. for (kind in this._delayInfo) {
  30763. geometry._delayInfo = geometry._delayInfo || [];
  30764. geometry._delayInfo.push(kind);
  30765. }
  30766. // Bounding info
  30767. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30768. return geometry;
  30769. };
  30770. Geometry.prototype.serialize = function () {
  30771. var serializationObject = {};
  30772. serializationObject.id = this.id;
  30773. serializationObject.updatable = this._updatable;
  30774. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30775. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30776. }
  30777. return serializationObject;
  30778. };
  30779. Geometry.prototype.toNumberArray = function (origin) {
  30780. if (Array.isArray(origin)) {
  30781. return origin;
  30782. }
  30783. else {
  30784. return Array.prototype.slice.call(origin);
  30785. }
  30786. };
  30787. Geometry.prototype.serializeVerticeData = function () {
  30788. var serializationObject = this.serialize();
  30789. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30790. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30791. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30792. serializationObject.positions._updatable = true;
  30793. }
  30794. }
  30795. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30796. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30797. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30798. serializationObject.normals._updatable = true;
  30799. }
  30800. }
  30801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30802. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30803. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30804. serializationObject.uvs._updatable = true;
  30805. }
  30806. }
  30807. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30808. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30809. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30810. serializationObject.uv2s._updatable = true;
  30811. }
  30812. }
  30813. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30814. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30815. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30816. serializationObject.uv3s._updatable = true;
  30817. }
  30818. }
  30819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30820. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30821. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30822. serializationObject.uv4s._updatable = true;
  30823. }
  30824. }
  30825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30826. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30827. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30828. serializationObject.uv5s._updatable = true;
  30829. }
  30830. }
  30831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30832. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30833. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30834. serializationObject.uv6s._updatable = true;
  30835. }
  30836. }
  30837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30838. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30839. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30840. serializationObject.colors._updatable = true;
  30841. }
  30842. }
  30843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30844. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30845. serializationObject.matricesIndices._isExpanded = true;
  30846. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30847. serializationObject.matricesIndices._updatable = true;
  30848. }
  30849. }
  30850. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30851. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30852. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30853. serializationObject.matricesWeights._updatable = true;
  30854. }
  30855. }
  30856. serializationObject.indices = this.toNumberArray(this.getIndices());
  30857. return serializationObject;
  30858. };
  30859. // Statics
  30860. Geometry.ExtractFromMesh = function (mesh, id) {
  30861. var geometry = mesh._geometry;
  30862. if (!geometry) {
  30863. return null;
  30864. }
  30865. return geometry.copy(id);
  30866. };
  30867. /**
  30868. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30869. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30870. * Be aware Math.random() could cause collisions, but:
  30871. * "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"
  30872. */
  30873. Geometry.RandomId = function () {
  30874. return BABYLON.Tools.RandomId();
  30875. };
  30876. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30877. var scene = mesh.getScene();
  30878. // Geometry
  30879. var geometryId = parsedGeometry.geometryId;
  30880. if (geometryId) {
  30881. var geometry = scene.getGeometryByID(geometryId);
  30882. if (geometry) {
  30883. geometry.applyToMesh(mesh);
  30884. }
  30885. }
  30886. else if (parsedGeometry instanceof ArrayBuffer) {
  30887. var binaryInfo = mesh._binaryInfo;
  30888. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30889. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30890. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30891. }
  30892. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30893. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30894. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30895. }
  30896. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30897. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30898. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30899. }
  30900. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30901. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30902. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30903. }
  30904. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30905. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30906. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30907. }
  30908. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30909. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30910. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30911. }
  30912. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30913. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30914. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30915. }
  30916. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30917. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30918. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30919. }
  30920. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30921. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30922. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30923. }
  30924. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30925. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30927. }
  30928. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30929. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30930. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30931. }
  30932. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30933. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30934. mesh.setIndices(indicesData, null);
  30935. }
  30936. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30937. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30938. mesh.subMeshes = [];
  30939. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30940. var materialIndex = subMeshesData[(i * 5) + 0];
  30941. var verticesStart = subMeshesData[(i * 5) + 1];
  30942. var verticesCount = subMeshesData[(i * 5) + 2];
  30943. var indexStart = subMeshesData[(i * 5) + 3];
  30944. var indexCount = subMeshesData[(i * 5) + 4];
  30945. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30946. }
  30947. }
  30948. }
  30949. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30950. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30951. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30952. if (parsedGeometry.uvs) {
  30953. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30954. }
  30955. if (parsedGeometry.uvs2) {
  30956. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30957. }
  30958. if (parsedGeometry.uvs3) {
  30959. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30960. }
  30961. if (parsedGeometry.uvs4) {
  30962. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30963. }
  30964. if (parsedGeometry.uvs5) {
  30965. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30966. }
  30967. if (parsedGeometry.uvs6) {
  30968. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30969. }
  30970. if (parsedGeometry.colors) {
  30971. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30972. }
  30973. if (parsedGeometry.matricesIndices) {
  30974. if (!parsedGeometry.matricesIndices._isExpanded) {
  30975. var floatIndices = [];
  30976. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30977. var matricesIndex = parsedGeometry.matricesIndices[i];
  30978. floatIndices.push(matricesIndex & 0x000000FF);
  30979. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30980. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30981. floatIndices.push(matricesIndex >> 24);
  30982. }
  30983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30984. }
  30985. else {
  30986. delete parsedGeometry.matricesIndices._isExpanded;
  30987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30988. }
  30989. }
  30990. if (parsedGeometry.matricesIndicesExtra) {
  30991. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30992. var floatIndices = [];
  30993. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30994. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30995. floatIndices.push(matricesIndex & 0x000000FF);
  30996. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30997. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30998. floatIndices.push(matricesIndex >> 24);
  30999. }
  31000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31001. }
  31002. else {
  31003. delete parsedGeometry.matricesIndices._isExpanded;
  31004. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31005. }
  31006. }
  31007. if (parsedGeometry.matricesWeights) {
  31008. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31010. }
  31011. if (parsedGeometry.matricesWeightsExtra) {
  31012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31013. }
  31014. mesh.setIndices(parsedGeometry.indices, null);
  31015. }
  31016. // SubMeshes
  31017. if (parsedGeometry.subMeshes) {
  31018. mesh.subMeshes = [];
  31019. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31020. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31021. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31022. }
  31023. }
  31024. // Flat shading
  31025. if (mesh._shouldGenerateFlatShading) {
  31026. mesh.convertToFlatShadedMesh();
  31027. delete mesh._shouldGenerateFlatShading;
  31028. }
  31029. // Update
  31030. mesh.computeWorldMatrix(true);
  31031. // Octree
  31032. if (scene['_selectionOctree']) {
  31033. scene['_selectionOctree'].addMesh(mesh);
  31034. }
  31035. };
  31036. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31037. var epsilon = 1e-3;
  31038. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31039. return;
  31040. }
  31041. var noInfluenceBoneIndex = 0.0;
  31042. if (parsedGeometry.skeletonId > -1) {
  31043. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31044. if (!skeleton) {
  31045. return;
  31046. }
  31047. noInfluenceBoneIndex = skeleton.bones.length;
  31048. }
  31049. else {
  31050. return;
  31051. }
  31052. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31053. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31054. var matricesWeights = parsedGeometry.matricesWeights;
  31055. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31056. var influencers = parsedGeometry.numBoneInfluencer;
  31057. var size = matricesWeights.length;
  31058. for (var i = 0; i < size; i += 4) {
  31059. var weight = 0.0;
  31060. var firstZeroWeight = -1;
  31061. for (var j = 0; j < 4; j++) {
  31062. var w = matricesWeights[i + j];
  31063. weight += w;
  31064. if (w < epsilon && firstZeroWeight < 0) {
  31065. firstZeroWeight = j;
  31066. }
  31067. }
  31068. if (matricesWeightsExtra) {
  31069. for (var j = 0; j < 4; j++) {
  31070. var w = matricesWeightsExtra[i + j];
  31071. weight += w;
  31072. if (w < epsilon && firstZeroWeight < 0) {
  31073. firstZeroWeight = j + 4;
  31074. }
  31075. }
  31076. }
  31077. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31078. firstZeroWeight = influencers - 1;
  31079. }
  31080. if (weight > epsilon) {
  31081. var mweight = 1.0 / weight;
  31082. for (var j = 0; j < 4; j++) {
  31083. matricesWeights[i + j] *= mweight;
  31084. }
  31085. if (matricesWeightsExtra) {
  31086. for (var j = 0; j < 4; j++) {
  31087. matricesWeightsExtra[i + j] *= mweight;
  31088. }
  31089. }
  31090. }
  31091. else {
  31092. if (firstZeroWeight >= 4) {
  31093. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31094. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31095. }
  31096. else {
  31097. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31098. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31099. }
  31100. }
  31101. }
  31102. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31103. if (parsedGeometry.matricesWeightsExtra) {
  31104. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31105. }
  31106. };
  31107. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31108. if (scene.getGeometryByID(parsedVertexData.id)) {
  31109. return null; // null since geometry could be something else than a box...
  31110. }
  31111. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31112. if (BABYLON.Tags) {
  31113. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31114. }
  31115. if (parsedVertexData.delayLoadingFile) {
  31116. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31117. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31118. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31119. geometry._delayInfo = [];
  31120. if (parsedVertexData.hasUVs) {
  31121. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31122. }
  31123. if (parsedVertexData.hasUVs2) {
  31124. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31125. }
  31126. if (parsedVertexData.hasUVs3) {
  31127. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31128. }
  31129. if (parsedVertexData.hasUVs4) {
  31130. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31131. }
  31132. if (parsedVertexData.hasUVs5) {
  31133. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31134. }
  31135. if (parsedVertexData.hasUVs6) {
  31136. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31137. }
  31138. if (parsedVertexData.hasColors) {
  31139. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31140. }
  31141. if (parsedVertexData.hasMatricesIndices) {
  31142. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31143. }
  31144. if (parsedVertexData.hasMatricesWeights) {
  31145. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31146. }
  31147. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31148. }
  31149. else {
  31150. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31151. }
  31152. scene.pushGeometry(geometry, true);
  31153. return geometry;
  31154. };
  31155. return Geometry;
  31156. }());
  31157. BABYLON.Geometry = Geometry;
  31158. /////// Primitives //////////////////////////////////////////////
  31159. (function (Geometry) {
  31160. var Primitives;
  31161. (function (Primitives) {
  31162. /// Abstract class
  31163. var _Primitive = /** @class */ (function (_super) {
  31164. __extends(_Primitive, _super);
  31165. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31166. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31167. if (mesh === void 0) { mesh = null; }
  31168. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31169. _this._canBeRegenerated = _canBeRegenerated;
  31170. _this._beingRegenerated = true;
  31171. _this.regenerate();
  31172. _this._beingRegenerated = false;
  31173. return _this;
  31174. }
  31175. _Primitive.prototype.canBeRegenerated = function () {
  31176. return this._canBeRegenerated;
  31177. };
  31178. _Primitive.prototype.regenerate = function () {
  31179. if (!this._canBeRegenerated) {
  31180. return;
  31181. }
  31182. this._beingRegenerated = true;
  31183. this.setAllVerticesData(this._regenerateVertexData(), false);
  31184. this._beingRegenerated = false;
  31185. };
  31186. _Primitive.prototype.asNewGeometry = function (id) {
  31187. return _super.prototype.copy.call(this, id);
  31188. };
  31189. // overrides
  31190. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31191. if (!this._beingRegenerated) {
  31192. return;
  31193. }
  31194. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31195. };
  31196. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31197. if (!this._beingRegenerated) {
  31198. return;
  31199. }
  31200. _super.prototype.setVerticesData.call(this, kind, data, false);
  31201. };
  31202. // to override
  31203. // protected
  31204. _Primitive.prototype._regenerateVertexData = function () {
  31205. throw new Error("Abstract method");
  31206. };
  31207. _Primitive.prototype.copy = function (id) {
  31208. throw new Error("Must be overriden in sub-classes.");
  31209. };
  31210. _Primitive.prototype.serialize = function () {
  31211. var serializationObject = _super.prototype.serialize.call(this);
  31212. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31213. return serializationObject;
  31214. };
  31215. return _Primitive;
  31216. }(Geometry));
  31217. Primitives._Primitive = _Primitive;
  31218. var Ribbon = /** @class */ (function (_super) {
  31219. __extends(Ribbon, _super);
  31220. // Members
  31221. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31222. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31223. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31224. _this.pathArray = pathArray;
  31225. _this.closeArray = closeArray;
  31226. _this.closePath = closePath;
  31227. _this.offset = offset;
  31228. _this.side = side;
  31229. return _this;
  31230. }
  31231. Ribbon.prototype._regenerateVertexData = function () {
  31232. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31233. };
  31234. Ribbon.prototype.copy = function (id) {
  31235. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31236. };
  31237. return Ribbon;
  31238. }(_Primitive));
  31239. Primitives.Ribbon = Ribbon;
  31240. var Box = /** @class */ (function (_super) {
  31241. __extends(Box, _super);
  31242. // Members
  31243. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31244. if (mesh === void 0) { mesh = null; }
  31245. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31246. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31247. _this.size = size;
  31248. _this.side = side;
  31249. return _this;
  31250. }
  31251. Box.prototype._regenerateVertexData = function () {
  31252. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31253. };
  31254. Box.prototype.copy = function (id) {
  31255. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31256. };
  31257. Box.prototype.serialize = function () {
  31258. var serializationObject = _super.prototype.serialize.call(this);
  31259. serializationObject.size = this.size;
  31260. return serializationObject;
  31261. };
  31262. Box.Parse = function (parsedBox, scene) {
  31263. if (scene.getGeometryByID(parsedBox.id)) {
  31264. return null; // null since geometry could be something else than a box...
  31265. }
  31266. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31267. if (BABYLON.Tags) {
  31268. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31269. }
  31270. scene.pushGeometry(box, true);
  31271. return box;
  31272. };
  31273. return Box;
  31274. }(_Primitive));
  31275. Primitives.Box = Box;
  31276. var Sphere = /** @class */ (function (_super) {
  31277. __extends(Sphere, _super);
  31278. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31279. if (mesh === void 0) { mesh = null; }
  31280. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31281. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31282. _this.segments = segments;
  31283. _this.diameter = diameter;
  31284. _this.side = side;
  31285. return _this;
  31286. }
  31287. Sphere.prototype._regenerateVertexData = function () {
  31288. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31289. };
  31290. Sphere.prototype.copy = function (id) {
  31291. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31292. };
  31293. Sphere.prototype.serialize = function () {
  31294. var serializationObject = _super.prototype.serialize.call(this);
  31295. serializationObject.segments = this.segments;
  31296. serializationObject.diameter = this.diameter;
  31297. return serializationObject;
  31298. };
  31299. Sphere.Parse = function (parsedSphere, scene) {
  31300. if (scene.getGeometryByID(parsedSphere.id)) {
  31301. return null; // null since geometry could be something else than a sphere...
  31302. }
  31303. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31304. if (BABYLON.Tags) {
  31305. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31306. }
  31307. scene.pushGeometry(sphere, true);
  31308. return sphere;
  31309. };
  31310. return Sphere;
  31311. }(_Primitive));
  31312. Primitives.Sphere = Sphere;
  31313. var Disc = /** @class */ (function (_super) {
  31314. __extends(Disc, _super);
  31315. // Members
  31316. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31317. if (mesh === void 0) { mesh = null; }
  31318. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31319. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31320. _this.radius = radius;
  31321. _this.tessellation = tessellation;
  31322. _this.side = side;
  31323. return _this;
  31324. }
  31325. Disc.prototype._regenerateVertexData = function () {
  31326. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31327. };
  31328. Disc.prototype.copy = function (id) {
  31329. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31330. };
  31331. return Disc;
  31332. }(_Primitive));
  31333. Primitives.Disc = Disc;
  31334. var Cylinder = /** @class */ (function (_super) {
  31335. __extends(Cylinder, _super);
  31336. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31337. if (subdivisions === void 0) { subdivisions = 1; }
  31338. if (mesh === void 0) { mesh = null; }
  31339. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31340. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31341. _this.height = height;
  31342. _this.diameterTop = diameterTop;
  31343. _this.diameterBottom = diameterBottom;
  31344. _this.tessellation = tessellation;
  31345. _this.subdivisions = subdivisions;
  31346. _this.side = side;
  31347. return _this;
  31348. }
  31349. Cylinder.prototype._regenerateVertexData = function () {
  31350. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31351. };
  31352. Cylinder.prototype.copy = function (id) {
  31353. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31354. };
  31355. Cylinder.prototype.serialize = function () {
  31356. var serializationObject = _super.prototype.serialize.call(this);
  31357. serializationObject.height = this.height;
  31358. serializationObject.diameterTop = this.diameterTop;
  31359. serializationObject.diameterBottom = this.diameterBottom;
  31360. serializationObject.tessellation = this.tessellation;
  31361. return serializationObject;
  31362. };
  31363. Cylinder.Parse = function (parsedCylinder, scene) {
  31364. if (scene.getGeometryByID(parsedCylinder.id)) {
  31365. return null; // null since geometry could be something else than a cylinder...
  31366. }
  31367. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31368. if (BABYLON.Tags) {
  31369. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31370. }
  31371. scene.pushGeometry(cylinder, true);
  31372. return cylinder;
  31373. };
  31374. return Cylinder;
  31375. }(_Primitive));
  31376. Primitives.Cylinder = Cylinder;
  31377. var Torus = /** @class */ (function (_super) {
  31378. __extends(Torus, _super);
  31379. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31380. if (mesh === void 0) { mesh = null; }
  31381. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31382. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31383. _this.diameter = diameter;
  31384. _this.thickness = thickness;
  31385. _this.tessellation = tessellation;
  31386. _this.side = side;
  31387. return _this;
  31388. }
  31389. Torus.prototype._regenerateVertexData = function () {
  31390. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31391. };
  31392. Torus.prototype.copy = function (id) {
  31393. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31394. };
  31395. Torus.prototype.serialize = function () {
  31396. var serializationObject = _super.prototype.serialize.call(this);
  31397. serializationObject.diameter = this.diameter;
  31398. serializationObject.thickness = this.thickness;
  31399. serializationObject.tessellation = this.tessellation;
  31400. return serializationObject;
  31401. };
  31402. Torus.Parse = function (parsedTorus, scene) {
  31403. if (scene.getGeometryByID(parsedTorus.id)) {
  31404. return null; // null since geometry could be something else than a torus...
  31405. }
  31406. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31407. if (BABYLON.Tags) {
  31408. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31409. }
  31410. scene.pushGeometry(torus, true);
  31411. return torus;
  31412. };
  31413. return Torus;
  31414. }(_Primitive));
  31415. Primitives.Torus = Torus;
  31416. var Ground = /** @class */ (function (_super) {
  31417. __extends(Ground, _super);
  31418. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31419. if (mesh === void 0) { mesh = null; }
  31420. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31421. _this.width = width;
  31422. _this.height = height;
  31423. _this.subdivisions = subdivisions;
  31424. return _this;
  31425. }
  31426. Ground.prototype._regenerateVertexData = function () {
  31427. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31428. };
  31429. Ground.prototype.copy = function (id) {
  31430. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31431. };
  31432. Ground.prototype.serialize = function () {
  31433. var serializationObject = _super.prototype.serialize.call(this);
  31434. serializationObject.width = this.width;
  31435. serializationObject.height = this.height;
  31436. serializationObject.subdivisions = this.subdivisions;
  31437. return serializationObject;
  31438. };
  31439. Ground.Parse = function (parsedGround, scene) {
  31440. if (scene.getGeometryByID(parsedGround.id)) {
  31441. return null; // null since geometry could be something else than a ground...
  31442. }
  31443. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31444. if (BABYLON.Tags) {
  31445. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31446. }
  31447. scene.pushGeometry(ground, true);
  31448. return ground;
  31449. };
  31450. return Ground;
  31451. }(_Primitive));
  31452. Primitives.Ground = Ground;
  31453. var TiledGround = /** @class */ (function (_super) {
  31454. __extends(TiledGround, _super);
  31455. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31456. if (mesh === void 0) { mesh = null; }
  31457. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31458. _this.xmin = xmin;
  31459. _this.zmin = zmin;
  31460. _this.xmax = xmax;
  31461. _this.zmax = zmax;
  31462. _this.subdivisions = subdivisions;
  31463. _this.precision = precision;
  31464. return _this;
  31465. }
  31466. TiledGround.prototype._regenerateVertexData = function () {
  31467. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31468. };
  31469. TiledGround.prototype.copy = function (id) {
  31470. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31471. };
  31472. return TiledGround;
  31473. }(_Primitive));
  31474. Primitives.TiledGround = TiledGround;
  31475. var Plane = /** @class */ (function (_super) {
  31476. __extends(Plane, _super);
  31477. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31478. if (mesh === void 0) { mesh = null; }
  31479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31481. _this.size = size;
  31482. _this.side = side;
  31483. return _this;
  31484. }
  31485. Plane.prototype._regenerateVertexData = function () {
  31486. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31487. };
  31488. Plane.prototype.copy = function (id) {
  31489. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31490. };
  31491. Plane.prototype.serialize = function () {
  31492. var serializationObject = _super.prototype.serialize.call(this);
  31493. serializationObject.size = this.size;
  31494. return serializationObject;
  31495. };
  31496. Plane.Parse = function (parsedPlane, scene) {
  31497. if (scene.getGeometryByID(parsedPlane.id)) {
  31498. return null; // null since geometry could be something else than a ground...
  31499. }
  31500. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31501. if (BABYLON.Tags) {
  31502. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31503. }
  31504. scene.pushGeometry(plane, true);
  31505. return plane;
  31506. };
  31507. return Plane;
  31508. }(_Primitive));
  31509. Primitives.Plane = Plane;
  31510. var TorusKnot = /** @class */ (function (_super) {
  31511. __extends(TorusKnot, _super);
  31512. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31513. if (mesh === void 0) { mesh = null; }
  31514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31516. _this.radius = radius;
  31517. _this.tube = tube;
  31518. _this.radialSegments = radialSegments;
  31519. _this.tubularSegments = tubularSegments;
  31520. _this.p = p;
  31521. _this.q = q;
  31522. _this.side = side;
  31523. return _this;
  31524. }
  31525. TorusKnot.prototype._regenerateVertexData = function () {
  31526. 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 });
  31527. };
  31528. TorusKnot.prototype.copy = function (id) {
  31529. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31530. };
  31531. TorusKnot.prototype.serialize = function () {
  31532. var serializationObject = _super.prototype.serialize.call(this);
  31533. serializationObject.radius = this.radius;
  31534. serializationObject.tube = this.tube;
  31535. serializationObject.radialSegments = this.radialSegments;
  31536. serializationObject.tubularSegments = this.tubularSegments;
  31537. serializationObject.p = this.p;
  31538. serializationObject.q = this.q;
  31539. return serializationObject;
  31540. };
  31541. ;
  31542. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31543. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31544. return null; // null since geometry could be something else than a ground...
  31545. }
  31546. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31547. if (BABYLON.Tags) {
  31548. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31549. }
  31550. scene.pushGeometry(torusKnot, true);
  31551. return torusKnot;
  31552. };
  31553. return TorusKnot;
  31554. }(_Primitive));
  31555. Primitives.TorusKnot = TorusKnot;
  31556. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31557. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31558. })(BABYLON || (BABYLON = {}));
  31559. //# sourceMappingURL=babylon.geometry.js.map
  31560. var BABYLON;
  31561. (function (BABYLON) {
  31562. var PostProcessManager = /** @class */ (function () {
  31563. function PostProcessManager(scene) {
  31564. this._vertexBuffers = {};
  31565. this._scene = scene;
  31566. }
  31567. PostProcessManager.prototype._prepareBuffers = function () {
  31568. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31569. return;
  31570. }
  31571. // VBO
  31572. var vertices = [];
  31573. vertices.push(1, 1);
  31574. vertices.push(-1, 1);
  31575. vertices.push(-1, -1);
  31576. vertices.push(1, -1);
  31577. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31578. this._buildIndexBuffer();
  31579. };
  31580. PostProcessManager.prototype._buildIndexBuffer = function () {
  31581. // Indices
  31582. var indices = [];
  31583. indices.push(0);
  31584. indices.push(1);
  31585. indices.push(2);
  31586. indices.push(0);
  31587. indices.push(2);
  31588. indices.push(3);
  31589. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31590. };
  31591. PostProcessManager.prototype._rebuild = function () {
  31592. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31593. if (!vb) {
  31594. return;
  31595. }
  31596. vb._rebuild();
  31597. this._buildIndexBuffer();
  31598. };
  31599. // Methods
  31600. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31601. if (sourceTexture === void 0) { sourceTexture = null; }
  31602. if (postProcesses === void 0) { postProcesses = null; }
  31603. var camera = this._scene.activeCamera;
  31604. if (!camera) {
  31605. return false;
  31606. }
  31607. var postProcesses = postProcesses || camera._postProcesses;
  31608. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31609. return false;
  31610. }
  31611. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31612. return true;
  31613. };
  31614. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31615. if (targetTexture === void 0) { targetTexture = null; }
  31616. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31617. if (!this._scene.activeCamera) {
  31618. return;
  31619. }
  31620. var engine = this._scene.getEngine();
  31621. for (var index = 0; index < postProcesses.length; index++) {
  31622. if (index < postProcesses.length - 1) {
  31623. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31624. }
  31625. else {
  31626. if (targetTexture) {
  31627. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31628. }
  31629. else {
  31630. engine.restoreDefaultFramebuffer();
  31631. }
  31632. }
  31633. var pp = postProcesses[index];
  31634. var effect = pp.apply();
  31635. if (effect) {
  31636. pp.onBeforeRenderObservable.notifyObservers(effect);
  31637. // VBOs
  31638. this._prepareBuffers();
  31639. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31640. // Draw order
  31641. engine.draw(true, 0, 6);
  31642. pp.onAfterRenderObservable.notifyObservers(effect);
  31643. }
  31644. }
  31645. // Restore depth buffer
  31646. engine.setDepthBuffer(true);
  31647. engine.setDepthWrite(true);
  31648. };
  31649. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31650. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31651. var camera = this._scene.activeCamera;
  31652. if (!camera) {
  31653. return;
  31654. }
  31655. postProcesses = postProcesses || camera._postProcesses;
  31656. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31657. return;
  31658. }
  31659. var engine = this._scene.getEngine();
  31660. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31661. if (index < len - 1) {
  31662. postProcesses[index + 1].activate(camera, targetTexture);
  31663. }
  31664. else {
  31665. if (targetTexture) {
  31666. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31667. }
  31668. else {
  31669. engine.restoreDefaultFramebuffer();
  31670. }
  31671. }
  31672. if (doNotPresent) {
  31673. break;
  31674. }
  31675. var pp = postProcesses[index];
  31676. var effect = pp.apply();
  31677. if (effect) {
  31678. pp.onBeforeRenderObservable.notifyObservers(effect);
  31679. // VBOs
  31680. this._prepareBuffers();
  31681. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31682. // Draw order
  31683. engine.draw(true, 0, 6);
  31684. pp.onAfterRenderObservable.notifyObservers(effect);
  31685. }
  31686. }
  31687. // Restore states
  31688. engine.setDepthBuffer(true);
  31689. engine.setDepthWrite(true);
  31690. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31691. };
  31692. PostProcessManager.prototype.dispose = function () {
  31693. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31694. if (buffer) {
  31695. buffer.dispose();
  31696. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31697. }
  31698. if (this._indexBuffer) {
  31699. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31700. this._indexBuffer = null;
  31701. }
  31702. };
  31703. return PostProcessManager;
  31704. }());
  31705. BABYLON.PostProcessManager = PostProcessManager;
  31706. })(BABYLON || (BABYLON = {}));
  31707. //# sourceMappingURL=babylon.postProcessManager.js.map
  31708. var BABYLON;
  31709. (function (BABYLON) {
  31710. /**
  31711. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31712. */
  31713. var PerformanceMonitor = /** @class */ (function () {
  31714. /**
  31715. * constructor
  31716. * @param frameSampleSize The number of samples required to saturate the sliding window
  31717. */
  31718. function PerformanceMonitor(frameSampleSize) {
  31719. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31720. this._enabled = true;
  31721. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31722. }
  31723. /**
  31724. * Samples current frame
  31725. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31726. */
  31727. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31728. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31729. if (!this._enabled)
  31730. return;
  31731. if (this._lastFrameTimeMs != null) {
  31732. var dt = timeMs - this._lastFrameTimeMs;
  31733. this._rollingFrameTime.add(dt);
  31734. }
  31735. this._lastFrameTimeMs = timeMs;
  31736. };
  31737. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31738. /**
  31739. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31740. * @return Average frame time in milliseconds
  31741. */
  31742. get: function () {
  31743. return this._rollingFrameTime.average;
  31744. },
  31745. enumerable: true,
  31746. configurable: true
  31747. });
  31748. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31749. /**
  31750. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31751. * @return Frame time variance in milliseconds squared
  31752. */
  31753. get: function () {
  31754. return this._rollingFrameTime.variance;
  31755. },
  31756. enumerable: true,
  31757. configurable: true
  31758. });
  31759. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31760. /**
  31761. * Returns the frame time of the most recent frame
  31762. * @return Frame time in milliseconds
  31763. */
  31764. get: function () {
  31765. return this._rollingFrameTime.history(0);
  31766. },
  31767. enumerable: true,
  31768. configurable: true
  31769. });
  31770. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31771. /**
  31772. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31773. * @return Framerate in frames per second
  31774. */
  31775. get: function () {
  31776. return 1000.0 / this._rollingFrameTime.average;
  31777. },
  31778. enumerable: true,
  31779. configurable: true
  31780. });
  31781. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31782. /**
  31783. * Returns the average framerate in frames per second using the most recent frame time
  31784. * @return Framerate in frames per second
  31785. */
  31786. get: function () {
  31787. var history = this._rollingFrameTime.history(0);
  31788. if (history === 0) {
  31789. return 0;
  31790. }
  31791. return 1000.0 / history;
  31792. },
  31793. enumerable: true,
  31794. configurable: true
  31795. });
  31796. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31797. /**
  31798. * Returns true if enough samples have been taken to completely fill the sliding window
  31799. * @return true if saturated
  31800. */
  31801. get: function () {
  31802. return this._rollingFrameTime.isSaturated();
  31803. },
  31804. enumerable: true,
  31805. configurable: true
  31806. });
  31807. /**
  31808. * Enables contributions to the sliding window sample set
  31809. */
  31810. PerformanceMonitor.prototype.enable = function () {
  31811. this._enabled = true;
  31812. };
  31813. /**
  31814. * Disables contributions to the sliding window sample set
  31815. * Samples will not be interpolated over the disabled period
  31816. */
  31817. PerformanceMonitor.prototype.disable = function () {
  31818. this._enabled = false;
  31819. //clear last sample to avoid interpolating over the disabled period when next enabled
  31820. this._lastFrameTimeMs = null;
  31821. this._lastChangeTimeMs = null;
  31822. };
  31823. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31824. /**
  31825. * Returns true if sampling is enabled
  31826. * @return true if enabled
  31827. */
  31828. get: function () {
  31829. return this._enabled;
  31830. },
  31831. enumerable: true,
  31832. configurable: true
  31833. });
  31834. /**
  31835. * Resets performance monitor
  31836. */
  31837. PerformanceMonitor.prototype.reset = function () {
  31838. //clear last sample to avoid interpolating over the disabled period when next enabled
  31839. this._lastFrameTimeMs = null;
  31840. this._lastChangeTimeMs = null;
  31841. //wipe record
  31842. this._rollingFrameTime.reset();
  31843. };
  31844. return PerformanceMonitor;
  31845. }());
  31846. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31847. /**
  31848. * RollingAverage
  31849. *
  31850. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31851. */
  31852. var RollingAverage = /** @class */ (function () {
  31853. /**
  31854. * constructor
  31855. * @param length The number of samples required to saturate the sliding window
  31856. */
  31857. function RollingAverage(length) {
  31858. this._samples = new Array(length);
  31859. this.reset();
  31860. }
  31861. /**
  31862. * Adds a sample to the sample set
  31863. * @param v The sample value
  31864. */
  31865. RollingAverage.prototype.add = function (v) {
  31866. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31867. var delta;
  31868. //we need to check if we've already wrapped round
  31869. if (this.isSaturated()) {
  31870. //remove bottom of stack from mean
  31871. var bottomValue = this._samples[this._pos];
  31872. delta = bottomValue - this.average;
  31873. this.average -= delta / (this._sampleCount - 1);
  31874. this._m2 -= delta * (bottomValue - this.average);
  31875. }
  31876. else {
  31877. this._sampleCount++;
  31878. }
  31879. //add new value to mean
  31880. delta = v - this.average;
  31881. this.average += delta / (this._sampleCount);
  31882. this._m2 += delta * (v - this.average);
  31883. //set the new variance
  31884. this.variance = this._m2 / (this._sampleCount - 1);
  31885. this._samples[this._pos] = v;
  31886. this._pos++;
  31887. this._pos %= this._samples.length; //positive wrap around
  31888. };
  31889. /**
  31890. * Returns previously added values or null if outside of history or outside the sliding window domain
  31891. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31892. * @return Value previously recorded with add() or null if outside of range
  31893. */
  31894. RollingAverage.prototype.history = function (i) {
  31895. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31896. return 0;
  31897. }
  31898. var i0 = this._wrapPosition(this._pos - 1.0);
  31899. return this._samples[this._wrapPosition(i0 - i)];
  31900. };
  31901. /**
  31902. * Returns true if enough samples have been taken to completely fill the sliding window
  31903. * @return true if sample-set saturated
  31904. */
  31905. RollingAverage.prototype.isSaturated = function () {
  31906. return this._sampleCount >= this._samples.length;
  31907. };
  31908. /**
  31909. * Resets the rolling average (equivalent to 0 samples taken so far)
  31910. */
  31911. RollingAverage.prototype.reset = function () {
  31912. this.average = 0;
  31913. this.variance = 0;
  31914. this._sampleCount = 0;
  31915. this._pos = 0;
  31916. this._m2 = 0;
  31917. };
  31918. /**
  31919. * Wraps a value around the sample range boundaries
  31920. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31921. * @return Wrapped position in sample range
  31922. */
  31923. RollingAverage.prototype._wrapPosition = function (i) {
  31924. var max = this._samples.length;
  31925. return ((i % max) + max) % max;
  31926. };
  31927. return RollingAverage;
  31928. }());
  31929. BABYLON.RollingAverage = RollingAverage;
  31930. })(BABYLON || (BABYLON = {}));
  31931. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31932. var BABYLON;
  31933. (function (BABYLON) {
  31934. /**
  31935. * This groups together the common properties used for image processing either in direct forward pass
  31936. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31937. * or not.
  31938. */
  31939. var ImageProcessingConfiguration = /** @class */ (function () {
  31940. function ImageProcessingConfiguration() {
  31941. /**
  31942. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31943. */
  31944. this.colorCurves = new BABYLON.ColorCurves();
  31945. this._colorCurvesEnabled = false;
  31946. this._colorGradingEnabled = false;
  31947. this._colorGradingWithGreenDepth = true;
  31948. this._colorGradingBGR = true;
  31949. this._exposure = 1.0;
  31950. this._toneMappingEnabled = false;
  31951. this._contrast = 1.0;
  31952. /**
  31953. * Vignette stretch size.
  31954. */
  31955. this.vignetteStretch = 0;
  31956. /**
  31957. * Vignette centre X Offset.
  31958. */
  31959. this.vignetteCentreX = 0;
  31960. /**
  31961. * Vignette centre Y Offset.
  31962. */
  31963. this.vignetteCentreY = 0;
  31964. /**
  31965. * Vignette weight or intensity of the vignette effect.
  31966. */
  31967. this.vignetteWeight = 1.5;
  31968. /**
  31969. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31970. * if vignetteEnabled is set to true.
  31971. */
  31972. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31973. /**
  31974. * Camera field of view used by the Vignette effect.
  31975. */
  31976. this.vignetteCameraFov = 0.5;
  31977. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31978. this._vignetteEnabled = false;
  31979. this._applyByPostProcess = false;
  31980. /**
  31981. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31982. * @type {BABYLON.Observable}
  31983. */
  31984. this.onUpdateParameters = new BABYLON.Observable();
  31985. }
  31986. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31987. /**
  31988. * Gets wether the color curves effect is enabled.
  31989. */
  31990. get: function () {
  31991. return this._colorCurvesEnabled;
  31992. },
  31993. /**
  31994. * Sets wether the color curves effect is enabled.
  31995. */
  31996. set: function (value) {
  31997. if (this._colorCurvesEnabled === value) {
  31998. return;
  31999. }
  32000. this._colorCurvesEnabled = value;
  32001. this._updateParameters();
  32002. },
  32003. enumerable: true,
  32004. configurable: true
  32005. });
  32006. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32007. /**
  32008. * Gets wether the color grading effect is enabled.
  32009. */
  32010. get: function () {
  32011. return this._colorGradingEnabled;
  32012. },
  32013. /**
  32014. * Sets wether the color grading effect is enabled.
  32015. */
  32016. set: function (value) {
  32017. if (this._colorGradingEnabled === value) {
  32018. return;
  32019. }
  32020. this._colorGradingEnabled = value;
  32021. this._updateParameters();
  32022. },
  32023. enumerable: true,
  32024. configurable: true
  32025. });
  32026. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32027. /**
  32028. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32029. */
  32030. get: function () {
  32031. return this._colorGradingWithGreenDepth;
  32032. },
  32033. /**
  32034. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32035. */
  32036. set: function (value) {
  32037. if (this._colorGradingWithGreenDepth === value) {
  32038. return;
  32039. }
  32040. this._colorGradingWithGreenDepth = value;
  32041. this._updateParameters();
  32042. },
  32043. enumerable: true,
  32044. configurable: true
  32045. });
  32046. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32047. /**
  32048. * Gets wether the color grading texture contains BGR values.
  32049. */
  32050. get: function () {
  32051. return this._colorGradingBGR;
  32052. },
  32053. /**
  32054. * Sets wether the color grading texture contains BGR values.
  32055. */
  32056. set: function (value) {
  32057. if (this._colorGradingBGR === value) {
  32058. return;
  32059. }
  32060. this._colorGradingBGR = value;
  32061. this._updateParameters();
  32062. },
  32063. enumerable: true,
  32064. configurable: true
  32065. });
  32066. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32067. /**
  32068. * Gets the Exposure used in the effect.
  32069. */
  32070. get: function () {
  32071. return this._exposure;
  32072. },
  32073. /**
  32074. * Sets the Exposure used in the effect.
  32075. */
  32076. set: function (value) {
  32077. if (this._exposure === value) {
  32078. return;
  32079. }
  32080. this._exposure = value;
  32081. this._updateParameters();
  32082. },
  32083. enumerable: true,
  32084. configurable: true
  32085. });
  32086. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32087. /**
  32088. * Gets wether the tone mapping effect is enabled.
  32089. */
  32090. get: function () {
  32091. return this._toneMappingEnabled;
  32092. },
  32093. /**
  32094. * Sets wether the tone mapping effect is enabled.
  32095. */
  32096. set: function (value) {
  32097. if (this._toneMappingEnabled === value) {
  32098. return;
  32099. }
  32100. this._toneMappingEnabled = value;
  32101. this._updateParameters();
  32102. },
  32103. enumerable: true,
  32104. configurable: true
  32105. });
  32106. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32107. /**
  32108. * Gets the contrast used in the effect.
  32109. */
  32110. get: function () {
  32111. return this._contrast;
  32112. },
  32113. /**
  32114. * Sets the contrast used in the effect.
  32115. */
  32116. set: function (value) {
  32117. if (this._contrast === value) {
  32118. return;
  32119. }
  32120. this._contrast = value;
  32121. this._updateParameters();
  32122. },
  32123. enumerable: true,
  32124. configurable: true
  32125. });
  32126. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32127. /**
  32128. * Gets the vignette blend mode allowing different kind of effect.
  32129. */
  32130. get: function () {
  32131. return this._vignetteBlendMode;
  32132. },
  32133. /**
  32134. * Sets the vignette blend mode allowing different kind of effect.
  32135. */
  32136. set: function (value) {
  32137. if (this._vignetteBlendMode === value) {
  32138. return;
  32139. }
  32140. this._vignetteBlendMode = value;
  32141. this._updateParameters();
  32142. },
  32143. enumerable: true,
  32144. configurable: true
  32145. });
  32146. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32147. /**
  32148. * Gets wether the vignette effect is enabled.
  32149. */
  32150. get: function () {
  32151. return this._vignetteEnabled;
  32152. },
  32153. /**
  32154. * Sets wether the vignette effect is enabled.
  32155. */
  32156. set: function (value) {
  32157. if (this._vignetteEnabled === value) {
  32158. return;
  32159. }
  32160. this._vignetteEnabled = value;
  32161. this._updateParameters();
  32162. },
  32163. enumerable: true,
  32164. configurable: true
  32165. });
  32166. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32167. /**
  32168. * Gets wether the image processing is applied through a post process or not.
  32169. */
  32170. get: function () {
  32171. return this._applyByPostProcess;
  32172. },
  32173. /**
  32174. * Sets wether the image processing is applied through a post process or not.
  32175. */
  32176. set: function (value) {
  32177. if (this._applyByPostProcess === value) {
  32178. return;
  32179. }
  32180. this._applyByPostProcess = value;
  32181. this._updateParameters();
  32182. },
  32183. enumerable: true,
  32184. configurable: true
  32185. });
  32186. /**
  32187. * Method called each time the image processing information changes requires to recompile the effect.
  32188. */
  32189. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32190. this.onUpdateParameters.notifyObservers(this);
  32191. };
  32192. ImageProcessingConfiguration.prototype.getClassName = function () {
  32193. return "ImageProcessingConfiguration";
  32194. };
  32195. /**
  32196. * Prepare the list of uniforms associated with the Image Processing effects.
  32197. * @param uniformsList The list of uniforms used in the effect
  32198. * @param defines the list of defines currently in use
  32199. */
  32200. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32201. if (defines.EXPOSURE) {
  32202. uniforms.push("exposureLinear");
  32203. }
  32204. if (defines.CONTRAST) {
  32205. uniforms.push("contrast");
  32206. }
  32207. if (defines.COLORGRADING) {
  32208. uniforms.push("colorTransformSettings");
  32209. }
  32210. if (defines.VIGNETTE) {
  32211. uniforms.push("vInverseScreenSize");
  32212. uniforms.push("vignetteSettings1");
  32213. uniforms.push("vignetteSettings2");
  32214. }
  32215. if (defines.COLORCURVES) {
  32216. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32217. }
  32218. };
  32219. /**
  32220. * Prepare the list of samplers associated with the Image Processing effects.
  32221. * @param uniformsList The list of uniforms used in the effect
  32222. * @param defines the list of defines currently in use
  32223. */
  32224. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32225. if (defines.COLORGRADING) {
  32226. samplersList.push("txColorTransform");
  32227. }
  32228. };
  32229. /**
  32230. * Prepare the list of defines associated to the shader.
  32231. * @param defines the list of defines to complete
  32232. */
  32233. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32234. if (forPostProcess === void 0) { forPostProcess = false; }
  32235. if (forPostProcess !== this.applyByPostProcess) {
  32236. defines.VIGNETTE = false;
  32237. defines.TONEMAPPING = false;
  32238. defines.CONTRAST = false;
  32239. defines.EXPOSURE = false;
  32240. defines.COLORCURVES = false;
  32241. defines.COLORGRADING = false;
  32242. defines.COLORGRADING3D = false;
  32243. defines.IMAGEPROCESSING = false;
  32244. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32245. return;
  32246. }
  32247. defines.VIGNETTE = this.vignetteEnabled;
  32248. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32249. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32250. defines.TONEMAPPING = this.toneMappingEnabled;
  32251. defines.CONTRAST = (this.contrast !== 1.0);
  32252. defines.EXPOSURE = (this.exposure !== 1.0);
  32253. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32254. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32255. if (defines.COLORGRADING) {
  32256. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32257. }
  32258. else {
  32259. defines.COLORGRADING3D = false;
  32260. }
  32261. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32262. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32263. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32264. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32265. };
  32266. /**
  32267. * Returns true if all the image processing information are ready.
  32268. */
  32269. ImageProcessingConfiguration.prototype.isReady = function () {
  32270. // Color Grading texure can not be none blocking.
  32271. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32272. };
  32273. /**
  32274. * Binds the image processing to the shader.
  32275. * @param effect The effect to bind to
  32276. */
  32277. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32278. if (aspectRatio === void 0) { aspectRatio = 1; }
  32279. // Color Curves
  32280. if (this._colorCurvesEnabled && this.colorCurves) {
  32281. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32282. }
  32283. // Vignette
  32284. if (this._vignetteEnabled) {
  32285. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32286. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32287. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32288. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32289. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32290. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32291. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32292. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32293. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32294. var vignettePower = -2.0 * this.vignetteWeight;
  32295. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32296. }
  32297. // Exposure
  32298. effect.setFloat("exposureLinear", this.exposure);
  32299. // Contrast
  32300. effect.setFloat("contrast", this.contrast);
  32301. // Color transform settings
  32302. if (this.colorGradingTexture) {
  32303. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32304. var textureSize = this.colorGradingTexture.getSize().height;
  32305. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32306. 0.5 / textureSize, // textureOffset
  32307. textureSize, // textureSize
  32308. this.colorGradingTexture.level // weight
  32309. );
  32310. }
  32311. };
  32312. /**
  32313. * Clones the current image processing instance.
  32314. * @return The cloned image processing
  32315. */
  32316. ImageProcessingConfiguration.prototype.clone = function () {
  32317. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32318. };
  32319. /**
  32320. * Serializes the current image processing instance to a json representation.
  32321. * @return a JSON representation
  32322. */
  32323. ImageProcessingConfiguration.prototype.serialize = function () {
  32324. return BABYLON.SerializationHelper.Serialize(this);
  32325. };
  32326. /**
  32327. * Parses the image processing from a json representation.
  32328. * @param source the JSON source to parse
  32329. * @return The parsed image processing
  32330. */
  32331. ImageProcessingConfiguration.Parse = function (source) {
  32332. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32333. };
  32334. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32335. /**
  32336. * Used to apply the vignette as a mix with the pixel color.
  32337. */
  32338. get: function () {
  32339. return this._VIGNETTEMODE_MULTIPLY;
  32340. },
  32341. enumerable: true,
  32342. configurable: true
  32343. });
  32344. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32345. /**
  32346. * Used to apply the vignette as a replacement of the pixel color.
  32347. */
  32348. get: function () {
  32349. return this._VIGNETTEMODE_OPAQUE;
  32350. },
  32351. enumerable: true,
  32352. configurable: true
  32353. });
  32354. // Static constants associated to the image processing.
  32355. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32356. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32357. __decorate([
  32358. BABYLON.serializeAsColorCurves()
  32359. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32363. __decorate([
  32364. BABYLON.serializeAsTexture()
  32365. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32375. __decorate([
  32376. BABYLON.serialize()
  32377. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32378. __decorate([
  32379. BABYLON.serialize()
  32380. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32381. __decorate([
  32382. BABYLON.serialize()
  32383. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32384. __decorate([
  32385. BABYLON.serialize()
  32386. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32387. __decorate([
  32388. BABYLON.serialize()
  32389. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32390. __decorate([
  32391. BABYLON.serialize()
  32392. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32393. __decorate([
  32394. BABYLON.serialize()
  32395. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32396. __decorate([
  32397. BABYLON.serializeAsColor4()
  32398. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32399. __decorate([
  32400. BABYLON.serialize()
  32401. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32402. __decorate([
  32403. BABYLON.serialize()
  32404. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32405. __decorate([
  32406. BABYLON.serialize()
  32407. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32408. __decorate([
  32409. BABYLON.serialize()
  32410. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32411. return ImageProcessingConfiguration;
  32412. }());
  32413. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32414. })(BABYLON || (BABYLON = {}));
  32415. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32416. var BABYLON;
  32417. (function (BABYLON) {
  32418. /**
  32419. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32420. * It can help converting any input color in a desired output one. This can then be used to create effects
  32421. * from sepia, black and white to sixties or futuristic rendering...
  32422. *
  32423. * The only supported format is currently 3dl.
  32424. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32425. */
  32426. var ColorGradingTexture = /** @class */ (function (_super) {
  32427. __extends(ColorGradingTexture, _super);
  32428. /**
  32429. * Instantiates a ColorGradingTexture from the following parameters.
  32430. *
  32431. * @param url The location of the color gradind data (currently only supporting 3dl)
  32432. * @param scene The scene the texture will be used in
  32433. */
  32434. function ColorGradingTexture(url, scene) {
  32435. var _this = _super.call(this, scene) || this;
  32436. if (!url) {
  32437. return _this;
  32438. }
  32439. _this._engine = scene.getEngine();
  32440. _this._textureMatrix = BABYLON.Matrix.Identity();
  32441. _this.name = url;
  32442. _this.url = url;
  32443. _this.hasAlpha = false;
  32444. _this.isCube = false;
  32445. _this.is3D = _this._engine.webGLVersion > 1;
  32446. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32447. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32448. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32449. _this.anisotropicFilteringLevel = 1;
  32450. _this._texture = _this._getFromCache(url, true);
  32451. if (!_this._texture) {
  32452. if (!scene.useDelayedTextureLoading) {
  32453. _this.loadTexture();
  32454. }
  32455. else {
  32456. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32457. }
  32458. }
  32459. return _this;
  32460. }
  32461. /**
  32462. * Returns the texture matrix used in most of the material.
  32463. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32464. */
  32465. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32466. return this._textureMatrix;
  32467. };
  32468. /**
  32469. * Occurs when the file being loaded is a .3dl LUT file.
  32470. */
  32471. ColorGradingTexture.prototype.load3dlTexture = function () {
  32472. var engine = this._engine;
  32473. var texture;
  32474. if (engine.webGLVersion === 1) {
  32475. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32476. }
  32477. else {
  32478. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32479. }
  32480. this._texture = texture;
  32481. var callback = function (text) {
  32482. var data = null;
  32483. var tempData = null;
  32484. var line;
  32485. var lines = text.split('\n');
  32486. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32487. var maxColor = 0;
  32488. for (var i = 0; i < lines.length; i++) {
  32489. line = lines[i];
  32490. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32491. continue;
  32492. if (line.indexOf('#') === 0)
  32493. continue;
  32494. var words = line.split(" ");
  32495. if (size === 0) {
  32496. // Number of space + one
  32497. size = words.length;
  32498. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32499. tempData = new Float32Array(size * size * size * 4);
  32500. continue;
  32501. }
  32502. if (size != 0) {
  32503. var r = Math.max(parseInt(words[0]), 0);
  32504. var g = Math.max(parseInt(words[1]), 0);
  32505. var b = Math.max(parseInt(words[2]), 0);
  32506. maxColor = Math.max(r, maxColor);
  32507. maxColor = Math.max(g, maxColor);
  32508. maxColor = Math.max(b, maxColor);
  32509. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32510. if (tempData) {
  32511. tempData[pixelStorageIndex + 0] = r;
  32512. tempData[pixelStorageIndex + 1] = g;
  32513. tempData[pixelStorageIndex + 2] = b;
  32514. }
  32515. pixelIndexSlice++;
  32516. if (pixelIndexSlice % size == 0) {
  32517. pixelIndexH++;
  32518. pixelIndexSlice = 0;
  32519. if (pixelIndexH % size == 0) {
  32520. pixelIndexW++;
  32521. pixelIndexH = 0;
  32522. }
  32523. }
  32524. }
  32525. }
  32526. if (tempData && data) {
  32527. for (var i = 0; i < tempData.length; i++) {
  32528. if (i > 0 && (i + 1) % 4 === 0) {
  32529. data[i] = 255;
  32530. }
  32531. else {
  32532. var value = tempData[i];
  32533. data[i] = (value / maxColor * 255);
  32534. }
  32535. }
  32536. }
  32537. if (texture.is3D) {
  32538. texture.updateSize(size, size, size);
  32539. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32540. }
  32541. else {
  32542. texture.updateSize(size * size, size);
  32543. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32544. }
  32545. };
  32546. BABYLON.Tools.LoadFile(this.url, callback);
  32547. return this._texture;
  32548. };
  32549. /**
  32550. * Starts the loading process of the texture.
  32551. */
  32552. ColorGradingTexture.prototype.loadTexture = function () {
  32553. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32554. this.load3dlTexture();
  32555. }
  32556. };
  32557. /**
  32558. * Clones the color gradind texture.
  32559. */
  32560. ColorGradingTexture.prototype.clone = function () {
  32561. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32562. // Base texture
  32563. newTexture.level = this.level;
  32564. return newTexture;
  32565. };
  32566. /**
  32567. * Called during delayed load for textures.
  32568. */
  32569. ColorGradingTexture.prototype.delayLoad = function () {
  32570. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32571. return;
  32572. }
  32573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32574. this._texture = this._getFromCache(this.url, true);
  32575. if (!this._texture) {
  32576. this.loadTexture();
  32577. }
  32578. };
  32579. /**
  32580. * Parses a color grading texture serialized by Babylon.
  32581. * @param parsedTexture The texture information being parsedTexture
  32582. * @param scene The scene to load the texture in
  32583. * @param rootUrl The root url of the data assets to load
  32584. * @return A color gradind texture
  32585. */
  32586. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32587. var texture = null;
  32588. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32589. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32590. texture.name = parsedTexture.name;
  32591. texture.level = parsedTexture.level;
  32592. }
  32593. return texture;
  32594. };
  32595. /**
  32596. * Serializes the LUT texture to json format.
  32597. */
  32598. ColorGradingTexture.prototype.serialize = function () {
  32599. if (!this.name) {
  32600. return null;
  32601. }
  32602. var serializationObject = {};
  32603. serializationObject.name = this.name;
  32604. serializationObject.level = this.level;
  32605. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32606. return serializationObject;
  32607. };
  32608. /**
  32609. * Empty line regex stored for GC.
  32610. */
  32611. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32612. return ColorGradingTexture;
  32613. }(BABYLON.BaseTexture));
  32614. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32615. })(BABYLON || (BABYLON = {}));
  32616. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32617. var BABYLON;
  32618. (function (BABYLON) {
  32619. /**
  32620. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32621. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32622. * 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;
  32623. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32624. */
  32625. var ColorCurves = /** @class */ (function () {
  32626. function ColorCurves() {
  32627. this._dirty = true;
  32628. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32629. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32630. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32631. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32632. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32633. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32634. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32635. this._globalHue = 30;
  32636. this._globalDensity = 0;
  32637. this._globalSaturation = 0;
  32638. this._globalExposure = 0;
  32639. this._highlightsHue = 30;
  32640. this._highlightsDensity = 0;
  32641. this._highlightsSaturation = 0;
  32642. this._highlightsExposure = 0;
  32643. this._midtonesHue = 30;
  32644. this._midtonesDensity = 0;
  32645. this._midtonesSaturation = 0;
  32646. this._midtonesExposure = 0;
  32647. this._shadowsHue = 30;
  32648. this._shadowsDensity = 0;
  32649. this._shadowsSaturation = 0;
  32650. this._shadowsExposure = 0;
  32651. }
  32652. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32653. /**
  32654. * Gets the global Hue value.
  32655. * 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).
  32656. */
  32657. get: function () {
  32658. return this._globalHue;
  32659. },
  32660. /**
  32661. * Sets the global Hue value.
  32662. * 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).
  32663. */
  32664. set: function (value) {
  32665. this._globalHue = value;
  32666. this._dirty = true;
  32667. },
  32668. enumerable: true,
  32669. configurable: true
  32670. });
  32671. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32672. /**
  32673. * Gets the global Density value.
  32674. * 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.
  32675. * Values less than zero provide a filter of opposite hue.
  32676. */
  32677. get: function () {
  32678. return this._globalDensity;
  32679. },
  32680. /**
  32681. * Sets the global Density value.
  32682. * 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.
  32683. * Values less than zero provide a filter of opposite hue.
  32684. */
  32685. set: function (value) {
  32686. this._globalDensity = value;
  32687. this._dirty = true;
  32688. },
  32689. enumerable: true,
  32690. configurable: true
  32691. });
  32692. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32693. /**
  32694. * Gets the global Saturation value.
  32695. * 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.
  32696. */
  32697. get: function () {
  32698. return this._globalSaturation;
  32699. },
  32700. /**
  32701. * Sets the global Saturation value.
  32702. * 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.
  32703. */
  32704. set: function (value) {
  32705. this._globalSaturation = value;
  32706. this._dirty = true;
  32707. },
  32708. enumerable: true,
  32709. configurable: true
  32710. });
  32711. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32712. /**
  32713. * Gets the highlights Hue value.
  32714. * 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).
  32715. */
  32716. get: function () {
  32717. return this._highlightsHue;
  32718. },
  32719. /**
  32720. * Sets the highlights Hue value.
  32721. * 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).
  32722. */
  32723. set: function (value) {
  32724. this._highlightsHue = value;
  32725. this._dirty = true;
  32726. },
  32727. enumerable: true,
  32728. configurable: true
  32729. });
  32730. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32731. /**
  32732. * Gets the highlights Density value.
  32733. * 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.
  32734. * Values less than zero provide a filter of opposite hue.
  32735. */
  32736. get: function () {
  32737. return this._highlightsDensity;
  32738. },
  32739. /**
  32740. * Sets the highlights Density value.
  32741. * 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.
  32742. * Values less than zero provide a filter of opposite hue.
  32743. */
  32744. set: function (value) {
  32745. this._highlightsDensity = value;
  32746. this._dirty = true;
  32747. },
  32748. enumerable: true,
  32749. configurable: true
  32750. });
  32751. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32752. /**
  32753. * Gets the highlights Saturation value.
  32754. * 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.
  32755. */
  32756. get: function () {
  32757. return this._highlightsSaturation;
  32758. },
  32759. /**
  32760. * Sets the highlights Saturation value.
  32761. * 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.
  32762. */
  32763. set: function (value) {
  32764. this._highlightsSaturation = value;
  32765. this._dirty = true;
  32766. },
  32767. enumerable: true,
  32768. configurable: true
  32769. });
  32770. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32771. /**
  32772. * Gets the highlights Exposure value.
  32773. * 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.
  32774. */
  32775. get: function () {
  32776. return this._highlightsExposure;
  32777. },
  32778. /**
  32779. * Sets the highlights Exposure value.
  32780. * 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.
  32781. */
  32782. set: function (value) {
  32783. this._highlightsExposure = value;
  32784. this._dirty = true;
  32785. },
  32786. enumerable: true,
  32787. configurable: true
  32788. });
  32789. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32790. /**
  32791. * Gets the midtones Hue value.
  32792. * 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).
  32793. */
  32794. get: function () {
  32795. return this._midtonesHue;
  32796. },
  32797. /**
  32798. * Sets the midtones Hue value.
  32799. * 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).
  32800. */
  32801. set: function (value) {
  32802. this._midtonesHue = value;
  32803. this._dirty = true;
  32804. },
  32805. enumerable: true,
  32806. configurable: true
  32807. });
  32808. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32809. /**
  32810. * Gets the midtones Density value.
  32811. * 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.
  32812. * Values less than zero provide a filter of opposite hue.
  32813. */
  32814. get: function () {
  32815. return this._midtonesDensity;
  32816. },
  32817. /**
  32818. * Sets the midtones Density value.
  32819. * 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.
  32820. * Values less than zero provide a filter of opposite hue.
  32821. */
  32822. set: function (value) {
  32823. this._midtonesDensity = value;
  32824. this._dirty = true;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32830. /**
  32831. * Gets the midtones Saturation value.
  32832. * 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.
  32833. */
  32834. get: function () {
  32835. return this._midtonesSaturation;
  32836. },
  32837. /**
  32838. * Sets the midtones Saturation value.
  32839. * 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.
  32840. */
  32841. set: function (value) {
  32842. this._midtonesSaturation = value;
  32843. this._dirty = true;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32849. /**
  32850. * Gets the midtones Exposure value.
  32851. * 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.
  32852. */
  32853. get: function () {
  32854. return this._midtonesExposure;
  32855. },
  32856. /**
  32857. * Sets the midtones Exposure value.
  32858. * 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.
  32859. */
  32860. set: function (value) {
  32861. this._midtonesExposure = value;
  32862. this._dirty = true;
  32863. },
  32864. enumerable: true,
  32865. configurable: true
  32866. });
  32867. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32868. /**
  32869. * Gets the shadows Hue value.
  32870. * 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).
  32871. */
  32872. get: function () {
  32873. return this._shadowsHue;
  32874. },
  32875. /**
  32876. * Sets the shadows Hue value.
  32877. * 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).
  32878. */
  32879. set: function (value) {
  32880. this._shadowsHue = value;
  32881. this._dirty = true;
  32882. },
  32883. enumerable: true,
  32884. configurable: true
  32885. });
  32886. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32887. /**
  32888. * Gets the shadows Density value.
  32889. * 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.
  32890. * Values less than zero provide a filter of opposite hue.
  32891. */
  32892. get: function () {
  32893. return this._shadowsDensity;
  32894. },
  32895. /**
  32896. * Sets the shadows Density value.
  32897. * 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.
  32898. * Values less than zero provide a filter of opposite hue.
  32899. */
  32900. set: function (value) {
  32901. this._shadowsDensity = value;
  32902. this._dirty = true;
  32903. },
  32904. enumerable: true,
  32905. configurable: true
  32906. });
  32907. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32908. /**
  32909. * Gets the shadows Saturation value.
  32910. * 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.
  32911. */
  32912. get: function () {
  32913. return this._shadowsSaturation;
  32914. },
  32915. /**
  32916. * Sets the shadows Saturation value.
  32917. * 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.
  32918. */
  32919. set: function (value) {
  32920. this._shadowsSaturation = value;
  32921. this._dirty = true;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32927. /**
  32928. * Gets the shadows Exposure value.
  32929. * 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.
  32930. */
  32931. get: function () {
  32932. return this._shadowsExposure;
  32933. },
  32934. /**
  32935. * Sets the shadows Exposure value.
  32936. * 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.
  32937. */
  32938. set: function (value) {
  32939. this._shadowsExposure = value;
  32940. this._dirty = true;
  32941. },
  32942. enumerable: true,
  32943. configurable: true
  32944. });
  32945. ColorCurves.prototype.getClassName = function () {
  32946. return "ColorCurves";
  32947. };
  32948. /**
  32949. * Binds the color curves to the shader.
  32950. * @param colorCurves The color curve to bind
  32951. * @param effect The effect to bind to
  32952. */
  32953. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32954. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32955. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32956. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32957. if (colorCurves._dirty) {
  32958. colorCurves._dirty = false;
  32959. // Fill in global info.
  32960. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32961. // Compute highlights info.
  32962. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32963. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32964. // Compute midtones info.
  32965. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32966. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32967. // Compute shadows info.
  32968. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32969. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32970. // Compute deltas (neutral is midtones).
  32971. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32972. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32973. }
  32974. if (effect) {
  32975. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32976. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32977. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32978. }
  32979. };
  32980. /**
  32981. * Prepare the list of uniforms associated with the ColorCurves effects.
  32982. * @param uniformsList The list of uniforms used in the effect
  32983. */
  32984. ColorCurves.PrepareUniforms = function (uniformsList) {
  32985. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32986. };
  32987. /**
  32988. * Returns color grading data based on a hue, density, saturation and exposure value.
  32989. * @param filterHue The hue of the color filter.
  32990. * @param filterDensity The density of the color filter.
  32991. * @param saturation The saturation.
  32992. * @param exposure The exposure.
  32993. * @param result The result data container.
  32994. */
  32995. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32996. if (hue == null) {
  32997. return;
  32998. }
  32999. hue = ColorCurves.clamp(hue, 0, 360);
  33000. density = ColorCurves.clamp(density, -100, 100);
  33001. saturation = ColorCurves.clamp(saturation, -100, 100);
  33002. exposure = ColorCurves.clamp(exposure, -100, 100);
  33003. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33004. // so that the maximum filter density is only 50% control. This provides fine control
  33005. // for small values and reasonable range.
  33006. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33007. density *= 0.5;
  33008. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33009. if (density < 0) {
  33010. density *= -1;
  33011. hue = (hue + 180) % 360;
  33012. }
  33013. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33014. result.scaleToRef(2, result);
  33015. result.a = 1 + 0.01 * saturation;
  33016. };
  33017. /**
  33018. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33019. * @param value The input slider value in range [-100,100].
  33020. * @returns Adjusted value.
  33021. */
  33022. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33023. value /= 100;
  33024. var x = Math.abs(value);
  33025. x = Math.pow(x, 2);
  33026. if (value < 0) {
  33027. x *= -1;
  33028. }
  33029. x *= 100;
  33030. return x;
  33031. };
  33032. /**
  33033. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33034. * @param hue The hue (H) input.
  33035. * @param saturation The saturation (S) input.
  33036. * @param brightness The brightness (B) input.
  33037. * @result An RGBA color represented as Vector4.
  33038. */
  33039. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33040. var h = ColorCurves.clamp(hue, 0, 360);
  33041. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33042. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33043. if (s === 0) {
  33044. result.r = v;
  33045. result.g = v;
  33046. result.b = v;
  33047. }
  33048. else {
  33049. // sector 0 to 5
  33050. h /= 60;
  33051. var i = Math.floor(h);
  33052. // fractional part of h
  33053. var f = h - i;
  33054. var p = v * (1 - s);
  33055. var q = v * (1 - s * f);
  33056. var t = v * (1 - s * (1 - f));
  33057. switch (i) {
  33058. case 0:
  33059. result.r = v;
  33060. result.g = t;
  33061. result.b = p;
  33062. break;
  33063. case 1:
  33064. result.r = q;
  33065. result.g = v;
  33066. result.b = p;
  33067. break;
  33068. case 2:
  33069. result.r = p;
  33070. result.g = v;
  33071. result.b = t;
  33072. break;
  33073. case 3:
  33074. result.r = p;
  33075. result.g = q;
  33076. result.b = v;
  33077. break;
  33078. case 4:
  33079. result.r = t;
  33080. result.g = p;
  33081. result.b = v;
  33082. break;
  33083. default:// case 5:
  33084. result.r = v;
  33085. result.g = p;
  33086. result.b = q;
  33087. break;
  33088. }
  33089. }
  33090. result.a = 1;
  33091. };
  33092. /**
  33093. * Returns a value clamped between min and max
  33094. * @param value The value to clamp
  33095. * @param min The minimum of value
  33096. * @param max The maximum of value
  33097. * @returns The clamped value.
  33098. */
  33099. ColorCurves.clamp = function (value, min, max) {
  33100. return Math.min(Math.max(value, min), max);
  33101. };
  33102. /**
  33103. * Clones the current color curve instance.
  33104. * @return The cloned curves
  33105. */
  33106. ColorCurves.prototype.clone = function () {
  33107. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33108. };
  33109. /**
  33110. * Serializes the current color curve instance to a json representation.
  33111. * @return a JSON representation
  33112. */
  33113. ColorCurves.prototype.serialize = function () {
  33114. return BABYLON.SerializationHelper.Serialize(this);
  33115. };
  33116. /**
  33117. * Parses the color curve from a json representation.
  33118. * @param source the JSON source to parse
  33119. * @return The parsed curves
  33120. */
  33121. ColorCurves.Parse = function (source) {
  33122. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33123. };
  33124. __decorate([
  33125. BABYLON.serialize()
  33126. ], ColorCurves.prototype, "_globalHue", void 0);
  33127. __decorate([
  33128. BABYLON.serialize()
  33129. ], ColorCurves.prototype, "_globalDensity", void 0);
  33130. __decorate([
  33131. BABYLON.serialize()
  33132. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33133. __decorate([
  33134. BABYLON.serialize()
  33135. ], ColorCurves.prototype, "_globalExposure", void 0);
  33136. __decorate([
  33137. BABYLON.serialize()
  33138. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33139. __decorate([
  33140. BABYLON.serialize()
  33141. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33142. __decorate([
  33143. BABYLON.serialize()
  33144. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33145. __decorate([
  33146. BABYLON.serialize()
  33147. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33148. __decorate([
  33149. BABYLON.serialize()
  33150. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33151. __decorate([
  33152. BABYLON.serialize()
  33153. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33154. __decorate([
  33155. BABYLON.serialize()
  33156. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33157. __decorate([
  33158. BABYLON.serialize()
  33159. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33160. return ColorCurves;
  33161. }());
  33162. BABYLON.ColorCurves = ColorCurves;
  33163. })(BABYLON || (BABYLON = {}));
  33164. //# sourceMappingURL=babylon.colorCurves.js.map
  33165. var BABYLON;
  33166. (function (BABYLON) {
  33167. var StandardMaterialDefines = /** @class */ (function (_super) {
  33168. __extends(StandardMaterialDefines, _super);
  33169. function StandardMaterialDefines() {
  33170. var _this = _super.call(this) || this;
  33171. _this.MAINUV1 = false;
  33172. _this.MAINUV2 = false;
  33173. _this.DIFFUSE = false;
  33174. _this.DIFFUSEDIRECTUV = 0;
  33175. _this.AMBIENT = false;
  33176. _this.AMBIENTDIRECTUV = 0;
  33177. _this.OPACITY = false;
  33178. _this.OPACITYDIRECTUV = 0;
  33179. _this.OPACITYRGB = false;
  33180. _this.REFLECTION = false;
  33181. _this.EMISSIVE = false;
  33182. _this.EMISSIVEDIRECTUV = 0;
  33183. _this.SPECULAR = false;
  33184. _this.SPECULARDIRECTUV = 0;
  33185. _this.BUMP = false;
  33186. _this.BUMPDIRECTUV = 0;
  33187. _this.PARALLAX = false;
  33188. _this.PARALLAXOCCLUSION = false;
  33189. _this.SPECULAROVERALPHA = false;
  33190. _this.CLIPPLANE = false;
  33191. _this.ALPHATEST = false;
  33192. _this.DEPTHPREPASS = false;
  33193. _this.ALPHAFROMDIFFUSE = false;
  33194. _this.POINTSIZE = false;
  33195. _this.FOG = false;
  33196. _this.SPECULARTERM = false;
  33197. _this.DIFFUSEFRESNEL = false;
  33198. _this.OPACITYFRESNEL = false;
  33199. _this.REFLECTIONFRESNEL = false;
  33200. _this.REFRACTIONFRESNEL = false;
  33201. _this.EMISSIVEFRESNEL = false;
  33202. _this.FRESNEL = false;
  33203. _this.NORMAL = false;
  33204. _this.UV1 = false;
  33205. _this.UV2 = false;
  33206. _this.VERTEXCOLOR = false;
  33207. _this.VERTEXALPHA = false;
  33208. _this.NUM_BONE_INFLUENCERS = 0;
  33209. _this.BonesPerMesh = 0;
  33210. _this.INSTANCES = false;
  33211. _this.GLOSSINESS = false;
  33212. _this.ROUGHNESS = false;
  33213. _this.EMISSIVEASILLUMINATION = false;
  33214. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33215. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33216. _this.LIGHTMAP = false;
  33217. _this.LIGHTMAPDIRECTUV = 0;
  33218. _this.USELIGHTMAPASSHADOWMAP = false;
  33219. _this.REFLECTIONMAP_3D = false;
  33220. _this.REFLECTIONMAP_SPHERICAL = false;
  33221. _this.REFLECTIONMAP_PLANAR = false;
  33222. _this.REFLECTIONMAP_CUBIC = false;
  33223. _this.REFLECTIONMAP_PROJECTION = false;
  33224. _this.REFLECTIONMAP_SKYBOX = false;
  33225. _this.REFLECTIONMAP_EXPLICIT = false;
  33226. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33227. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33228. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33229. _this.INVERTCUBICMAP = false;
  33230. _this.LOGARITHMICDEPTH = false;
  33231. _this.REFRACTION = false;
  33232. _this.REFRACTIONMAP_3D = false;
  33233. _this.REFLECTIONOVERALPHA = false;
  33234. _this.TWOSIDEDLIGHTING = false;
  33235. _this.SHADOWFLOAT = false;
  33236. _this.MORPHTARGETS = false;
  33237. _this.MORPHTARGETS_NORMAL = false;
  33238. _this.MORPHTARGETS_TANGENT = false;
  33239. _this.NUM_MORPH_INFLUENCERS = 0;
  33240. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33241. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33242. _this.IMAGEPROCESSING = false;
  33243. _this.VIGNETTE = false;
  33244. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33245. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33246. _this.TONEMAPPING = false;
  33247. _this.CONTRAST = false;
  33248. _this.COLORCURVES = false;
  33249. _this.COLORGRADING = false;
  33250. _this.COLORGRADING3D = false;
  33251. _this.SAMPLER3DGREENDEPTH = false;
  33252. _this.SAMPLER3DBGRMAP = false;
  33253. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33254. _this.EXPOSURE = false;
  33255. _this.rebuild();
  33256. return _this;
  33257. }
  33258. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33259. var modes = [
  33260. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33261. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33262. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33263. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33264. ];
  33265. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33266. var mode = modes_1[_i];
  33267. this[mode] = (mode === modeToEnable);
  33268. }
  33269. };
  33270. return StandardMaterialDefines;
  33271. }(BABYLON.MaterialDefines));
  33272. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33273. var StandardMaterial = /** @class */ (function (_super) {
  33274. __extends(StandardMaterial, _super);
  33275. function StandardMaterial(name, scene) {
  33276. var _this = _super.call(this, name, scene) || this;
  33277. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33278. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33279. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33280. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33281. _this.specularPower = 64;
  33282. _this._useAlphaFromDiffuseTexture = false;
  33283. _this._useEmissiveAsIllumination = false;
  33284. _this._linkEmissiveWithDiffuse = false;
  33285. _this._useSpecularOverAlpha = false;
  33286. _this._useReflectionOverAlpha = false;
  33287. _this._disableLighting = false;
  33288. _this._useParallax = false;
  33289. _this._useParallaxOcclusion = false;
  33290. _this.parallaxScaleBias = 0.05;
  33291. _this._roughness = 0;
  33292. _this.indexOfRefraction = 0.98;
  33293. _this.invertRefractionY = true;
  33294. _this._useLightmapAsShadowmap = false;
  33295. _this._useReflectionFresnelFromSpecular = false;
  33296. _this._useGlossinessFromSpecularMapAlpha = false;
  33297. _this._maxSimultaneousLights = 4;
  33298. /**
  33299. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33300. */
  33301. _this._invertNormalMapX = false;
  33302. /**
  33303. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33304. */
  33305. _this._invertNormalMapY = false;
  33306. /**
  33307. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33308. */
  33309. _this._twoSidedLighting = false;
  33310. _this._renderTargets = new BABYLON.SmartArray(16);
  33311. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33312. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33313. // Setup the default processing configuration to the scene.
  33314. _this._attachImageProcessingConfiguration(null);
  33315. _this.getRenderTargetTextures = function () {
  33316. _this._renderTargets.reset();
  33317. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33318. _this._renderTargets.push(_this._reflectionTexture);
  33319. }
  33320. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33321. _this._renderTargets.push(_this._refractionTexture);
  33322. }
  33323. return _this._renderTargets;
  33324. };
  33325. return _this;
  33326. }
  33327. ;
  33328. ;
  33329. ;
  33330. ;
  33331. ;
  33332. ;
  33333. ;
  33334. ;
  33335. ;
  33336. ;
  33337. ;
  33338. ;
  33339. ;
  33340. ;
  33341. ;
  33342. ;
  33343. ;
  33344. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33345. /**
  33346. * Gets the image processing configuration used either in this material.
  33347. */
  33348. get: function () {
  33349. return this._imageProcessingConfiguration;
  33350. },
  33351. /**
  33352. * Sets the Default image processing configuration used either in the this material.
  33353. *
  33354. * If sets to null, the scene one is in use.
  33355. */
  33356. set: function (value) {
  33357. this._attachImageProcessingConfiguration(value);
  33358. // Ensure the effect will be rebuilt.
  33359. this._markAllSubMeshesAsTexturesDirty();
  33360. },
  33361. enumerable: true,
  33362. configurable: true
  33363. });
  33364. /**
  33365. * Attaches a new image processing configuration to the Standard Material.
  33366. * @param configuration
  33367. */
  33368. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33369. var _this = this;
  33370. if (configuration === this._imageProcessingConfiguration) {
  33371. return;
  33372. }
  33373. // Detaches observer.
  33374. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33375. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33376. }
  33377. // Pick the scene configuration if needed.
  33378. if (!configuration) {
  33379. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33380. }
  33381. else {
  33382. this._imageProcessingConfiguration = configuration;
  33383. }
  33384. // Attaches observer.
  33385. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33386. _this._markAllSubMeshesAsImageProcessingDirty();
  33387. });
  33388. };
  33389. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33390. /**
  33391. * Gets wether the color curves effect is enabled.
  33392. */
  33393. get: function () {
  33394. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33395. },
  33396. /**
  33397. * Sets wether the color curves effect is enabled.
  33398. */
  33399. set: function (value) {
  33400. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33406. /**
  33407. * Gets wether the color grading effect is enabled.
  33408. */
  33409. get: function () {
  33410. return this.imageProcessingConfiguration.colorGradingEnabled;
  33411. },
  33412. /**
  33413. * Gets wether the color grading effect is enabled.
  33414. */
  33415. set: function (value) {
  33416. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33417. },
  33418. enumerable: true,
  33419. configurable: true
  33420. });
  33421. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33422. /**
  33423. * Gets wether tonemapping is enabled or not.
  33424. */
  33425. get: function () {
  33426. return this._imageProcessingConfiguration.toneMappingEnabled;
  33427. },
  33428. /**
  33429. * Sets wether tonemapping is enabled or not
  33430. */
  33431. set: function (value) {
  33432. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33433. },
  33434. enumerable: true,
  33435. configurable: true
  33436. });
  33437. ;
  33438. ;
  33439. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33440. /**
  33441. * The camera exposure used on this material.
  33442. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33443. * This corresponds to a photographic exposure.
  33444. */
  33445. get: function () {
  33446. return this._imageProcessingConfiguration.exposure;
  33447. },
  33448. /**
  33449. * The camera exposure used on this material.
  33450. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33451. * This corresponds to a photographic exposure.
  33452. */
  33453. set: function (value) {
  33454. this._imageProcessingConfiguration.exposure = value;
  33455. },
  33456. enumerable: true,
  33457. configurable: true
  33458. });
  33459. ;
  33460. ;
  33461. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33462. /**
  33463. * Gets The camera contrast used on this material.
  33464. */
  33465. get: function () {
  33466. return this._imageProcessingConfiguration.contrast;
  33467. },
  33468. /**
  33469. * Sets The camera contrast used on this material.
  33470. */
  33471. set: function (value) {
  33472. this._imageProcessingConfiguration.contrast = value;
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33478. /**
  33479. * Gets the Color Grading 2D Lookup Texture.
  33480. */
  33481. get: function () {
  33482. return this._imageProcessingConfiguration.colorGradingTexture;
  33483. },
  33484. /**
  33485. * Sets the Color Grading 2D Lookup Texture.
  33486. */
  33487. set: function (value) {
  33488. this._imageProcessingConfiguration.colorGradingTexture = value;
  33489. },
  33490. enumerable: true,
  33491. configurable: true
  33492. });
  33493. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33494. /**
  33495. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33496. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33497. * 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;
  33498. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33499. */
  33500. get: function () {
  33501. return this._imageProcessingConfiguration.colorCurves;
  33502. },
  33503. /**
  33504. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33505. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33506. * 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;
  33507. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33508. */
  33509. set: function (value) {
  33510. this._imageProcessingConfiguration.colorCurves = value;
  33511. },
  33512. enumerable: true,
  33513. configurable: true
  33514. });
  33515. StandardMaterial.prototype.getClassName = function () {
  33516. return "StandardMaterial";
  33517. };
  33518. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33519. get: function () {
  33520. return this._useLogarithmicDepth;
  33521. },
  33522. set: function (value) {
  33523. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33524. this._markAllSubMeshesAsMiscDirty();
  33525. },
  33526. enumerable: true,
  33527. configurable: true
  33528. });
  33529. StandardMaterial.prototype.needAlphaBlending = function () {
  33530. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33531. };
  33532. StandardMaterial.prototype.needAlphaTesting = function () {
  33533. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33534. };
  33535. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33536. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33537. };
  33538. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33539. return this._diffuseTexture;
  33540. };
  33541. /**
  33542. * Child classes can use it to update shaders
  33543. */
  33544. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33545. if (useInstances === void 0) { useInstances = false; }
  33546. if (subMesh.effect && this.isFrozen) {
  33547. if (this._wasPreviouslyReady && subMesh.effect) {
  33548. return true;
  33549. }
  33550. }
  33551. if (!subMesh._materialDefines) {
  33552. subMesh._materialDefines = new StandardMaterialDefines();
  33553. }
  33554. var scene = this.getScene();
  33555. var defines = subMesh._materialDefines;
  33556. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33557. if (defines._renderId === scene.getRenderId()) {
  33558. return true;
  33559. }
  33560. }
  33561. var engine = scene.getEngine();
  33562. // Lights
  33563. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33564. // Textures
  33565. if (defines._areTexturesDirty) {
  33566. defines._needUVs = false;
  33567. defines.MAINUV1 = false;
  33568. defines.MAINUV2 = false;
  33569. if (scene.texturesEnabled) {
  33570. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33571. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33572. return false;
  33573. }
  33574. else {
  33575. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33576. }
  33577. }
  33578. else {
  33579. defines.DIFFUSE = false;
  33580. }
  33581. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33582. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33583. return false;
  33584. }
  33585. else {
  33586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33587. }
  33588. }
  33589. else {
  33590. defines.AMBIENT = false;
  33591. }
  33592. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33593. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33594. return false;
  33595. }
  33596. else {
  33597. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33598. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33599. }
  33600. }
  33601. else {
  33602. defines.OPACITY = false;
  33603. }
  33604. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33605. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33606. return false;
  33607. }
  33608. else {
  33609. defines._needNormals = true;
  33610. defines.REFLECTION = true;
  33611. defines.ROUGHNESS = (this._roughness > 0);
  33612. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33613. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33614. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33615. switch (this._reflectionTexture.coordinatesMode) {
  33616. case BABYLON.Texture.CUBIC_MODE:
  33617. case BABYLON.Texture.INVCUBIC_MODE:
  33618. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33619. break;
  33620. case BABYLON.Texture.EXPLICIT_MODE:
  33621. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33622. break;
  33623. case BABYLON.Texture.PLANAR_MODE:
  33624. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33625. break;
  33626. case BABYLON.Texture.PROJECTION_MODE:
  33627. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33628. break;
  33629. case BABYLON.Texture.SKYBOX_MODE:
  33630. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33631. break;
  33632. case BABYLON.Texture.SPHERICAL_MODE:
  33633. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33634. break;
  33635. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33636. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33637. break;
  33638. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33639. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33640. break;
  33641. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33642. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33643. break;
  33644. }
  33645. }
  33646. }
  33647. else {
  33648. defines.REFLECTION = false;
  33649. }
  33650. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33651. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33652. return false;
  33653. }
  33654. else {
  33655. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33656. }
  33657. }
  33658. else {
  33659. defines.EMISSIVE = false;
  33660. }
  33661. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33662. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33663. return false;
  33664. }
  33665. else {
  33666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33667. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33668. }
  33669. }
  33670. else {
  33671. defines.LIGHTMAP = false;
  33672. }
  33673. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33674. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33675. return false;
  33676. }
  33677. else {
  33678. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33679. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33680. }
  33681. }
  33682. else {
  33683. defines.SPECULAR = false;
  33684. }
  33685. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33686. // Bump texure can not be not blocking.
  33687. if (!this._bumpTexture.isReady()) {
  33688. return false;
  33689. }
  33690. else {
  33691. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33692. defines.PARALLAX = this._useParallax;
  33693. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33694. }
  33695. }
  33696. else {
  33697. defines.BUMP = false;
  33698. }
  33699. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33700. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33701. return false;
  33702. }
  33703. else {
  33704. defines._needUVs = true;
  33705. defines.REFRACTION = true;
  33706. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33707. }
  33708. }
  33709. else {
  33710. defines.REFRACTION = false;
  33711. }
  33712. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33713. }
  33714. else {
  33715. defines.DIFFUSE = false;
  33716. defines.AMBIENT = false;
  33717. defines.OPACITY = false;
  33718. defines.REFLECTION = false;
  33719. defines.EMISSIVE = false;
  33720. defines.LIGHTMAP = false;
  33721. defines.BUMP = false;
  33722. defines.REFRACTION = false;
  33723. }
  33724. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33725. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33726. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33727. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33728. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33729. }
  33730. if (defines._areImageProcessingDirty) {
  33731. if (!this._imageProcessingConfiguration.isReady()) {
  33732. return false;
  33733. }
  33734. this._imageProcessingConfiguration.prepareDefines(defines);
  33735. }
  33736. if (defines._areFresnelDirty) {
  33737. if (StandardMaterial.FresnelEnabled) {
  33738. // Fresnel
  33739. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33740. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33741. this._reflectionFresnelParameters) {
  33742. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33743. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33744. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33745. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33746. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33747. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33748. defines._needNormals = true;
  33749. defines.FRESNEL = true;
  33750. }
  33751. }
  33752. else {
  33753. defines.FRESNEL = false;
  33754. }
  33755. }
  33756. // Misc.
  33757. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33758. // Attribs
  33759. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33760. // Values that need to be evaluated on every frame
  33761. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33762. // Get correct effect
  33763. if (defines.isDirty) {
  33764. defines.markAsProcessed();
  33765. scene.resetCachedMaterial();
  33766. // Fallbacks
  33767. var fallbacks = new BABYLON.EffectFallbacks();
  33768. if (defines.REFLECTION) {
  33769. fallbacks.addFallback(0, "REFLECTION");
  33770. }
  33771. if (defines.SPECULAR) {
  33772. fallbacks.addFallback(0, "SPECULAR");
  33773. }
  33774. if (defines.BUMP) {
  33775. fallbacks.addFallback(0, "BUMP");
  33776. }
  33777. if (defines.PARALLAX) {
  33778. fallbacks.addFallback(1, "PARALLAX");
  33779. }
  33780. if (defines.PARALLAXOCCLUSION) {
  33781. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33782. }
  33783. if (defines.SPECULAROVERALPHA) {
  33784. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33785. }
  33786. if (defines.FOG) {
  33787. fallbacks.addFallback(1, "FOG");
  33788. }
  33789. if (defines.POINTSIZE) {
  33790. fallbacks.addFallback(0, "POINTSIZE");
  33791. }
  33792. if (defines.LOGARITHMICDEPTH) {
  33793. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33794. }
  33795. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33796. if (defines.SPECULARTERM) {
  33797. fallbacks.addFallback(0, "SPECULARTERM");
  33798. }
  33799. if (defines.DIFFUSEFRESNEL) {
  33800. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33801. }
  33802. if (defines.OPACITYFRESNEL) {
  33803. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33804. }
  33805. if (defines.REFLECTIONFRESNEL) {
  33806. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33807. }
  33808. if (defines.EMISSIVEFRESNEL) {
  33809. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33810. }
  33811. if (defines.FRESNEL) {
  33812. fallbacks.addFallback(4, "FRESNEL");
  33813. }
  33814. //Attributes
  33815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33816. if (defines.NORMAL) {
  33817. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33818. }
  33819. if (defines.UV1) {
  33820. attribs.push(BABYLON.VertexBuffer.UVKind);
  33821. }
  33822. if (defines.UV2) {
  33823. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33824. }
  33825. if (defines.VERTEXCOLOR) {
  33826. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33827. }
  33828. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33829. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33830. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33831. var shaderName = "default";
  33832. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33833. "vFogInfos", "vFogColor", "pointSize",
  33834. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33835. "mBones",
  33836. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33837. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33838. "logarithmicDepthConstant", "vTangentSpaceParams"
  33839. ];
  33840. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33841. var uniformBuffers = ["Material", "Scene"];
  33842. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33843. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33844. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33845. uniformsNames: uniforms,
  33846. uniformBuffersNames: uniformBuffers,
  33847. samplers: samplers,
  33848. defines: defines,
  33849. maxSimultaneousLights: this._maxSimultaneousLights
  33850. });
  33851. if (this.customShaderNameResolve) {
  33852. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33853. }
  33854. var join = defines.toString();
  33855. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33856. attributes: attribs,
  33857. uniformsNames: uniforms,
  33858. uniformBuffersNames: uniformBuffers,
  33859. samplers: samplers,
  33860. defines: join,
  33861. fallbacks: fallbacks,
  33862. onCompiled: this.onCompiled,
  33863. onError: this.onError,
  33864. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33865. }, engine), defines);
  33866. this.buildUniformLayout();
  33867. }
  33868. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33869. return false;
  33870. }
  33871. defines._renderId = scene.getRenderId();
  33872. this._wasPreviouslyReady = true;
  33873. return true;
  33874. };
  33875. StandardMaterial.prototype.buildUniformLayout = function () {
  33876. // Order is important !
  33877. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33878. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33879. this._uniformBuffer.addUniform("opacityParts", 4);
  33880. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33881. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33882. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33883. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33884. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33885. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33886. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33887. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33888. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33889. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33890. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33891. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33892. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33893. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33894. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33895. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33896. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33897. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33898. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33899. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33900. this._uniformBuffer.addUniform("specularMatrix", 16);
  33901. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33902. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33903. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33904. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33905. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33906. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33907. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33908. this._uniformBuffer.addUniform("pointSize", 1);
  33909. this._uniformBuffer.create();
  33910. };
  33911. StandardMaterial.prototype.unbind = function () {
  33912. if (this._activeEffect) {
  33913. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33914. this._activeEffect.setTexture("reflection2DSampler", null);
  33915. }
  33916. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33917. this._activeEffect.setTexture("refraction2DSampler", null);
  33918. }
  33919. }
  33920. _super.prototype.unbind.call(this);
  33921. };
  33922. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33923. var scene = this.getScene();
  33924. var defines = subMesh._materialDefines;
  33925. if (!defines) {
  33926. return;
  33927. }
  33928. var effect = subMesh.effect;
  33929. if (!effect) {
  33930. return;
  33931. }
  33932. this._activeEffect = effect;
  33933. // Matrices
  33934. this.bindOnlyWorldMatrix(world);
  33935. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33936. // Bones
  33937. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33938. if (mustRebind) {
  33939. this._uniformBuffer.bindToEffect(effect, "Material");
  33940. this.bindViewProjection(effect);
  33941. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33942. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33943. // Fresnel
  33944. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33945. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33946. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33947. }
  33948. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33949. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33950. }
  33951. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33952. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33953. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33954. }
  33955. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33956. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33957. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33958. }
  33959. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33960. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33961. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33962. }
  33963. }
  33964. // Textures
  33965. if (scene.texturesEnabled) {
  33966. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33967. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33968. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33969. }
  33970. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33971. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33972. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33973. }
  33974. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33975. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33976. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33977. }
  33978. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33979. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33980. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33981. }
  33982. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33983. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33984. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33985. }
  33986. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33987. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33988. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33989. }
  33990. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33991. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33992. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33993. }
  33994. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33995. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33996. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33997. if (scene._mirroredCameraPosition) {
  33998. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33999. }
  34000. else {
  34001. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34002. }
  34003. }
  34004. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34005. var depth = 1.0;
  34006. if (!this._refractionTexture.isCube) {
  34007. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34008. if (this._refractionTexture.depth) {
  34009. depth = this._refractionTexture.depth;
  34010. }
  34011. }
  34012. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34013. }
  34014. }
  34015. // Point size
  34016. if (this.pointsCloud) {
  34017. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34018. }
  34019. if (defines.SPECULARTERM) {
  34020. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34021. }
  34022. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34023. // Diffuse
  34024. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34025. }
  34026. // Textures
  34027. if (scene.texturesEnabled) {
  34028. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34029. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34030. }
  34031. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34032. effect.setTexture("ambientSampler", this._ambientTexture);
  34033. }
  34034. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34035. effect.setTexture("opacitySampler", this._opacityTexture);
  34036. }
  34037. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34038. if (this._reflectionTexture.isCube) {
  34039. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34040. }
  34041. else {
  34042. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34043. }
  34044. }
  34045. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34046. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34047. }
  34048. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34049. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34050. }
  34051. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34052. effect.setTexture("specularSampler", this._specularTexture);
  34053. }
  34054. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34055. effect.setTexture("bumpSampler", this._bumpTexture);
  34056. }
  34057. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34058. var depth = 1.0;
  34059. if (this._refractionTexture.isCube) {
  34060. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34061. }
  34062. else {
  34063. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34064. }
  34065. }
  34066. }
  34067. // Clip plane
  34068. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34069. // Colors
  34070. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34071. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34072. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34073. }
  34074. if (mustRebind || !this.isFrozen) {
  34075. // Lights
  34076. if (scene.lightsEnabled && !this._disableLighting) {
  34077. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34078. }
  34079. // View
  34080. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34081. this.bindView(effect);
  34082. }
  34083. // Fog
  34084. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34085. // Morph targets
  34086. if (defines.NUM_MORPH_INFLUENCERS) {
  34087. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34088. }
  34089. // Log. depth
  34090. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34091. // image processing
  34092. this._imageProcessingConfiguration.bind(this._activeEffect);
  34093. }
  34094. this._uniformBuffer.update();
  34095. this._afterBind(mesh, this._activeEffect);
  34096. };
  34097. StandardMaterial.prototype.getAnimatables = function () {
  34098. var results = [];
  34099. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34100. results.push(this._diffuseTexture);
  34101. }
  34102. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34103. results.push(this._ambientTexture);
  34104. }
  34105. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34106. results.push(this._opacityTexture);
  34107. }
  34108. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34109. results.push(this._reflectionTexture);
  34110. }
  34111. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34112. results.push(this._emissiveTexture);
  34113. }
  34114. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34115. results.push(this._specularTexture);
  34116. }
  34117. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34118. results.push(this._bumpTexture);
  34119. }
  34120. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34121. results.push(this._lightmapTexture);
  34122. }
  34123. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34124. results.push(this._refractionTexture);
  34125. }
  34126. return results;
  34127. };
  34128. StandardMaterial.prototype.getActiveTextures = function () {
  34129. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34130. if (this._diffuseTexture) {
  34131. activeTextures.push(this._diffuseTexture);
  34132. }
  34133. if (this._ambientTexture) {
  34134. activeTextures.push(this._ambientTexture);
  34135. }
  34136. if (this._opacityTexture) {
  34137. activeTextures.push(this._opacityTexture);
  34138. }
  34139. if (this._reflectionTexture) {
  34140. activeTextures.push(this._reflectionTexture);
  34141. }
  34142. if (this._emissiveTexture) {
  34143. activeTextures.push(this._emissiveTexture);
  34144. }
  34145. if (this._specularTexture) {
  34146. activeTextures.push(this._specularTexture);
  34147. }
  34148. if (this._bumpTexture) {
  34149. activeTextures.push(this._bumpTexture);
  34150. }
  34151. if (this._lightmapTexture) {
  34152. activeTextures.push(this._lightmapTexture);
  34153. }
  34154. if (this._refractionTexture) {
  34155. activeTextures.push(this._refractionTexture);
  34156. }
  34157. return activeTextures;
  34158. };
  34159. StandardMaterial.prototype.hasTexture = function (texture) {
  34160. if (_super.prototype.hasTexture.call(this, texture)) {
  34161. return true;
  34162. }
  34163. if (this._diffuseTexture === texture) {
  34164. return true;
  34165. }
  34166. if (this._ambientTexture === texture) {
  34167. return true;
  34168. }
  34169. if (this._opacityTexture === texture) {
  34170. return true;
  34171. }
  34172. if (this._reflectionTexture === texture) {
  34173. return true;
  34174. }
  34175. if (this._emissiveTexture === texture) {
  34176. return true;
  34177. }
  34178. if (this._specularTexture === texture) {
  34179. return true;
  34180. }
  34181. if (this._bumpTexture === texture) {
  34182. return true;
  34183. }
  34184. if (this._lightmapTexture === texture) {
  34185. return true;
  34186. }
  34187. if (this._refractionTexture === texture) {
  34188. return true;
  34189. }
  34190. return false;
  34191. };
  34192. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34193. if (forceDisposeTextures) {
  34194. if (this._diffuseTexture) {
  34195. this._diffuseTexture.dispose();
  34196. }
  34197. if (this._ambientTexture) {
  34198. this._ambientTexture.dispose();
  34199. }
  34200. if (this._opacityTexture) {
  34201. this._opacityTexture.dispose();
  34202. }
  34203. if (this._reflectionTexture) {
  34204. this._reflectionTexture.dispose();
  34205. }
  34206. if (this._emissiveTexture) {
  34207. this._emissiveTexture.dispose();
  34208. }
  34209. if (this._specularTexture) {
  34210. this._specularTexture.dispose();
  34211. }
  34212. if (this._bumpTexture) {
  34213. this._bumpTexture.dispose();
  34214. }
  34215. if (this._lightmapTexture) {
  34216. this._lightmapTexture.dispose();
  34217. }
  34218. if (this._refractionTexture) {
  34219. this._refractionTexture.dispose();
  34220. }
  34221. }
  34222. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34223. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34224. }
  34225. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34226. };
  34227. StandardMaterial.prototype.clone = function (name) {
  34228. var _this = this;
  34229. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34230. result.name = name;
  34231. result.id = name;
  34232. return result;
  34233. };
  34234. StandardMaterial.prototype.serialize = function () {
  34235. return BABYLON.SerializationHelper.Serialize(this);
  34236. };
  34237. // Statics
  34238. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34239. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34240. };
  34241. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34242. get: function () {
  34243. return StandardMaterial._DiffuseTextureEnabled;
  34244. },
  34245. set: function (value) {
  34246. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34247. return;
  34248. }
  34249. StandardMaterial._DiffuseTextureEnabled = value;
  34250. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34251. },
  34252. enumerable: true,
  34253. configurable: true
  34254. });
  34255. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34256. get: function () {
  34257. return StandardMaterial._AmbientTextureEnabled;
  34258. },
  34259. set: function (value) {
  34260. if (StandardMaterial._AmbientTextureEnabled === value) {
  34261. return;
  34262. }
  34263. StandardMaterial._AmbientTextureEnabled = value;
  34264. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34265. },
  34266. enumerable: true,
  34267. configurable: true
  34268. });
  34269. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34270. get: function () {
  34271. return StandardMaterial._OpacityTextureEnabled;
  34272. },
  34273. set: function (value) {
  34274. if (StandardMaterial._OpacityTextureEnabled === value) {
  34275. return;
  34276. }
  34277. StandardMaterial._OpacityTextureEnabled = value;
  34278. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34279. },
  34280. enumerable: true,
  34281. configurable: true
  34282. });
  34283. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34284. get: function () {
  34285. return StandardMaterial._ReflectionTextureEnabled;
  34286. },
  34287. set: function (value) {
  34288. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34289. return;
  34290. }
  34291. StandardMaterial._ReflectionTextureEnabled = value;
  34292. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34293. },
  34294. enumerable: true,
  34295. configurable: true
  34296. });
  34297. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34298. get: function () {
  34299. return StandardMaterial._EmissiveTextureEnabled;
  34300. },
  34301. set: function (value) {
  34302. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34303. return;
  34304. }
  34305. StandardMaterial._EmissiveTextureEnabled = value;
  34306. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34307. },
  34308. enumerable: true,
  34309. configurable: true
  34310. });
  34311. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34312. get: function () {
  34313. return StandardMaterial._SpecularTextureEnabled;
  34314. },
  34315. set: function (value) {
  34316. if (StandardMaterial._SpecularTextureEnabled === value) {
  34317. return;
  34318. }
  34319. StandardMaterial._SpecularTextureEnabled = value;
  34320. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34321. },
  34322. enumerable: true,
  34323. configurable: true
  34324. });
  34325. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34326. get: function () {
  34327. return StandardMaterial._BumpTextureEnabled;
  34328. },
  34329. set: function (value) {
  34330. if (StandardMaterial._BumpTextureEnabled === value) {
  34331. return;
  34332. }
  34333. StandardMaterial._BumpTextureEnabled = value;
  34334. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34335. },
  34336. enumerable: true,
  34337. configurable: true
  34338. });
  34339. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34340. get: function () {
  34341. return StandardMaterial._LightmapTextureEnabled;
  34342. },
  34343. set: function (value) {
  34344. if (StandardMaterial._LightmapTextureEnabled === value) {
  34345. return;
  34346. }
  34347. StandardMaterial._LightmapTextureEnabled = value;
  34348. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34349. },
  34350. enumerable: true,
  34351. configurable: true
  34352. });
  34353. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34354. get: function () {
  34355. return StandardMaterial._RefractionTextureEnabled;
  34356. },
  34357. set: function (value) {
  34358. if (StandardMaterial._RefractionTextureEnabled === value) {
  34359. return;
  34360. }
  34361. StandardMaterial._RefractionTextureEnabled = value;
  34362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34363. },
  34364. enumerable: true,
  34365. configurable: true
  34366. });
  34367. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34368. get: function () {
  34369. return StandardMaterial._ColorGradingTextureEnabled;
  34370. },
  34371. set: function (value) {
  34372. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34373. return;
  34374. }
  34375. StandardMaterial._ColorGradingTextureEnabled = value;
  34376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34382. get: function () {
  34383. return StandardMaterial._FresnelEnabled;
  34384. },
  34385. set: function (value) {
  34386. if (StandardMaterial._FresnelEnabled === value) {
  34387. return;
  34388. }
  34389. StandardMaterial._FresnelEnabled = value;
  34390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34391. },
  34392. enumerable: true,
  34393. configurable: true
  34394. });
  34395. // Flags used to enable or disable a type of texture for all Standard Materials
  34396. StandardMaterial._DiffuseTextureEnabled = true;
  34397. StandardMaterial._AmbientTextureEnabled = true;
  34398. StandardMaterial._OpacityTextureEnabled = true;
  34399. StandardMaterial._ReflectionTextureEnabled = true;
  34400. StandardMaterial._EmissiveTextureEnabled = true;
  34401. StandardMaterial._SpecularTextureEnabled = true;
  34402. StandardMaterial._BumpTextureEnabled = true;
  34403. StandardMaterial._LightmapTextureEnabled = true;
  34404. StandardMaterial._RefractionTextureEnabled = true;
  34405. StandardMaterial._ColorGradingTextureEnabled = true;
  34406. StandardMaterial._FresnelEnabled = true;
  34407. __decorate([
  34408. BABYLON.serializeAsTexture("diffuseTexture")
  34409. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34410. __decorate([
  34411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34412. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34413. __decorate([
  34414. BABYLON.serializeAsTexture("ambientTexture")
  34415. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34416. __decorate([
  34417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34418. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34419. __decorate([
  34420. BABYLON.serializeAsTexture("opacityTexture")
  34421. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34422. __decorate([
  34423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34424. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34425. __decorate([
  34426. BABYLON.serializeAsTexture("reflectionTexture")
  34427. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34428. __decorate([
  34429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34430. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34431. __decorate([
  34432. BABYLON.serializeAsTexture("emissiveTexture")
  34433. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34434. __decorate([
  34435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34436. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34437. __decorate([
  34438. BABYLON.serializeAsTexture("specularTexture")
  34439. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34440. __decorate([
  34441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34442. ], StandardMaterial.prototype, "specularTexture", void 0);
  34443. __decorate([
  34444. BABYLON.serializeAsTexture("bumpTexture")
  34445. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34446. __decorate([
  34447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34448. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34449. __decorate([
  34450. BABYLON.serializeAsTexture("lightmapTexture")
  34451. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34452. __decorate([
  34453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34454. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34455. __decorate([
  34456. BABYLON.serializeAsTexture("refractionTexture")
  34457. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34458. __decorate([
  34459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34460. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34461. __decorate([
  34462. BABYLON.serializeAsColor3("ambient")
  34463. ], StandardMaterial.prototype, "ambientColor", void 0);
  34464. __decorate([
  34465. BABYLON.serializeAsColor3("diffuse")
  34466. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34467. __decorate([
  34468. BABYLON.serializeAsColor3("specular")
  34469. ], StandardMaterial.prototype, "specularColor", void 0);
  34470. __decorate([
  34471. BABYLON.serializeAsColor3("emissive")
  34472. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34473. __decorate([
  34474. BABYLON.serialize()
  34475. ], StandardMaterial.prototype, "specularPower", void 0);
  34476. __decorate([
  34477. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34478. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34479. __decorate([
  34480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34481. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34482. __decorate([
  34483. BABYLON.serialize("useEmissiveAsIllumination")
  34484. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34485. __decorate([
  34486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34487. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34488. __decorate([
  34489. BABYLON.serialize("linkEmissiveWithDiffuse")
  34490. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34491. __decorate([
  34492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34493. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34494. __decorate([
  34495. BABYLON.serialize("useSpecularOverAlpha")
  34496. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34497. __decorate([
  34498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34499. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34500. __decorate([
  34501. BABYLON.serialize("useReflectionOverAlpha")
  34502. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34503. __decorate([
  34504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34505. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34506. __decorate([
  34507. BABYLON.serialize("disableLighting")
  34508. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34509. __decorate([
  34510. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34511. ], StandardMaterial.prototype, "disableLighting", void 0);
  34512. __decorate([
  34513. BABYLON.serialize("useParallax")
  34514. ], StandardMaterial.prototype, "_useParallax", void 0);
  34515. __decorate([
  34516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34517. ], StandardMaterial.prototype, "useParallax", void 0);
  34518. __decorate([
  34519. BABYLON.serialize("useParallaxOcclusion")
  34520. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34521. __decorate([
  34522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34523. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34524. __decorate([
  34525. BABYLON.serialize()
  34526. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34527. __decorate([
  34528. BABYLON.serialize("roughness")
  34529. ], StandardMaterial.prototype, "_roughness", void 0);
  34530. __decorate([
  34531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34532. ], StandardMaterial.prototype, "roughness", void 0);
  34533. __decorate([
  34534. BABYLON.serialize()
  34535. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34536. __decorate([
  34537. BABYLON.serialize()
  34538. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34539. __decorate([
  34540. BABYLON.serialize("useLightmapAsShadowmap")
  34541. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34542. __decorate([
  34543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34544. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34545. __decorate([
  34546. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34547. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34548. __decorate([
  34549. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34550. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34551. __decorate([
  34552. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34553. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34554. __decorate([
  34555. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34556. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34557. __decorate([
  34558. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34559. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34560. __decorate([
  34561. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34562. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34563. __decorate([
  34564. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34565. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34566. __decorate([
  34567. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34568. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34569. __decorate([
  34570. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34571. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34572. __decorate([
  34573. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34574. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34575. __decorate([
  34576. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34577. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34578. __decorate([
  34579. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34580. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34581. __decorate([
  34582. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34583. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34584. __decorate([
  34585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34586. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34587. __decorate([
  34588. BABYLON.serialize("maxSimultaneousLights")
  34589. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34590. __decorate([
  34591. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34592. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34593. __decorate([
  34594. BABYLON.serialize("invertNormalMapX")
  34595. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34596. __decorate([
  34597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34598. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34599. __decorate([
  34600. BABYLON.serialize("invertNormalMapY")
  34601. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34602. __decorate([
  34603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34604. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34605. __decorate([
  34606. BABYLON.serialize("twoSidedLighting")
  34607. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34608. __decorate([
  34609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34610. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34611. __decorate([
  34612. BABYLON.serialize()
  34613. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34614. return StandardMaterial;
  34615. }(BABYLON.PushMaterial));
  34616. BABYLON.StandardMaterial = StandardMaterial;
  34617. })(BABYLON || (BABYLON = {}));
  34618. //# sourceMappingURL=babylon.standardMaterial.js.map
  34619. var BABYLON;
  34620. (function (BABYLON) {
  34621. var PBRMaterialDefines = /** @class */ (function (_super) {
  34622. __extends(PBRMaterialDefines, _super);
  34623. function PBRMaterialDefines() {
  34624. var _this = _super.call(this) || this;
  34625. _this.PBR = true;
  34626. _this.MAINUV1 = false;
  34627. _this.MAINUV2 = false;
  34628. _this.UV1 = false;
  34629. _this.UV2 = false;
  34630. _this.ALBEDO = false;
  34631. _this.ALBEDODIRECTUV = 0;
  34632. _this.VERTEXCOLOR = false;
  34633. _this.AMBIENT = false;
  34634. _this.AMBIENTDIRECTUV = 0;
  34635. _this.AMBIENTINGRAYSCALE = false;
  34636. _this.OPACITY = false;
  34637. _this.VERTEXALPHA = false;
  34638. _this.OPACITYDIRECTUV = 0;
  34639. _this.OPACITYRGB = false;
  34640. _this.ALPHATEST = false;
  34641. _this.DEPTHPREPASS = false;
  34642. _this.ALPHABLEND = false;
  34643. _this.ALPHAFROMALBEDO = false;
  34644. _this.ALPHATESTVALUE = 0.5;
  34645. _this.SPECULAROVERALPHA = false;
  34646. _this.RADIANCEOVERALPHA = false;
  34647. _this.ALPHAFRESNEL = false;
  34648. _this.PREMULTIPLYALPHA = false;
  34649. _this.EMISSIVE = false;
  34650. _this.EMISSIVEDIRECTUV = 0;
  34651. _this.REFLECTIVITY = false;
  34652. _this.REFLECTIVITYDIRECTUV = 0;
  34653. _this.SPECULARTERM = false;
  34654. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34655. _this.MICROSURFACEAUTOMATIC = false;
  34656. _this.LODBASEDMICROSFURACE = false;
  34657. _this.MICROSURFACEMAP = false;
  34658. _this.MICROSURFACEMAPDIRECTUV = 0;
  34659. _this.METALLICWORKFLOW = false;
  34660. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34661. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34662. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34663. _this.AOSTOREINMETALMAPRED = false;
  34664. _this.ENVIRONMENTBRDF = false;
  34665. _this.NORMAL = false;
  34666. _this.TANGENT = false;
  34667. _this.BUMP = false;
  34668. _this.BUMPDIRECTUV = 0;
  34669. _this.PARALLAX = false;
  34670. _this.PARALLAXOCCLUSION = false;
  34671. _this.NORMALXYSCALE = true;
  34672. _this.LIGHTMAP = false;
  34673. _this.LIGHTMAPDIRECTUV = 0;
  34674. _this.USELIGHTMAPASSHADOWMAP = false;
  34675. _this.REFLECTION = false;
  34676. _this.REFLECTIONMAP_3D = false;
  34677. _this.REFLECTIONMAP_SPHERICAL = false;
  34678. _this.REFLECTIONMAP_PLANAR = false;
  34679. _this.REFLECTIONMAP_CUBIC = false;
  34680. _this.REFLECTIONMAP_PROJECTION = false;
  34681. _this.REFLECTIONMAP_SKYBOX = false;
  34682. _this.REFLECTIONMAP_EXPLICIT = false;
  34683. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34684. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34685. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34686. _this.INVERTCUBICMAP = false;
  34687. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34688. _this.USESPHERICALINFRAGMENT = false;
  34689. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34690. _this.LODINREFLECTIONALPHA = false;
  34691. _this.GAMMAREFLECTION = false;
  34692. _this.REFRACTION = false;
  34693. _this.REFRACTIONMAP_3D = false;
  34694. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34695. _this.LODINREFRACTIONALPHA = false;
  34696. _this.GAMMAREFRACTION = false;
  34697. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34698. _this.INSTANCES = false;
  34699. _this.NUM_BONE_INFLUENCERS = 0;
  34700. _this.BonesPerMesh = 0;
  34701. _this.NONUNIFORMSCALING = false;
  34702. _this.MORPHTARGETS = false;
  34703. _this.MORPHTARGETS_NORMAL = false;
  34704. _this.MORPHTARGETS_TANGENT = false;
  34705. _this.NUM_MORPH_INFLUENCERS = 0;
  34706. _this.IMAGEPROCESSING = false;
  34707. _this.VIGNETTE = false;
  34708. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34709. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34710. _this.TONEMAPPING = false;
  34711. _this.CONTRAST = false;
  34712. _this.COLORCURVES = false;
  34713. _this.COLORGRADING = false;
  34714. _this.COLORGRADING3D = false;
  34715. _this.SAMPLER3DGREENDEPTH = false;
  34716. _this.SAMPLER3DBGRMAP = false;
  34717. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34718. _this.EXPOSURE = false;
  34719. _this.USEPHYSICALLIGHTFALLOFF = false;
  34720. _this.TWOSIDEDLIGHTING = false;
  34721. _this.SHADOWFLOAT = false;
  34722. _this.CLIPPLANE = false;
  34723. _this.POINTSIZE = false;
  34724. _this.FOG = false;
  34725. _this.LOGARITHMICDEPTH = false;
  34726. _this.FORCENORMALFORWARD = false;
  34727. _this.rebuild();
  34728. return _this;
  34729. }
  34730. PBRMaterialDefines.prototype.reset = function () {
  34731. _super.prototype.reset.call(this);
  34732. this.ALPHATESTVALUE = 0.5;
  34733. this.PBR = true;
  34734. };
  34735. return PBRMaterialDefines;
  34736. }(BABYLON.MaterialDefines));
  34737. /**
  34738. * The Physically based material base class of BJS.
  34739. *
  34740. * This offers the main features of a standard PBR material.
  34741. * For more information, please refer to the documentation :
  34742. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34743. */
  34744. var PBRBaseMaterial = /** @class */ (function (_super) {
  34745. __extends(PBRBaseMaterial, _super);
  34746. /**
  34747. * Instantiates a new PBRMaterial instance.
  34748. *
  34749. * @param name The material name
  34750. * @param scene The scene the material will be use in.
  34751. */
  34752. function PBRBaseMaterial(name, scene) {
  34753. var _this = _super.call(this, name, scene) || this;
  34754. /**
  34755. * Intensity of the direct lights e.g. the four lights available in your scene.
  34756. * This impacts both the direct diffuse and specular highlights.
  34757. */
  34758. _this._directIntensity = 1.0;
  34759. /**
  34760. * Intensity of the emissive part of the material.
  34761. * This helps controlling the emissive effect without modifying the emissive color.
  34762. */
  34763. _this._emissiveIntensity = 1.0;
  34764. /**
  34765. * Intensity of the environment e.g. how much the environment will light the object
  34766. * either through harmonics for rough material or through the refelction for shiny ones.
  34767. */
  34768. _this._environmentIntensity = 1.0;
  34769. /**
  34770. * This is a special control allowing the reduction of the specular highlights coming from the
  34771. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34772. */
  34773. _this._specularIntensity = 1.0;
  34774. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34775. /**
  34776. * Debug Control allowing disabling the bump map on this material.
  34777. */
  34778. _this._disableBumpMap = false;
  34779. /**
  34780. * AKA Occlusion Texture Intensity in other nomenclature.
  34781. */
  34782. _this._ambientTextureStrength = 1.0;
  34783. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34784. /**
  34785. * AKA Diffuse Color in other nomenclature.
  34786. */
  34787. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34788. /**
  34789. * AKA Specular Color in other nomenclature.
  34790. */
  34791. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34792. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34793. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34794. /**
  34795. * AKA Glossiness in other nomenclature.
  34796. */
  34797. _this._microSurface = 0.9;
  34798. /**
  34799. * source material index of refraction (IOR)' / 'destination material IOR.
  34800. */
  34801. _this._indexOfRefraction = 0.66;
  34802. /**
  34803. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34804. */
  34805. _this._invertRefractionY = false;
  34806. /**
  34807. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34808. * Materials half opaque for instance using refraction could benefit from this control.
  34809. */
  34810. _this._linkRefractionWithTransparency = false;
  34811. _this._useLightmapAsShadowmap = false;
  34812. /**
  34813. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34814. */
  34815. _this._useAlphaFromAlbedoTexture = false;
  34816. /**
  34817. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34818. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34819. */
  34820. _this._useSpecularOverAlpha = true;
  34821. /**
  34822. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34823. */
  34824. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34825. /**
  34826. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34827. */
  34828. _this._useRoughnessFromMetallicTextureAlpha = true;
  34829. /**
  34830. * Specifies if the metallic texture contains the roughness information in its green channel.
  34831. */
  34832. _this._useRoughnessFromMetallicTextureGreen = false;
  34833. /**
  34834. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34835. */
  34836. _this._useMetallnessFromMetallicTextureBlue = false;
  34837. /**
  34838. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34839. */
  34840. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34841. /**
  34842. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34843. */
  34844. _this._useAmbientInGrayScale = false;
  34845. /**
  34846. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34847. * The material will try to infer what glossiness each pixel should be.
  34848. */
  34849. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34850. /**
  34851. * BJS is using an harcoded light falloff based on a manually sets up range.
  34852. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34853. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34854. */
  34855. _this._usePhysicalLightFalloff = true;
  34856. /**
  34857. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34858. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34859. */
  34860. _this._useRadianceOverAlpha = true;
  34861. /**
  34862. * Allows using the bump map in parallax mode.
  34863. */
  34864. _this._useParallax = false;
  34865. /**
  34866. * Allows using the bump map in parallax occlusion mode.
  34867. */
  34868. _this._useParallaxOcclusion = false;
  34869. /**
  34870. * Controls the scale bias of the parallax mode.
  34871. */
  34872. _this._parallaxScaleBias = 0.05;
  34873. /**
  34874. * If sets to true, disables all the lights affecting the material.
  34875. */
  34876. _this._disableLighting = false;
  34877. /**
  34878. * Number of Simultaneous lights allowed on the material.
  34879. */
  34880. _this._maxSimultaneousLights = 4;
  34881. /**
  34882. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34883. */
  34884. _this._invertNormalMapX = false;
  34885. /**
  34886. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34887. */
  34888. _this._invertNormalMapY = false;
  34889. /**
  34890. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34891. */
  34892. _this._twoSidedLighting = false;
  34893. /**
  34894. * Defines the alpha limits in alpha test mode.
  34895. */
  34896. _this._alphaCutOff = 0.4;
  34897. /**
  34898. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34899. */
  34900. _this._forceAlphaTest = false;
  34901. /**
  34902. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34903. * And/Or occlude the blended part.
  34904. */
  34905. _this._useAlphaFresnel = false;
  34906. /**
  34907. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34908. * from cos thetav and roughness:
  34909. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34910. */
  34911. _this._environmentBRDFTexture = null;
  34912. /**
  34913. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34914. */
  34915. _this._forceIrradianceInFragment = false;
  34916. /**
  34917. * Force normal to face away from face.
  34918. * (Temporary internal fix to remove before 3.1)
  34919. */
  34920. _this._forceNormalForward = false;
  34921. _this._renderTargets = new BABYLON.SmartArray(16);
  34922. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34923. // Setup the default processing configuration to the scene.
  34924. _this._attachImageProcessingConfiguration(null);
  34925. _this.getRenderTargetTextures = function () {
  34926. _this._renderTargets.reset();
  34927. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34928. _this._renderTargets.push(_this._reflectionTexture);
  34929. }
  34930. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34931. _this._renderTargets.push(_this._refractionTexture);
  34932. }
  34933. return _this._renderTargets;
  34934. };
  34935. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34936. return _this;
  34937. }
  34938. /**
  34939. * Attaches a new image processing configuration to the PBR Material.
  34940. * @param configuration
  34941. */
  34942. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34943. var _this = this;
  34944. if (configuration === this._imageProcessingConfiguration) {
  34945. return;
  34946. }
  34947. // Detaches observer.
  34948. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34949. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34950. }
  34951. // Pick the scene configuration if needed.
  34952. if (!configuration) {
  34953. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34954. }
  34955. else {
  34956. this._imageProcessingConfiguration = configuration;
  34957. }
  34958. // Attaches observer.
  34959. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34960. _this._markAllSubMeshesAsImageProcessingDirty();
  34961. });
  34962. };
  34963. PBRBaseMaterial.prototype.getClassName = function () {
  34964. return "PBRBaseMaterial";
  34965. };
  34966. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34967. get: function () {
  34968. return this._useLogarithmicDepth;
  34969. },
  34970. set: function (value) {
  34971. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34972. },
  34973. enumerable: true,
  34974. configurable: true
  34975. });
  34976. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34977. if (this._linkRefractionWithTransparency) {
  34978. return false;
  34979. }
  34980. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34981. };
  34982. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34983. if (this._forceAlphaTest) {
  34984. return true;
  34985. }
  34986. if (this._linkRefractionWithTransparency) {
  34987. return false;
  34988. }
  34989. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34990. };
  34991. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34992. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34993. };
  34994. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34995. return this._albedoTexture;
  34996. };
  34997. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34998. var _this = this;
  34999. if (subMesh.effect && this.isFrozen) {
  35000. if (this._wasPreviouslyReady) {
  35001. return true;
  35002. }
  35003. }
  35004. if (!subMesh._materialDefines) {
  35005. subMesh._materialDefines = new PBRMaterialDefines();
  35006. }
  35007. var scene = this.getScene();
  35008. var defines = subMesh._materialDefines;
  35009. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35010. if (defines._renderId === scene.getRenderId()) {
  35011. return true;
  35012. }
  35013. }
  35014. var engine = scene.getEngine();
  35015. // Lights
  35016. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35017. defines._needNormals = true;
  35018. // Textures
  35019. if (defines._areTexturesDirty) {
  35020. defines._needUVs = false;
  35021. if (scene.texturesEnabled) {
  35022. if (scene.getEngine().getCaps().textureLOD) {
  35023. defines.LODBASEDMICROSFURACE = true;
  35024. }
  35025. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35026. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35027. return false;
  35028. }
  35029. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35030. }
  35031. else {
  35032. defines.ALBEDO = false;
  35033. }
  35034. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35035. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35036. return false;
  35037. }
  35038. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35039. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35040. }
  35041. else {
  35042. defines.AMBIENT = false;
  35043. }
  35044. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35045. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35046. return false;
  35047. }
  35048. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35049. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35050. }
  35051. else {
  35052. defines.OPACITY = false;
  35053. }
  35054. var reflectionTexture = this._getReflectionTexture();
  35055. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35056. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35057. return false;
  35058. }
  35059. defines.REFLECTION = true;
  35060. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35061. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35062. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35063. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35064. defines.INVERTCUBICMAP = true;
  35065. }
  35066. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35067. switch (reflectionTexture.coordinatesMode) {
  35068. case BABYLON.Texture.CUBIC_MODE:
  35069. case BABYLON.Texture.INVCUBIC_MODE:
  35070. defines.REFLECTIONMAP_CUBIC = true;
  35071. break;
  35072. case BABYLON.Texture.EXPLICIT_MODE:
  35073. defines.REFLECTIONMAP_EXPLICIT = true;
  35074. break;
  35075. case BABYLON.Texture.PLANAR_MODE:
  35076. defines.REFLECTIONMAP_PLANAR = true;
  35077. break;
  35078. case BABYLON.Texture.PROJECTION_MODE:
  35079. defines.REFLECTIONMAP_PROJECTION = true;
  35080. break;
  35081. case BABYLON.Texture.SKYBOX_MODE:
  35082. defines.REFLECTIONMAP_SKYBOX = true;
  35083. break;
  35084. case BABYLON.Texture.SPHERICAL_MODE:
  35085. defines.REFLECTIONMAP_SPHERICAL = true;
  35086. break;
  35087. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35088. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35089. break;
  35090. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35091. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35092. break;
  35093. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35094. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35095. break;
  35096. }
  35097. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35098. if (reflectionTexture.sphericalPolynomial) {
  35099. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35100. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35101. defines.USESPHERICALINFRAGMENT = true;
  35102. }
  35103. }
  35104. }
  35105. }
  35106. else {
  35107. defines.REFLECTION = false;
  35108. defines.REFLECTIONMAP_3D = false;
  35109. defines.REFLECTIONMAP_SPHERICAL = false;
  35110. defines.REFLECTIONMAP_PLANAR = false;
  35111. defines.REFLECTIONMAP_CUBIC = false;
  35112. defines.REFLECTIONMAP_PROJECTION = false;
  35113. defines.REFLECTIONMAP_SKYBOX = false;
  35114. defines.REFLECTIONMAP_EXPLICIT = false;
  35115. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35116. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35117. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35118. defines.INVERTCUBICMAP = false;
  35119. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35120. defines.USESPHERICALINFRAGMENT = false;
  35121. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35122. defines.LODINREFLECTIONALPHA = false;
  35123. defines.GAMMAREFLECTION = false;
  35124. }
  35125. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35126. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35127. return false;
  35128. }
  35129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35130. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35131. }
  35132. else {
  35133. defines.LIGHTMAP = false;
  35134. }
  35135. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35136. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35137. return false;
  35138. }
  35139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35140. }
  35141. else {
  35142. defines.EMISSIVE = false;
  35143. }
  35144. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35145. if (this._metallicTexture) {
  35146. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35147. return false;
  35148. }
  35149. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35150. defines.METALLICWORKFLOW = true;
  35151. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35152. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35153. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35154. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35155. }
  35156. else if (this._reflectivityTexture) {
  35157. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35158. return false;
  35159. }
  35160. defines.METALLICWORKFLOW = false;
  35161. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35162. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35163. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35164. }
  35165. else {
  35166. defines.METALLICWORKFLOW = false;
  35167. defines.REFLECTIVITY = false;
  35168. }
  35169. if (this._microSurfaceTexture) {
  35170. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35171. return false;
  35172. }
  35173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35174. }
  35175. else {
  35176. defines.MICROSURFACEMAP = false;
  35177. }
  35178. }
  35179. else {
  35180. defines.REFLECTIVITY = false;
  35181. defines.MICROSURFACEMAP = false;
  35182. }
  35183. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35184. // Bump texure can not be none blocking.
  35185. if (!this._bumpTexture.isReady()) {
  35186. return false;
  35187. }
  35188. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35189. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35190. defines.PARALLAX = true;
  35191. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35192. }
  35193. else {
  35194. defines.PARALLAX = false;
  35195. }
  35196. }
  35197. else {
  35198. defines.BUMP = false;
  35199. }
  35200. var refractionTexture = this._getRefractionTexture();
  35201. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35202. if (!refractionTexture.isReadyOrNotBlocking()) {
  35203. return false;
  35204. }
  35205. defines.REFRACTION = true;
  35206. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35207. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35208. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35209. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35210. if (this._linkRefractionWithTransparency) {
  35211. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35212. }
  35213. }
  35214. else {
  35215. defines.REFRACTION = false;
  35216. }
  35217. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35218. // This is blocking.
  35219. if (!this._environmentBRDFTexture.isReady()) {
  35220. return false;
  35221. }
  35222. defines.ENVIRONMENTBRDF = true;
  35223. }
  35224. else {
  35225. defines.ENVIRONMENTBRDF = false;
  35226. }
  35227. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35228. defines.ALPHAFROMALBEDO = true;
  35229. }
  35230. else {
  35231. defines.ALPHAFROMALBEDO = false;
  35232. }
  35233. }
  35234. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35235. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35236. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35237. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35238. defines.METALLICWORKFLOW = true;
  35239. }
  35240. else {
  35241. defines.METALLICWORKFLOW = false;
  35242. }
  35243. if (!this.backFaceCulling && this._twoSidedLighting) {
  35244. defines.TWOSIDEDLIGHTING = true;
  35245. }
  35246. else {
  35247. defines.TWOSIDEDLIGHTING = false;
  35248. }
  35249. defines.ALPHATESTVALUE = this._alphaCutOff;
  35250. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35251. defines.ALPHABLEND = this.needAlphaBlending();
  35252. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35253. }
  35254. if (defines._areImageProcessingDirty) {
  35255. if (!this._imageProcessingConfiguration.isReady()) {
  35256. return false;
  35257. }
  35258. this._imageProcessingConfiguration.prepareDefines(defines);
  35259. }
  35260. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35261. // Misc.
  35262. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35263. // Values that need to be evaluated on every frame
  35264. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35265. // Attribs
  35266. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35267. if (mesh) {
  35268. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35269. mesh.createNormals(true);
  35270. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35271. }
  35272. }
  35273. }
  35274. // Get correct effect
  35275. if (defines.isDirty) {
  35276. defines.markAsProcessed();
  35277. scene.resetCachedMaterial();
  35278. // Fallbacks
  35279. var fallbacks = new BABYLON.EffectFallbacks();
  35280. if (defines.ENVIRONMENTBRDF) {
  35281. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35282. }
  35283. if (defines.REFLECTION) {
  35284. fallbacks.addFallback(0, "REFLECTION");
  35285. }
  35286. if (defines.REFRACTION) {
  35287. fallbacks.addFallback(0, "REFRACTION");
  35288. }
  35289. if (defines.REFLECTIVITY) {
  35290. fallbacks.addFallback(0, "REFLECTIVITY");
  35291. }
  35292. if (defines.BUMP) {
  35293. fallbacks.addFallback(0, "BUMP");
  35294. }
  35295. if (defines.PARALLAX) {
  35296. fallbacks.addFallback(1, "PARALLAX");
  35297. }
  35298. if (defines.PARALLAXOCCLUSION) {
  35299. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35300. }
  35301. if (defines.SPECULAROVERALPHA) {
  35302. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35303. }
  35304. if (defines.FOG) {
  35305. fallbacks.addFallback(1, "FOG");
  35306. }
  35307. if (defines.POINTSIZE) {
  35308. fallbacks.addFallback(0, "POINTSIZE");
  35309. }
  35310. if (defines.LOGARITHMICDEPTH) {
  35311. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35312. }
  35313. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35314. if (defines.SPECULARTERM) {
  35315. fallbacks.addFallback(0, "SPECULARTERM");
  35316. }
  35317. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35318. fallbacks.addCPUSkinningFallback(0, mesh);
  35319. }
  35320. //Attributes
  35321. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35322. if (defines.NORMAL) {
  35323. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35324. }
  35325. if (defines.TANGENT) {
  35326. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35327. }
  35328. if (defines.UV1) {
  35329. attribs.push(BABYLON.VertexBuffer.UVKind);
  35330. }
  35331. if (defines.UV2) {
  35332. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35333. }
  35334. if (defines.VERTEXCOLOR) {
  35335. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35336. }
  35337. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35338. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35339. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35340. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35341. "vFogInfos", "vFogColor", "pointSize",
  35342. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35343. "mBones",
  35344. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35345. "vLightingIntensity",
  35346. "logarithmicDepthConstant",
  35347. "vSphericalX", "vSphericalY", "vSphericalZ",
  35348. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35349. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35350. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35351. "vTangentSpaceParams"
  35352. ];
  35353. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35354. "bumpSampler", "lightmapSampler", "opacitySampler",
  35355. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35356. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35357. "microSurfaceSampler", "environmentBrdfSampler"];
  35358. var uniformBuffers = ["Material", "Scene"];
  35359. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35360. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35361. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35362. uniformsNames: uniforms,
  35363. uniformBuffersNames: uniformBuffers,
  35364. samplers: samplers,
  35365. defines: defines,
  35366. maxSimultaneousLights: this._maxSimultaneousLights
  35367. });
  35368. var onCompiled = function (effect) {
  35369. if (_this.onCompiled) {
  35370. _this.onCompiled(effect);
  35371. }
  35372. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35373. };
  35374. var join = defines.toString();
  35375. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35376. attributes: attribs,
  35377. uniformsNames: uniforms,
  35378. uniformBuffersNames: uniformBuffers,
  35379. samplers: samplers,
  35380. defines: join,
  35381. fallbacks: fallbacks,
  35382. onCompiled: onCompiled,
  35383. onError: this.onError,
  35384. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35385. }, engine), defines);
  35386. this.buildUniformLayout();
  35387. }
  35388. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35389. return false;
  35390. }
  35391. defines._renderId = scene.getRenderId();
  35392. this._wasPreviouslyReady = true;
  35393. return true;
  35394. };
  35395. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35396. // Order is important !
  35397. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35398. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35399. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35400. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35401. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35402. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35403. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35404. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35405. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35406. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35407. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35408. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35409. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35410. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35411. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35412. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35413. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35414. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35415. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35416. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35417. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35418. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35419. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35420. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35421. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35422. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35423. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35424. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35425. this._uniformBuffer.addUniform("pointSize", 1);
  35426. this._uniformBuffer.create();
  35427. };
  35428. PBRBaseMaterial.prototype.unbind = function () {
  35429. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35430. this._uniformBuffer.setTexture("reflectionSampler", null);
  35431. }
  35432. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35433. this._uniformBuffer.setTexture("refractionSampler", null);
  35434. }
  35435. _super.prototype.unbind.call(this);
  35436. };
  35437. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35438. this._activeEffect.setMatrix("world", world);
  35439. };
  35440. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35441. var scene = this.getScene();
  35442. var defines = subMesh._materialDefines;
  35443. if (!defines) {
  35444. return;
  35445. }
  35446. var effect = subMesh.effect;
  35447. if (!effect) {
  35448. return;
  35449. }
  35450. this._activeEffect = effect;
  35451. // Matrices
  35452. this.bindOnlyWorldMatrix(world);
  35453. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35454. // Bones
  35455. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35456. var reflectionTexture = null;
  35457. if (mustRebind) {
  35458. this._uniformBuffer.bindToEffect(effect, "Material");
  35459. this.bindViewProjection(effect);
  35460. reflectionTexture = this._getReflectionTexture();
  35461. var refractionTexture = this._getRefractionTexture();
  35462. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35463. // Texture uniforms
  35464. if (scene.texturesEnabled) {
  35465. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35466. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35467. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35468. }
  35469. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35470. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35471. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35472. }
  35473. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35474. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35475. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35476. }
  35477. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35478. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35479. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35480. var polynomials = reflectionTexture.sphericalPolynomial;
  35481. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35482. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35483. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35484. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35485. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35486. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35487. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35488. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35489. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35490. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35491. }
  35492. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35493. }
  35494. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35495. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35496. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35497. }
  35498. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35499. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35500. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35501. }
  35502. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35503. if (this._metallicTexture) {
  35504. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35505. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35506. }
  35507. else if (this._reflectivityTexture) {
  35508. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35509. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35510. }
  35511. if (this._microSurfaceTexture) {
  35512. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35513. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35514. }
  35515. }
  35516. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35517. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35518. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35519. if (scene._mirroredCameraPosition) {
  35520. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35521. }
  35522. else {
  35523. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35524. }
  35525. }
  35526. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35527. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35528. var depth = 1.0;
  35529. if (!refractionTexture.isCube) {
  35530. if (refractionTexture.depth) {
  35531. depth = refractionTexture.depth;
  35532. }
  35533. }
  35534. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35535. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35536. }
  35537. }
  35538. // Point size
  35539. if (this.pointsCloud) {
  35540. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35541. }
  35542. // Colors
  35543. if (defines.METALLICWORKFLOW) {
  35544. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35545. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35546. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35547. }
  35548. else {
  35549. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35550. }
  35551. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35552. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35553. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35554. // Misc
  35555. this._lightingInfos.x = this._directIntensity;
  35556. this._lightingInfos.y = this._emissiveIntensity;
  35557. this._lightingInfos.z = this._environmentIntensity;
  35558. this._lightingInfos.w = this._specularIntensity;
  35559. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35560. }
  35561. // Textures
  35562. if (scene.texturesEnabled) {
  35563. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35564. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35565. }
  35566. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35567. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35568. }
  35569. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35570. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35571. }
  35572. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35573. if (defines.LODBASEDMICROSFURACE) {
  35574. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35575. }
  35576. else {
  35577. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35578. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35579. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35580. }
  35581. }
  35582. if (defines.ENVIRONMENTBRDF) {
  35583. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35584. }
  35585. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35586. if (defines.LODBASEDMICROSFURACE) {
  35587. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35588. }
  35589. else {
  35590. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35591. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35592. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35593. }
  35594. }
  35595. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35596. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35597. }
  35598. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35599. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35600. }
  35601. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35602. if (this._metallicTexture) {
  35603. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35604. }
  35605. else if (this._reflectivityTexture) {
  35606. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35607. }
  35608. if (this._microSurfaceTexture) {
  35609. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35610. }
  35611. }
  35612. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35613. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35614. }
  35615. }
  35616. // Clip plane
  35617. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35618. // Colors
  35619. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35620. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35621. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35622. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35623. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35624. }
  35625. if (mustRebind || !this.isFrozen) {
  35626. // Lights
  35627. if (scene.lightsEnabled && !this._disableLighting) {
  35628. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35629. }
  35630. // View
  35631. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35632. this.bindView(effect);
  35633. }
  35634. // Fog
  35635. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35636. // Morph targets
  35637. if (defines.NUM_MORPH_INFLUENCERS) {
  35638. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35639. }
  35640. // image processing
  35641. this._imageProcessingConfiguration.bind(this._activeEffect);
  35642. // Log. depth
  35643. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35644. }
  35645. this._uniformBuffer.update();
  35646. this._afterBind(mesh);
  35647. };
  35648. PBRBaseMaterial.prototype.getAnimatables = function () {
  35649. var results = [];
  35650. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35651. results.push(this._albedoTexture);
  35652. }
  35653. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35654. results.push(this._ambientTexture);
  35655. }
  35656. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35657. results.push(this._opacityTexture);
  35658. }
  35659. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35660. results.push(this._reflectionTexture);
  35661. }
  35662. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35663. results.push(this._emissiveTexture);
  35664. }
  35665. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35666. results.push(this._metallicTexture);
  35667. }
  35668. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35669. results.push(this._reflectivityTexture);
  35670. }
  35671. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35672. results.push(this._bumpTexture);
  35673. }
  35674. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35675. results.push(this._lightmapTexture);
  35676. }
  35677. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35678. results.push(this._refractionTexture);
  35679. }
  35680. return results;
  35681. };
  35682. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35683. if (this._reflectionTexture) {
  35684. return this._reflectionTexture;
  35685. }
  35686. return this.getScene().environmentTexture;
  35687. };
  35688. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35689. if (this._refractionTexture) {
  35690. return this._refractionTexture;
  35691. }
  35692. if (this._linkRefractionWithTransparency) {
  35693. return this.getScene().environmentTexture;
  35694. }
  35695. return null;
  35696. };
  35697. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35698. if (forceDisposeTextures) {
  35699. if (this._albedoTexture) {
  35700. this._albedoTexture.dispose();
  35701. }
  35702. if (this._ambientTexture) {
  35703. this._ambientTexture.dispose();
  35704. }
  35705. if (this._opacityTexture) {
  35706. this._opacityTexture.dispose();
  35707. }
  35708. if (this._reflectionTexture) {
  35709. this._reflectionTexture.dispose();
  35710. }
  35711. if (this._environmentBRDFTexture) {
  35712. this._environmentBRDFTexture.dispose();
  35713. }
  35714. if (this._emissiveTexture) {
  35715. this._emissiveTexture.dispose();
  35716. }
  35717. if (this._metallicTexture) {
  35718. this._metallicTexture.dispose();
  35719. }
  35720. if (this._reflectivityTexture) {
  35721. this._reflectivityTexture.dispose();
  35722. }
  35723. if (this._bumpTexture) {
  35724. this._bumpTexture.dispose();
  35725. }
  35726. if (this._lightmapTexture) {
  35727. this._lightmapTexture.dispose();
  35728. }
  35729. if (this._refractionTexture) {
  35730. this._refractionTexture.dispose();
  35731. }
  35732. }
  35733. this._renderTargets.dispose();
  35734. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35735. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35736. }
  35737. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35738. };
  35739. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35740. __decorate([
  35741. BABYLON.serializeAsImageProcessingConfiguration()
  35742. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35743. __decorate([
  35744. BABYLON.serialize()
  35745. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35746. return PBRBaseMaterial;
  35747. }(BABYLON.PushMaterial));
  35748. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35749. })(BABYLON || (BABYLON = {}));
  35750. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35751. var BABYLON;
  35752. (function (BABYLON) {
  35753. var Internals;
  35754. (function (Internals) {
  35755. /**
  35756. * The Physically based simple base material of BJS.
  35757. *
  35758. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35759. * It is used as the base class for both the specGloss and metalRough conventions.
  35760. */
  35761. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35762. __extends(PBRBaseSimpleMaterial, _super);
  35763. /**
  35764. * Instantiates a new PBRMaterial instance.
  35765. *
  35766. * @param name The material name
  35767. * @param scene The scene the material will be use in.
  35768. */
  35769. function PBRBaseSimpleMaterial(name, scene) {
  35770. var _this = _super.call(this, name, scene) || this;
  35771. /**
  35772. * Number of Simultaneous lights allowed on the material.
  35773. */
  35774. _this.maxSimultaneousLights = 4;
  35775. /**
  35776. * If sets to true, disables all the lights affecting the material.
  35777. */
  35778. _this.disableLighting = false;
  35779. /**
  35780. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35781. */
  35782. _this.invertNormalMapX = false;
  35783. /**
  35784. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35785. */
  35786. _this.invertNormalMapY = false;
  35787. /**
  35788. * Emissivie color used to self-illuminate the model.
  35789. */
  35790. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35791. /**
  35792. * Occlusion Channel Strenght.
  35793. */
  35794. _this.occlusionStrength = 1.0;
  35795. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35796. _this._useAmbientInGrayScale = true;
  35797. return _this;
  35798. }
  35799. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35800. /**
  35801. * Gets the current transparency mode.
  35802. */
  35803. get: function () {
  35804. return this._transparencyMode;
  35805. },
  35806. /**
  35807. * Sets the transparency mode of the material.
  35808. */
  35809. set: function (value) {
  35810. if (this._transparencyMode === value) {
  35811. return;
  35812. }
  35813. this._transparencyMode = value;
  35814. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35815. this._forceAlphaTest = true;
  35816. }
  35817. else {
  35818. this._forceAlphaTest = false;
  35819. }
  35820. this._markAllSubMeshesAsTexturesDirty();
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35826. /**
  35827. * Gets the current double sided mode.
  35828. */
  35829. get: function () {
  35830. return this._twoSidedLighting;
  35831. },
  35832. /**
  35833. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35834. */
  35835. set: function (value) {
  35836. if (this._twoSidedLighting === value) {
  35837. return;
  35838. }
  35839. this._twoSidedLighting = value;
  35840. this.backFaceCulling = !value;
  35841. this._markAllSubMeshesAsTexturesDirty();
  35842. },
  35843. enumerable: true,
  35844. configurable: true
  35845. });
  35846. /**
  35847. * Specifies wether or not the alpha value of the albedo texture should be used.
  35848. */
  35849. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35850. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35851. };
  35852. /**
  35853. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35854. */
  35855. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35856. if (this._linkRefractionWithTransparency) {
  35857. return false;
  35858. }
  35859. return (this.alpha < 1.0) ||
  35860. (this._shouldUseAlphaFromAlbedoTexture() &&
  35861. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35862. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35863. };
  35864. /**
  35865. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35866. */
  35867. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35868. if (this._linkRefractionWithTransparency) {
  35869. return false;
  35870. }
  35871. return this._shouldUseAlphaFromAlbedoTexture() &&
  35872. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35873. };
  35874. /**
  35875. * Return the active textures of the material.
  35876. */
  35877. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35878. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35879. if (this.environmentTexture) {
  35880. activeTextures.push(this.environmentTexture);
  35881. }
  35882. if (this.normalTexture) {
  35883. activeTextures.push(this.normalTexture);
  35884. }
  35885. if (this.emissiveTexture) {
  35886. activeTextures.push(this.emissiveTexture);
  35887. }
  35888. if (this.occlusionTexture) {
  35889. activeTextures.push(this.occlusionTexture);
  35890. }
  35891. return activeTextures;
  35892. };
  35893. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35894. return "PBRBaseSimpleMaterial";
  35895. };
  35896. __decorate([
  35897. BABYLON.serialize(),
  35898. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35899. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35900. __decorate([
  35901. BABYLON.serialize(),
  35902. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35903. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35904. __decorate([
  35905. BABYLON.serializeAsTexture(),
  35906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35907. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35908. __decorate([
  35909. BABYLON.serialize(),
  35910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35911. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35912. __decorate([
  35913. BABYLON.serialize(),
  35914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35915. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35916. __decorate([
  35917. BABYLON.serializeAsTexture(),
  35918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35919. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35920. __decorate([
  35921. BABYLON.serializeAsColor3("emissive"),
  35922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35923. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35924. __decorate([
  35925. BABYLON.serializeAsTexture(),
  35926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35927. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35928. __decorate([
  35929. BABYLON.serialize(),
  35930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35931. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35932. __decorate([
  35933. BABYLON.serializeAsTexture(),
  35934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35935. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35936. __decorate([
  35937. BABYLON.serialize(),
  35938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35939. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35940. __decorate([
  35941. BABYLON.serialize()
  35942. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35943. __decorate([
  35944. BABYLON.serialize()
  35945. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35946. return PBRBaseSimpleMaterial;
  35947. }(BABYLON.PBRBaseMaterial));
  35948. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35949. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35950. })(BABYLON || (BABYLON = {}));
  35951. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35952. var BABYLON;
  35953. (function (BABYLON) {
  35954. /**
  35955. * The Physically based material of BJS.
  35956. *
  35957. * This offers the main features of a standard PBR material.
  35958. * For more information, please refer to the documentation :
  35959. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35960. */
  35961. var PBRMaterial = /** @class */ (function (_super) {
  35962. __extends(PBRMaterial, _super);
  35963. /**
  35964. * Instantiates a new PBRMaterial instance.
  35965. *
  35966. * @param name The material name
  35967. * @param scene The scene the material will be use in.
  35968. */
  35969. function PBRMaterial(name, scene) {
  35970. var _this = _super.call(this, name, scene) || this;
  35971. /**
  35972. * Intensity of the direct lights e.g. the four lights available in your scene.
  35973. * This impacts both the direct diffuse and specular highlights.
  35974. */
  35975. _this.directIntensity = 1.0;
  35976. /**
  35977. * Intensity of the emissive part of the material.
  35978. * This helps controlling the emissive effect without modifying the emissive color.
  35979. */
  35980. _this.emissiveIntensity = 1.0;
  35981. /**
  35982. * Intensity of the environment e.g. how much the environment will light the object
  35983. * either through harmonics for rough material or through the refelction for shiny ones.
  35984. */
  35985. _this.environmentIntensity = 1.0;
  35986. /**
  35987. * This is a special control allowing the reduction of the specular highlights coming from the
  35988. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35989. */
  35990. _this.specularIntensity = 1.0;
  35991. /**
  35992. * Debug Control allowing disabling the bump map on this material.
  35993. */
  35994. _this.disableBumpMap = false;
  35995. /**
  35996. * AKA Occlusion Texture Intensity in other nomenclature.
  35997. */
  35998. _this.ambientTextureStrength = 1.0;
  35999. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36000. /**
  36001. * AKA Diffuse Color in other nomenclature.
  36002. */
  36003. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36004. /**
  36005. * AKA Specular Color in other nomenclature.
  36006. */
  36007. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36008. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36009. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36010. /**
  36011. * AKA Glossiness in other nomenclature.
  36012. */
  36013. _this.microSurface = 1.0;
  36014. /**
  36015. * source material index of refraction (IOR)' / 'destination material IOR.
  36016. */
  36017. _this.indexOfRefraction = 0.66;
  36018. /**
  36019. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36020. */
  36021. _this.invertRefractionY = false;
  36022. /**
  36023. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36024. * Materials half opaque for instance using refraction could benefit from this control.
  36025. */
  36026. _this.linkRefractionWithTransparency = false;
  36027. _this.useLightmapAsShadowmap = false;
  36028. /**
  36029. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36030. */
  36031. _this.useAlphaFromAlbedoTexture = false;
  36032. /**
  36033. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36034. */
  36035. _this.forceAlphaTest = false;
  36036. /**
  36037. * Defines the alpha limits in alpha test mode.
  36038. */
  36039. _this.alphaCutOff = 0.4;
  36040. /**
  36041. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36042. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36043. */
  36044. _this.useSpecularOverAlpha = true;
  36045. /**
  36046. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36047. */
  36048. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36049. /**
  36050. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36051. */
  36052. _this.useRoughnessFromMetallicTextureAlpha = true;
  36053. /**
  36054. * Specifies if the metallic texture contains the roughness information in its green channel.
  36055. */
  36056. _this.useRoughnessFromMetallicTextureGreen = false;
  36057. /**
  36058. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36059. */
  36060. _this.useMetallnessFromMetallicTextureBlue = false;
  36061. /**
  36062. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36063. */
  36064. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36065. /**
  36066. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36067. */
  36068. _this.useAmbientInGrayScale = false;
  36069. /**
  36070. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36071. * The material will try to infer what glossiness each pixel should be.
  36072. */
  36073. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36074. /**
  36075. * BJS is using an harcoded light falloff based on a manually sets up range.
  36076. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36077. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36078. */
  36079. _this.usePhysicalLightFalloff = true;
  36080. /**
  36081. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36082. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36083. */
  36084. _this.useRadianceOverAlpha = true;
  36085. /**
  36086. * Allows using the bump map in parallax mode.
  36087. */
  36088. _this.useParallax = false;
  36089. /**
  36090. * Allows using the bump map in parallax occlusion mode.
  36091. */
  36092. _this.useParallaxOcclusion = false;
  36093. /**
  36094. * Controls the scale bias of the parallax mode.
  36095. */
  36096. _this.parallaxScaleBias = 0.05;
  36097. /**
  36098. * If sets to true, disables all the lights affecting the material.
  36099. */
  36100. _this.disableLighting = false;
  36101. /**
  36102. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36103. */
  36104. _this.forceIrradianceInFragment = false;
  36105. /**
  36106. * Number of Simultaneous lights allowed on the material.
  36107. */
  36108. _this.maxSimultaneousLights = 4;
  36109. /**
  36110. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36111. */
  36112. _this.invertNormalMapX = false;
  36113. /**
  36114. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36115. */
  36116. _this.invertNormalMapY = false;
  36117. /**
  36118. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36119. */
  36120. _this.twoSidedLighting = false;
  36121. /**
  36122. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36123. * And/Or occlude the blended part.
  36124. */
  36125. _this.useAlphaFresnel = false;
  36126. /**
  36127. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36128. * And/Or occlude the blended part.
  36129. */
  36130. _this.environmentBRDFTexture = null;
  36131. /**
  36132. * Force normal to face away from face.
  36133. * (Temporary internal fix to remove before 3.1)
  36134. */
  36135. _this.forceNormalForward = false;
  36136. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36137. return _this;
  36138. }
  36139. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36140. /**
  36141. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36142. */
  36143. get: function () {
  36144. return this._PBRMATERIAL_OPAQUE;
  36145. },
  36146. enumerable: true,
  36147. configurable: true
  36148. });
  36149. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36150. /**
  36151. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36152. */
  36153. get: function () {
  36154. return this._PBRMATERIAL_ALPHATEST;
  36155. },
  36156. enumerable: true,
  36157. configurable: true
  36158. });
  36159. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36160. /**
  36161. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36162. */
  36163. get: function () {
  36164. return this._PBRMATERIAL_ALPHABLEND;
  36165. },
  36166. enumerable: true,
  36167. configurable: true
  36168. });
  36169. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36170. /**
  36171. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36172. * They are also discarded below the alpha cutoff threshold to improve performances.
  36173. */
  36174. get: function () {
  36175. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36176. },
  36177. enumerable: true,
  36178. configurable: true
  36179. });
  36180. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36181. /**
  36182. * Gets the image processing configuration used either in this material.
  36183. */
  36184. get: function () {
  36185. return this._imageProcessingConfiguration;
  36186. },
  36187. /**
  36188. * Sets the Default image processing configuration used either in the this material.
  36189. *
  36190. * If sets to null, the scene one is in use.
  36191. */
  36192. set: function (value) {
  36193. this._attachImageProcessingConfiguration(value);
  36194. // Ensure the effect will be rebuilt.
  36195. this._markAllSubMeshesAsTexturesDirty();
  36196. },
  36197. enumerable: true,
  36198. configurable: true
  36199. });
  36200. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36201. /**
  36202. * Gets wether the color curves effect is enabled.
  36203. */
  36204. get: function () {
  36205. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36206. },
  36207. /**
  36208. * Sets wether the color curves effect is enabled.
  36209. */
  36210. set: function (value) {
  36211. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36212. },
  36213. enumerable: true,
  36214. configurable: true
  36215. });
  36216. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36217. /**
  36218. * Gets wether the color grading effect is enabled.
  36219. */
  36220. get: function () {
  36221. return this.imageProcessingConfiguration.colorGradingEnabled;
  36222. },
  36223. /**
  36224. * Gets wether the color grading effect is enabled.
  36225. */
  36226. set: function (value) {
  36227. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36228. },
  36229. enumerable: true,
  36230. configurable: true
  36231. });
  36232. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36233. /**
  36234. * Gets wether tonemapping is enabled or not.
  36235. */
  36236. get: function () {
  36237. return this._imageProcessingConfiguration.toneMappingEnabled;
  36238. },
  36239. /**
  36240. * Sets wether tonemapping is enabled or not
  36241. */
  36242. set: function (value) {
  36243. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36244. },
  36245. enumerable: true,
  36246. configurable: true
  36247. });
  36248. ;
  36249. ;
  36250. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36251. /**
  36252. * The camera exposure used on this material.
  36253. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36254. * This corresponds to a photographic exposure.
  36255. */
  36256. get: function () {
  36257. return this._imageProcessingConfiguration.exposure;
  36258. },
  36259. /**
  36260. * The camera exposure used on this material.
  36261. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36262. * This corresponds to a photographic exposure.
  36263. */
  36264. set: function (value) {
  36265. this._imageProcessingConfiguration.exposure = value;
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. ;
  36271. ;
  36272. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36273. /**
  36274. * Gets The camera contrast used on this material.
  36275. */
  36276. get: function () {
  36277. return this._imageProcessingConfiguration.contrast;
  36278. },
  36279. /**
  36280. * Sets The camera contrast used on this material.
  36281. */
  36282. set: function (value) {
  36283. this._imageProcessingConfiguration.contrast = value;
  36284. },
  36285. enumerable: true,
  36286. configurable: true
  36287. });
  36288. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36289. /**
  36290. * Gets the Color Grading 2D Lookup Texture.
  36291. */
  36292. get: function () {
  36293. return this._imageProcessingConfiguration.colorGradingTexture;
  36294. },
  36295. /**
  36296. * Sets the Color Grading 2D Lookup Texture.
  36297. */
  36298. set: function (value) {
  36299. this._imageProcessingConfiguration.colorGradingTexture = value;
  36300. },
  36301. enumerable: true,
  36302. configurable: true
  36303. });
  36304. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36305. /**
  36306. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36307. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36308. * 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;
  36309. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36310. */
  36311. get: function () {
  36312. return this._imageProcessingConfiguration.colorCurves;
  36313. },
  36314. /**
  36315. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36316. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36317. * 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;
  36318. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36319. */
  36320. set: function (value) {
  36321. this._imageProcessingConfiguration.colorCurves = value;
  36322. },
  36323. enumerable: true,
  36324. configurable: true
  36325. });
  36326. PBRMaterial.prototype.getClassName = function () {
  36327. return "PBRMaterial";
  36328. };
  36329. PBRMaterial.prototype.getActiveTextures = function () {
  36330. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36331. if (this._albedoTexture) {
  36332. activeTextures.push(this._albedoTexture);
  36333. }
  36334. if (this._ambientTexture) {
  36335. activeTextures.push(this._ambientTexture);
  36336. }
  36337. if (this._opacityTexture) {
  36338. activeTextures.push(this._opacityTexture);
  36339. }
  36340. if (this._reflectionTexture) {
  36341. activeTextures.push(this._reflectionTexture);
  36342. }
  36343. if (this._emissiveTexture) {
  36344. activeTextures.push(this._emissiveTexture);
  36345. }
  36346. if (this._reflectivityTexture) {
  36347. activeTextures.push(this._reflectivityTexture);
  36348. }
  36349. if (this._metallicTexture) {
  36350. activeTextures.push(this._metallicTexture);
  36351. }
  36352. if (this._microSurfaceTexture) {
  36353. activeTextures.push(this._microSurfaceTexture);
  36354. }
  36355. if (this._bumpTexture) {
  36356. activeTextures.push(this._bumpTexture);
  36357. }
  36358. if (this._lightmapTexture) {
  36359. activeTextures.push(this._lightmapTexture);
  36360. }
  36361. if (this._refractionTexture) {
  36362. activeTextures.push(this._refractionTexture);
  36363. }
  36364. return activeTextures;
  36365. };
  36366. PBRMaterial.prototype.hasTexture = function (texture) {
  36367. if (_super.prototype.hasTexture.call(this, texture)) {
  36368. return true;
  36369. }
  36370. if (this._albedoTexture === texture) {
  36371. return true;
  36372. }
  36373. if (this._ambientTexture === texture) {
  36374. return true;
  36375. }
  36376. if (this._opacityTexture === texture) {
  36377. return true;
  36378. }
  36379. if (this._reflectionTexture === texture) {
  36380. return true;
  36381. }
  36382. if (this._reflectivityTexture === texture) {
  36383. return true;
  36384. }
  36385. if (this._metallicTexture === texture) {
  36386. return true;
  36387. }
  36388. if (this._microSurfaceTexture === texture) {
  36389. return true;
  36390. }
  36391. if (this._bumpTexture === texture) {
  36392. return true;
  36393. }
  36394. if (this._lightmapTexture === texture) {
  36395. return true;
  36396. }
  36397. if (this._refractionTexture === texture) {
  36398. return true;
  36399. }
  36400. return false;
  36401. };
  36402. PBRMaterial.prototype.clone = function (name) {
  36403. var _this = this;
  36404. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36405. clone.id = name;
  36406. clone.name = name;
  36407. return clone;
  36408. };
  36409. PBRMaterial.prototype.serialize = function () {
  36410. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36411. serializationObject.customType = "BABYLON.PBRMaterial";
  36412. return serializationObject;
  36413. };
  36414. // Statics
  36415. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36416. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36417. };
  36418. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36419. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36420. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36421. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36422. __decorate([
  36423. BABYLON.serialize(),
  36424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36425. ], PBRMaterial.prototype, "directIntensity", void 0);
  36426. __decorate([
  36427. BABYLON.serialize(),
  36428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36429. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36430. __decorate([
  36431. BABYLON.serialize(),
  36432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36433. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36434. __decorate([
  36435. BABYLON.serialize(),
  36436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36437. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36438. __decorate([
  36439. BABYLON.serialize(),
  36440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36441. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36442. __decorate([
  36443. BABYLON.serializeAsTexture(),
  36444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36445. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36446. __decorate([
  36447. BABYLON.serializeAsTexture(),
  36448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36449. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36450. __decorate([
  36451. BABYLON.serialize(),
  36452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36453. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36454. __decorate([
  36455. BABYLON.serializeAsTexture(),
  36456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36457. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36458. __decorate([
  36459. BABYLON.serializeAsTexture(),
  36460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36461. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36462. __decorate([
  36463. BABYLON.serializeAsTexture(),
  36464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36465. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36466. __decorate([
  36467. BABYLON.serializeAsTexture(),
  36468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36469. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36470. __decorate([
  36471. BABYLON.serializeAsTexture(),
  36472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36473. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36474. __decorate([
  36475. BABYLON.serialize(),
  36476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36477. ], PBRMaterial.prototype, "metallic", void 0);
  36478. __decorate([
  36479. BABYLON.serialize(),
  36480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36481. ], PBRMaterial.prototype, "roughness", void 0);
  36482. __decorate([
  36483. BABYLON.serializeAsTexture(),
  36484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36485. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36486. __decorate([
  36487. BABYLON.serializeAsTexture(),
  36488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36489. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36490. __decorate([
  36491. BABYLON.serializeAsTexture(),
  36492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36493. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36494. __decorate([
  36495. BABYLON.serializeAsTexture(),
  36496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36497. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36498. __decorate([
  36499. BABYLON.serializeAsColor3("ambient"),
  36500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36501. ], PBRMaterial.prototype, "ambientColor", void 0);
  36502. __decorate([
  36503. BABYLON.serializeAsColor3("albedo"),
  36504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36505. ], PBRMaterial.prototype, "albedoColor", void 0);
  36506. __decorate([
  36507. BABYLON.serializeAsColor3("reflectivity"),
  36508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36509. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36510. __decorate([
  36511. BABYLON.serializeAsColor3("reflection"),
  36512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36513. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36514. __decorate([
  36515. BABYLON.serializeAsColor3("emissive"),
  36516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36517. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36518. __decorate([
  36519. BABYLON.serialize(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36521. ], PBRMaterial.prototype, "microSurface", void 0);
  36522. __decorate([
  36523. BABYLON.serialize(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36525. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36526. __decorate([
  36527. BABYLON.serialize(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36529. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36530. __decorate([
  36531. BABYLON.serialize(),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36533. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36534. __decorate([
  36535. BABYLON.serialize(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36537. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36538. __decorate([
  36539. BABYLON.serialize(),
  36540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36541. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36542. __decorate([
  36543. BABYLON.serialize(),
  36544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36545. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36546. __decorate([
  36547. BABYLON.serialize(),
  36548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36549. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36550. __decorate([
  36551. BABYLON.serialize(),
  36552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36553. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36554. __decorate([
  36555. BABYLON.serialize(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36558. __decorate([
  36559. BABYLON.serialize(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36562. __decorate([
  36563. BABYLON.serialize(),
  36564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36565. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36566. __decorate([
  36567. BABYLON.serialize(),
  36568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36569. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36570. __decorate([
  36571. BABYLON.serialize(),
  36572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36573. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36574. __decorate([
  36575. BABYLON.serialize(),
  36576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36577. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36578. __decorate([
  36579. BABYLON.serialize(),
  36580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36581. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36582. __decorate([
  36583. BABYLON.serialize(),
  36584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36585. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36586. __decorate([
  36587. BABYLON.serialize(),
  36588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36589. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36590. __decorate([
  36591. BABYLON.serialize(),
  36592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36593. ], PBRMaterial.prototype, "useParallax", void 0);
  36594. __decorate([
  36595. BABYLON.serialize(),
  36596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36597. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36598. __decorate([
  36599. BABYLON.serialize(),
  36600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36601. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36602. __decorate([
  36603. BABYLON.serialize(),
  36604. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36605. ], PBRMaterial.prototype, "disableLighting", void 0);
  36606. __decorate([
  36607. BABYLON.serialize(),
  36608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36609. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36610. __decorate([
  36611. BABYLON.serialize(),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36613. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36614. __decorate([
  36615. BABYLON.serialize(),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36617. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36618. __decorate([
  36619. BABYLON.serialize(),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36621. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36622. __decorate([
  36623. BABYLON.serialize(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36625. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36626. __decorate([
  36627. BABYLON.serialize(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36629. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36630. __decorate([
  36631. BABYLON.serializeAsTexture(),
  36632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36633. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36634. __decorate([
  36635. BABYLON.serialize(),
  36636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36637. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36638. return PBRMaterial;
  36639. }(BABYLON.PBRBaseMaterial));
  36640. BABYLON.PBRMaterial = PBRMaterial;
  36641. })(BABYLON || (BABYLON = {}));
  36642. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36643. var BABYLON;
  36644. (function (BABYLON) {
  36645. /**
  36646. * The PBR material of BJS following the metal roughness convention.
  36647. *
  36648. * This fits to the PBR convention in the GLTF definition:
  36649. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36650. */
  36651. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36652. __extends(PBRMetallicRoughnessMaterial, _super);
  36653. /**
  36654. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36655. *
  36656. * @param name The material name
  36657. * @param scene The scene the material will be use in.
  36658. */
  36659. function PBRMetallicRoughnessMaterial(name, scene) {
  36660. var _this = _super.call(this, name, scene) || this;
  36661. _this._useRoughnessFromMetallicTextureAlpha = false;
  36662. _this._useRoughnessFromMetallicTextureGreen = true;
  36663. _this._useMetallnessFromMetallicTextureBlue = true;
  36664. return _this;
  36665. }
  36666. /**
  36667. * Return the currrent class name of the material.
  36668. */
  36669. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36670. return "PBRMetallicRoughnessMaterial";
  36671. };
  36672. /**
  36673. * Return the active textures of the material.
  36674. */
  36675. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36676. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36677. if (this.baseTexture) {
  36678. activeTextures.push(this.baseTexture);
  36679. }
  36680. if (this.metallicRoughnessTexture) {
  36681. activeTextures.push(this.metallicRoughnessTexture);
  36682. }
  36683. return activeTextures;
  36684. };
  36685. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36686. if (_super.prototype.hasTexture.call(this, texture)) {
  36687. return true;
  36688. }
  36689. if (this.baseTexture === texture) {
  36690. return true;
  36691. }
  36692. if (this.metallicRoughnessTexture === texture) {
  36693. return true;
  36694. }
  36695. return false;
  36696. };
  36697. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36698. var _this = this;
  36699. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36700. clone.id = name;
  36701. clone.name = name;
  36702. return clone;
  36703. };
  36704. /**
  36705. * Serialize the material to a parsable JSON object.
  36706. */
  36707. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36709. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36710. return serializationObject;
  36711. };
  36712. /**
  36713. * Parses a JSON object correponding to the serialize function.
  36714. */
  36715. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36716. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36717. };
  36718. __decorate([
  36719. BABYLON.serializeAsColor3(),
  36720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36721. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36722. __decorate([
  36723. BABYLON.serializeAsTexture(),
  36724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36725. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36726. __decorate([
  36727. BABYLON.serialize(),
  36728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36729. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36730. __decorate([
  36731. BABYLON.serialize(),
  36732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36733. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36734. __decorate([
  36735. BABYLON.serializeAsTexture(),
  36736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36737. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36738. return PBRMetallicRoughnessMaterial;
  36739. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36740. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36741. })(BABYLON || (BABYLON = {}));
  36742. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36743. var BABYLON;
  36744. (function (BABYLON) {
  36745. /**
  36746. * The PBR material of BJS following the specular glossiness convention.
  36747. *
  36748. * This fits to the PBR convention in the GLTF definition:
  36749. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36750. */
  36751. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36752. __extends(PBRSpecularGlossinessMaterial, _super);
  36753. /**
  36754. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36755. *
  36756. * @param name The material name
  36757. * @param scene The scene the material will be use in.
  36758. */
  36759. function PBRSpecularGlossinessMaterial(name, scene) {
  36760. var _this = _super.call(this, name, scene) || this;
  36761. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36762. return _this;
  36763. }
  36764. /**
  36765. * Return the currrent class name of the material.
  36766. */
  36767. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36768. return "PBRSpecularGlossinessMaterial";
  36769. };
  36770. /**
  36771. * Return the active textures of the material.
  36772. */
  36773. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36774. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36775. if (this.diffuseTexture) {
  36776. activeTextures.push(this.diffuseTexture);
  36777. }
  36778. if (this.specularGlossinessTexture) {
  36779. activeTextures.push(this.specularGlossinessTexture);
  36780. }
  36781. return activeTextures;
  36782. };
  36783. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36784. if (_super.prototype.hasTexture.call(this, texture)) {
  36785. return true;
  36786. }
  36787. if (this.diffuseTexture === texture) {
  36788. return true;
  36789. }
  36790. if (this.specularGlossinessTexture === texture) {
  36791. return true;
  36792. }
  36793. return false;
  36794. };
  36795. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36796. var _this = this;
  36797. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36798. clone.id = name;
  36799. clone.name = name;
  36800. return clone;
  36801. };
  36802. /**
  36803. * Serialize the material to a parsable JSON object.
  36804. */
  36805. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36807. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36808. return serializationObject;
  36809. };
  36810. /**
  36811. * Parses a JSON object correponding to the serialize function.
  36812. */
  36813. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36814. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36815. };
  36816. __decorate([
  36817. BABYLON.serializeAsColor3("diffuse"),
  36818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36819. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36820. __decorate([
  36821. BABYLON.serializeAsTexture(),
  36822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36823. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36824. __decorate([
  36825. BABYLON.serializeAsColor3("specular"),
  36826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36827. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36828. __decorate([
  36829. BABYLON.serialize(),
  36830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36831. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36832. __decorate([
  36833. BABYLON.serializeAsTexture(),
  36834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36835. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36836. return PBRSpecularGlossinessMaterial;
  36837. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36838. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36839. })(BABYLON || (BABYLON = {}));
  36840. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36841. var BABYLON;
  36842. (function (BABYLON) {
  36843. BABYLON.CameraInputTypes = {};
  36844. var CameraInputsManager = /** @class */ (function () {
  36845. function CameraInputsManager(camera) {
  36846. this.attached = {};
  36847. this.camera = camera;
  36848. this.checkInputs = function () { };
  36849. }
  36850. CameraInputsManager.prototype.add = function (input) {
  36851. var type = input.getSimpleName();
  36852. if (this.attached[type]) {
  36853. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36854. return;
  36855. }
  36856. this.attached[type] = input;
  36857. input.camera = this.camera;
  36858. //for checkInputs, we are dynamically creating a function
  36859. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36860. if (input.checkInputs) {
  36861. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36862. }
  36863. if (this.attachedElement) {
  36864. input.attachControl(this.attachedElement);
  36865. }
  36866. };
  36867. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36868. for (var cam in this.attached) {
  36869. var input = this.attached[cam];
  36870. if (input === inputToRemove) {
  36871. input.detachControl(this.attachedElement);
  36872. input.camera = null;
  36873. delete this.attached[cam];
  36874. this.rebuildInputCheck();
  36875. }
  36876. }
  36877. };
  36878. CameraInputsManager.prototype.removeByType = function (inputType) {
  36879. for (var cam in this.attached) {
  36880. var input = this.attached[cam];
  36881. if (input.getClassName() === inputType) {
  36882. input.detachControl(this.attachedElement);
  36883. input.camera = null;
  36884. delete this.attached[cam];
  36885. this.rebuildInputCheck();
  36886. }
  36887. }
  36888. };
  36889. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36890. var current = this.checkInputs;
  36891. return function () {
  36892. current();
  36893. fn();
  36894. };
  36895. };
  36896. CameraInputsManager.prototype.attachInput = function (input) {
  36897. if (this.attachedElement) {
  36898. input.attachControl(this.attachedElement, this.noPreventDefault);
  36899. }
  36900. };
  36901. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36902. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36903. if (this.attachedElement) {
  36904. return;
  36905. }
  36906. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36907. this.attachedElement = element;
  36908. this.noPreventDefault = noPreventDefault;
  36909. for (var cam in this.attached) {
  36910. this.attached[cam].attachControl(element, noPreventDefault);
  36911. }
  36912. };
  36913. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36914. if (disconnect === void 0) { disconnect = false; }
  36915. if (this.attachedElement !== element) {
  36916. return;
  36917. }
  36918. for (var cam in this.attached) {
  36919. this.attached[cam].detachControl(element);
  36920. if (disconnect) {
  36921. this.attached[cam].camera = null;
  36922. }
  36923. }
  36924. this.attachedElement = null;
  36925. };
  36926. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36927. this.checkInputs = function () { };
  36928. for (var cam in this.attached) {
  36929. var input = this.attached[cam];
  36930. if (input.checkInputs) {
  36931. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36932. }
  36933. }
  36934. };
  36935. CameraInputsManager.prototype.clear = function () {
  36936. if (this.attachedElement) {
  36937. this.detachElement(this.attachedElement, true);
  36938. }
  36939. this.attached = {};
  36940. this.attachedElement = null;
  36941. this.checkInputs = function () { };
  36942. };
  36943. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36944. var inputs = {};
  36945. for (var cam in this.attached) {
  36946. var input = this.attached[cam];
  36947. var res = BABYLON.SerializationHelper.Serialize(input);
  36948. inputs[input.getClassName()] = res;
  36949. }
  36950. serializedCamera.inputsmgr = inputs;
  36951. };
  36952. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36953. var parsedInputs = parsedCamera.inputsmgr;
  36954. if (parsedInputs) {
  36955. this.clear();
  36956. for (var n in parsedInputs) {
  36957. var construct = BABYLON.CameraInputTypes[n];
  36958. if (construct) {
  36959. var parsedinput = parsedInputs[n];
  36960. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36961. this.add(input);
  36962. }
  36963. }
  36964. }
  36965. else {
  36966. //2016-03-08 this part is for managing backward compatibility
  36967. for (var n in this.attached) {
  36968. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36969. if (construct) {
  36970. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36971. this.remove(this.attached[n]);
  36972. this.add(input);
  36973. }
  36974. }
  36975. }
  36976. };
  36977. return CameraInputsManager;
  36978. }());
  36979. BABYLON.CameraInputsManager = CameraInputsManager;
  36980. })(BABYLON || (BABYLON = {}));
  36981. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36982. var BABYLON;
  36983. (function (BABYLON) {
  36984. var FreeCameraMouseInput = /** @class */ (function () {
  36985. function FreeCameraMouseInput(touchEnabled) {
  36986. if (touchEnabled === void 0) { touchEnabled = true; }
  36987. this.touchEnabled = touchEnabled;
  36988. this.buttons = [0, 1, 2];
  36989. this.angularSensibility = 2000.0;
  36990. this.previousPosition = null;
  36991. }
  36992. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36993. var _this = this;
  36994. var engine = this.camera.getEngine();
  36995. if (!this._pointerInput) {
  36996. this._pointerInput = function (p, s) {
  36997. var evt = p.event;
  36998. if (engine.isInVRExclusivePointerMode) {
  36999. return;
  37000. }
  37001. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37002. return;
  37003. }
  37004. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37005. return;
  37006. }
  37007. var srcElement = (evt.srcElement || evt.target);
  37008. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37009. try {
  37010. srcElement.setPointerCapture(evt.pointerId);
  37011. }
  37012. catch (e) {
  37013. //Nothing to do with the error. Execution will continue.
  37014. }
  37015. _this.previousPosition = {
  37016. x: evt.clientX,
  37017. y: evt.clientY
  37018. };
  37019. if (!noPreventDefault) {
  37020. evt.preventDefault();
  37021. element.focus();
  37022. }
  37023. }
  37024. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37025. try {
  37026. srcElement.releasePointerCapture(evt.pointerId);
  37027. }
  37028. catch (e) {
  37029. //Nothing to do with the error.
  37030. }
  37031. _this.previousPosition = null;
  37032. if (!noPreventDefault) {
  37033. evt.preventDefault();
  37034. }
  37035. }
  37036. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37037. if (!_this.previousPosition || engine.isPointerLock) {
  37038. return;
  37039. }
  37040. var offsetX = evt.clientX - _this.previousPosition.x;
  37041. var offsetY = evt.clientY - _this.previousPosition.y;
  37042. if (_this.camera.getScene().useRightHandedSystem) {
  37043. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37044. }
  37045. else {
  37046. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37047. }
  37048. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37049. _this.previousPosition = {
  37050. x: evt.clientX,
  37051. y: evt.clientY
  37052. };
  37053. if (!noPreventDefault) {
  37054. evt.preventDefault();
  37055. }
  37056. }
  37057. };
  37058. }
  37059. this._onMouseMove = function (evt) {
  37060. if (!engine.isPointerLock) {
  37061. return;
  37062. }
  37063. if (engine.isInVRExclusivePointerMode) {
  37064. return;
  37065. }
  37066. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37067. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37068. if (_this.camera.getScene().useRightHandedSystem) {
  37069. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37070. }
  37071. else {
  37072. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37073. }
  37074. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37075. _this.previousPosition = null;
  37076. if (!noPreventDefault) {
  37077. evt.preventDefault();
  37078. }
  37079. };
  37080. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37081. element.addEventListener("mousemove", this._onMouseMove, false);
  37082. };
  37083. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37084. if (this._observer && element) {
  37085. this.camera.getScene().onPointerObservable.remove(this._observer);
  37086. if (this._onMouseMove) {
  37087. element.removeEventListener("mousemove", this._onMouseMove);
  37088. }
  37089. this._observer = null;
  37090. this._onMouseMove = null;
  37091. this.previousPosition = null;
  37092. }
  37093. };
  37094. FreeCameraMouseInput.prototype.getClassName = function () {
  37095. return "FreeCameraMouseInput";
  37096. };
  37097. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37098. return "mouse";
  37099. };
  37100. __decorate([
  37101. BABYLON.serialize()
  37102. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37103. __decorate([
  37104. BABYLON.serialize()
  37105. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37106. return FreeCameraMouseInput;
  37107. }());
  37108. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37109. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37110. })(BABYLON || (BABYLON = {}));
  37111. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37112. var BABYLON;
  37113. (function (BABYLON) {
  37114. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37115. function FreeCameraKeyboardMoveInput() {
  37116. this._keys = new Array();
  37117. this.keysUp = [38];
  37118. this.keysDown = [40];
  37119. this.keysLeft = [37];
  37120. this.keysRight = [39];
  37121. }
  37122. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37123. var _this = this;
  37124. if (this._onCanvasBlurObserver) {
  37125. return;
  37126. }
  37127. this._scene = this.camera.getScene();
  37128. this._engine = this._scene.getEngine();
  37129. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37130. _this._keys = [];
  37131. });
  37132. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37133. var evt = info.event;
  37134. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37135. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37136. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37137. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37138. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37139. var index = _this._keys.indexOf(evt.keyCode);
  37140. if (index === -1) {
  37141. _this._keys.push(evt.keyCode);
  37142. }
  37143. if (!noPreventDefault) {
  37144. evt.preventDefault();
  37145. }
  37146. }
  37147. }
  37148. else {
  37149. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37150. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37151. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37152. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37153. var index = _this._keys.indexOf(evt.keyCode);
  37154. if (index >= 0) {
  37155. _this._keys.splice(index, 1);
  37156. }
  37157. if (!noPreventDefault) {
  37158. evt.preventDefault();
  37159. }
  37160. }
  37161. }
  37162. });
  37163. };
  37164. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37165. if (this._scene) {
  37166. if (this._onKeyboardObserver) {
  37167. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37168. }
  37169. if (this._onCanvasBlurObserver) {
  37170. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37171. }
  37172. this._onKeyboardObserver = null;
  37173. this._onCanvasBlurObserver = null;
  37174. }
  37175. this._keys = [];
  37176. };
  37177. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37178. if (this._onKeyboardObserver) {
  37179. var camera = this.camera;
  37180. // Keyboard
  37181. for (var index = 0; index < this._keys.length; index++) {
  37182. var keyCode = this._keys[index];
  37183. var speed = camera._computeLocalCameraSpeed();
  37184. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37185. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37186. }
  37187. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37188. camera._localDirection.copyFromFloats(0, 0, speed);
  37189. }
  37190. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37191. camera._localDirection.copyFromFloats(speed, 0, 0);
  37192. }
  37193. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37194. camera._localDirection.copyFromFloats(0, 0, -speed);
  37195. }
  37196. if (camera.getScene().useRightHandedSystem) {
  37197. camera._localDirection.z *= -1;
  37198. }
  37199. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37200. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37201. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37202. }
  37203. }
  37204. };
  37205. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37206. return "FreeCameraKeyboardMoveInput";
  37207. };
  37208. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37209. this._keys = [];
  37210. };
  37211. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37212. return "keyboard";
  37213. };
  37214. __decorate([
  37215. BABYLON.serialize()
  37216. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37217. __decorate([
  37218. BABYLON.serialize()
  37219. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37220. __decorate([
  37221. BABYLON.serialize()
  37222. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37223. __decorate([
  37224. BABYLON.serialize()
  37225. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37226. return FreeCameraKeyboardMoveInput;
  37227. }());
  37228. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37229. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37230. })(BABYLON || (BABYLON = {}));
  37231. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37232. var BABYLON;
  37233. (function (BABYLON) {
  37234. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37235. __extends(FreeCameraInputsManager, _super);
  37236. function FreeCameraInputsManager(camera) {
  37237. return _super.call(this, camera) || this;
  37238. }
  37239. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37240. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37241. return this;
  37242. };
  37243. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37244. if (touchEnabled === void 0) { touchEnabled = true; }
  37245. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37246. return this;
  37247. };
  37248. FreeCameraInputsManager.prototype.addGamepad = function () {
  37249. this.add(new BABYLON.FreeCameraGamepadInput());
  37250. return this;
  37251. };
  37252. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37253. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37254. return this;
  37255. };
  37256. FreeCameraInputsManager.prototype.addTouch = function () {
  37257. this.add(new BABYLON.FreeCameraTouchInput());
  37258. return this;
  37259. };
  37260. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37261. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37262. return this;
  37263. };
  37264. return FreeCameraInputsManager;
  37265. }(BABYLON.CameraInputsManager));
  37266. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37267. })(BABYLON || (BABYLON = {}));
  37268. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37269. var BABYLON;
  37270. (function (BABYLON) {
  37271. var TargetCamera = /** @class */ (function (_super) {
  37272. __extends(TargetCamera, _super);
  37273. function TargetCamera(name, position, scene) {
  37274. var _this = _super.call(this, name, position, scene) || this;
  37275. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37276. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37277. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37278. _this.speed = 2.0;
  37279. _this.noRotationConstraint = false;
  37280. _this.lockedTarget = null;
  37281. _this._currentTarget = BABYLON.Vector3.Zero();
  37282. _this._viewMatrix = BABYLON.Matrix.Zero();
  37283. _this._camMatrix = BABYLON.Matrix.Zero();
  37284. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37285. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37286. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37287. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37288. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37289. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37290. _this._tempMatrix = BABYLON.Matrix.Zero();
  37291. return _this;
  37292. }
  37293. TargetCamera.prototype.getFrontPosition = function (distance) {
  37294. var direction = this.getTarget().subtract(this.position);
  37295. direction.normalize();
  37296. direction.scaleInPlace(distance);
  37297. return this.globalPosition.add(direction);
  37298. };
  37299. TargetCamera.prototype._getLockedTargetPosition = function () {
  37300. if (!this.lockedTarget) {
  37301. return null;
  37302. }
  37303. if (this.lockedTarget.absolutePosition) {
  37304. this.lockedTarget.computeWorldMatrix();
  37305. }
  37306. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37307. };
  37308. TargetCamera.prototype.storeState = function () {
  37309. this._storedPosition = this.position.clone();
  37310. this._storedRotation = this.rotation.clone();
  37311. if (this.rotationQuaternion) {
  37312. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37313. }
  37314. return _super.prototype.storeState.call(this);
  37315. };
  37316. /**
  37317. * Restored camera state. You must call storeState() first
  37318. */
  37319. TargetCamera.prototype._restoreStateValues = function () {
  37320. if (!_super.prototype._restoreStateValues.call(this)) {
  37321. return false;
  37322. }
  37323. this.position = this._storedPosition.clone();
  37324. this.rotation = this._storedRotation.clone();
  37325. if (this.rotationQuaternion) {
  37326. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37327. }
  37328. this.cameraDirection.copyFromFloats(0, 0, 0);
  37329. this.cameraRotation.copyFromFloats(0, 0);
  37330. return true;
  37331. };
  37332. // Cache
  37333. TargetCamera.prototype._initCache = function () {
  37334. _super.prototype._initCache.call(this);
  37335. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37336. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37337. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37338. };
  37339. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37340. if (!ignoreParentClass) {
  37341. _super.prototype._updateCache.call(this);
  37342. }
  37343. var lockedTargetPosition = this._getLockedTargetPosition();
  37344. if (!lockedTargetPosition) {
  37345. this._cache.lockedTarget = null;
  37346. }
  37347. else {
  37348. if (!this._cache.lockedTarget) {
  37349. this._cache.lockedTarget = lockedTargetPosition.clone();
  37350. }
  37351. else {
  37352. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37353. }
  37354. }
  37355. this._cache.rotation.copyFrom(this.rotation);
  37356. if (this.rotationQuaternion)
  37357. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37358. };
  37359. // Synchronized
  37360. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37361. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37362. return false;
  37363. }
  37364. var lockedTargetPosition = this._getLockedTargetPosition();
  37365. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37366. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37367. };
  37368. // Methods
  37369. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37370. var engine = this.getEngine();
  37371. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37372. };
  37373. // Target
  37374. TargetCamera.prototype.setTarget = function (target) {
  37375. this.upVector.normalize();
  37376. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37377. this._camMatrix.invert();
  37378. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37379. var vDir = target.subtract(this.position);
  37380. if (vDir.x >= 0.0) {
  37381. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37382. }
  37383. else {
  37384. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37385. }
  37386. this.rotation.z = 0;
  37387. if (isNaN(this.rotation.x)) {
  37388. this.rotation.x = 0;
  37389. }
  37390. if (isNaN(this.rotation.y)) {
  37391. this.rotation.y = 0;
  37392. }
  37393. if (isNaN(this.rotation.z)) {
  37394. this.rotation.z = 0;
  37395. }
  37396. if (this.rotationQuaternion) {
  37397. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37398. }
  37399. };
  37400. /**
  37401. * Return the current target position of the camera. This value is expressed in local space.
  37402. */
  37403. TargetCamera.prototype.getTarget = function () {
  37404. return this._currentTarget;
  37405. };
  37406. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37407. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37408. };
  37409. TargetCamera.prototype._updatePosition = function () {
  37410. if (this.parent) {
  37411. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37412. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37413. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37414. return;
  37415. }
  37416. this.position.addInPlace(this.cameraDirection);
  37417. };
  37418. TargetCamera.prototype._checkInputs = function () {
  37419. var needToMove = this._decideIfNeedsToMove();
  37420. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37421. // Move
  37422. if (needToMove) {
  37423. this._updatePosition();
  37424. }
  37425. // Rotate
  37426. if (needToRotate) {
  37427. this.rotation.x += this.cameraRotation.x;
  37428. this.rotation.y += this.cameraRotation.y;
  37429. //rotate, if quaternion is set and rotation was used
  37430. if (this.rotationQuaternion) {
  37431. var len = this.rotation.lengthSquared();
  37432. if (len) {
  37433. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37434. }
  37435. }
  37436. if (!this.noRotationConstraint) {
  37437. var limit = (Math.PI / 2) * 0.95;
  37438. if (this.rotation.x > limit)
  37439. this.rotation.x = limit;
  37440. if (this.rotation.x < -limit)
  37441. this.rotation.x = -limit;
  37442. }
  37443. }
  37444. // Inertia
  37445. if (needToMove) {
  37446. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37447. this.cameraDirection.x = 0;
  37448. }
  37449. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37450. this.cameraDirection.y = 0;
  37451. }
  37452. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37453. this.cameraDirection.z = 0;
  37454. }
  37455. this.cameraDirection.scaleInPlace(this.inertia);
  37456. }
  37457. if (needToRotate) {
  37458. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37459. this.cameraRotation.x = 0;
  37460. }
  37461. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37462. this.cameraRotation.y = 0;
  37463. }
  37464. this.cameraRotation.scaleInPlace(this.inertia);
  37465. }
  37466. _super.prototype._checkInputs.call(this);
  37467. };
  37468. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37469. if (this.rotationQuaternion) {
  37470. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37471. }
  37472. else {
  37473. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37474. }
  37475. //update the up vector!
  37476. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37477. };
  37478. TargetCamera.prototype._getViewMatrix = function () {
  37479. if (!this.lockedTarget) {
  37480. // Compute
  37481. this._updateCameraRotationMatrix();
  37482. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37483. // Computing target and final matrix
  37484. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37485. }
  37486. else {
  37487. var targetPosition = this._getLockedTargetPosition();
  37488. if (targetPosition) {
  37489. this._currentTarget.copyFrom(targetPosition);
  37490. }
  37491. }
  37492. if (this.getScene().useRightHandedSystem) {
  37493. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37494. }
  37495. else {
  37496. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37497. }
  37498. return this._viewMatrix;
  37499. };
  37500. /**
  37501. * @override
  37502. * Override Camera.createRigCamera
  37503. */
  37504. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37505. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37506. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37507. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37508. if (!this.rotationQuaternion) {
  37509. this.rotationQuaternion = new BABYLON.Quaternion();
  37510. }
  37511. rigCamera._cameraRigParams = {};
  37512. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37513. }
  37514. return rigCamera;
  37515. }
  37516. return null;
  37517. };
  37518. /**
  37519. * @override
  37520. * Override Camera._updateRigCameras
  37521. */
  37522. TargetCamera.prototype._updateRigCameras = function () {
  37523. var camLeft = this._rigCameras[0];
  37524. var camRight = this._rigCameras[1];
  37525. switch (this.cameraRigMode) {
  37526. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37530. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37531. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37532. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37533. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37534. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37535. camLeft.setTarget(this.getTarget());
  37536. camRight.setTarget(this.getTarget());
  37537. break;
  37538. case BABYLON.Camera.RIG_MODE_VR:
  37539. if (camLeft.rotationQuaternion) {
  37540. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37541. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37542. }
  37543. else {
  37544. camLeft.rotation.copyFrom(this.rotation);
  37545. camRight.rotation.copyFrom(this.rotation);
  37546. }
  37547. camLeft.position.copyFrom(this.position);
  37548. camRight.position.copyFrom(this.position);
  37549. break;
  37550. }
  37551. _super.prototype._updateRigCameras.call(this);
  37552. };
  37553. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37554. if (!this._rigCamTransformMatrix) {
  37555. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37556. }
  37557. var target = this.getTarget();
  37558. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37559. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37560. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37561. };
  37562. TargetCamera.prototype.getClassName = function () {
  37563. return "TargetCamera";
  37564. };
  37565. __decorate([
  37566. BABYLON.serializeAsVector3()
  37567. ], TargetCamera.prototype, "rotation", void 0);
  37568. __decorate([
  37569. BABYLON.serialize()
  37570. ], TargetCamera.prototype, "speed", void 0);
  37571. __decorate([
  37572. BABYLON.serializeAsMeshReference("lockedTargetId")
  37573. ], TargetCamera.prototype, "lockedTarget", void 0);
  37574. return TargetCamera;
  37575. }(BABYLON.Camera));
  37576. BABYLON.TargetCamera = TargetCamera;
  37577. })(BABYLON || (BABYLON = {}));
  37578. //# sourceMappingURL=babylon.targetCamera.js.map
  37579. var BABYLON;
  37580. (function (BABYLON) {
  37581. var FreeCamera = /** @class */ (function (_super) {
  37582. __extends(FreeCamera, _super);
  37583. function FreeCamera(name, position, scene) {
  37584. var _this = _super.call(this, name, position, scene) || this;
  37585. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37586. _this.checkCollisions = false;
  37587. _this.applyGravity = false;
  37588. _this._needMoveForGravity = false;
  37589. _this._oldPosition = BABYLON.Vector3.Zero();
  37590. _this._diffPosition = BABYLON.Vector3.Zero();
  37591. _this._newPosition = BABYLON.Vector3.Zero();
  37592. // Collisions
  37593. _this._collisionMask = -1;
  37594. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37595. if (collidedMesh === void 0) { collidedMesh = null; }
  37596. //TODO move this to the collision coordinator!
  37597. if (_this.getScene().workerCollisions)
  37598. newPosition.multiplyInPlace(_this._collider.radius);
  37599. var updatePosition = function (newPos) {
  37600. _this._newPosition.copyFrom(newPos);
  37601. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37602. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37603. _this.position.addInPlace(_this._diffPosition);
  37604. if (_this.onCollide && collidedMesh) {
  37605. _this.onCollide(collidedMesh);
  37606. }
  37607. }
  37608. };
  37609. updatePosition(newPosition);
  37610. };
  37611. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37612. _this.inputs.addKeyboard().addMouse();
  37613. return _this;
  37614. }
  37615. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37616. //-- begin properties for backward compatibility for inputs
  37617. get: function () {
  37618. var mouse = this.inputs.attached["mouse"];
  37619. if (mouse)
  37620. return mouse.angularSensibility;
  37621. return 0;
  37622. },
  37623. set: function (value) {
  37624. var mouse = this.inputs.attached["mouse"];
  37625. if (mouse)
  37626. mouse.angularSensibility = value;
  37627. },
  37628. enumerable: true,
  37629. configurable: true
  37630. });
  37631. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37632. get: function () {
  37633. var keyboard = this.inputs.attached["keyboard"];
  37634. if (keyboard)
  37635. return keyboard.keysUp;
  37636. return [];
  37637. },
  37638. set: function (value) {
  37639. var keyboard = this.inputs.attached["keyboard"];
  37640. if (keyboard)
  37641. keyboard.keysUp = value;
  37642. },
  37643. enumerable: true,
  37644. configurable: true
  37645. });
  37646. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37647. get: function () {
  37648. var keyboard = this.inputs.attached["keyboard"];
  37649. if (keyboard)
  37650. return keyboard.keysDown;
  37651. return [];
  37652. },
  37653. set: function (value) {
  37654. var keyboard = this.inputs.attached["keyboard"];
  37655. if (keyboard)
  37656. keyboard.keysDown = value;
  37657. },
  37658. enumerable: true,
  37659. configurable: true
  37660. });
  37661. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37662. get: function () {
  37663. var keyboard = this.inputs.attached["keyboard"];
  37664. if (keyboard)
  37665. return keyboard.keysLeft;
  37666. return [];
  37667. },
  37668. set: function (value) {
  37669. var keyboard = this.inputs.attached["keyboard"];
  37670. if (keyboard)
  37671. keyboard.keysLeft = value;
  37672. },
  37673. enumerable: true,
  37674. configurable: true
  37675. });
  37676. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37677. get: function () {
  37678. var keyboard = this.inputs.attached["keyboard"];
  37679. if (keyboard)
  37680. return keyboard.keysRight;
  37681. return [];
  37682. },
  37683. set: function (value) {
  37684. var keyboard = this.inputs.attached["keyboard"];
  37685. if (keyboard)
  37686. keyboard.keysRight = value;
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. // Controls
  37692. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37693. this.inputs.attachElement(element, noPreventDefault);
  37694. };
  37695. FreeCamera.prototype.detachControl = function (element) {
  37696. this.inputs.detachElement(element);
  37697. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37698. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37699. };
  37700. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37701. get: function () {
  37702. return this._collisionMask;
  37703. },
  37704. set: function (mask) {
  37705. this._collisionMask = !isNaN(mask) ? mask : -1;
  37706. },
  37707. enumerable: true,
  37708. configurable: true
  37709. });
  37710. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37711. var globalPosition;
  37712. if (this.parent) {
  37713. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37714. }
  37715. else {
  37716. globalPosition = this.position;
  37717. }
  37718. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37719. if (!this._collider) {
  37720. this._collider = new BABYLON.Collider();
  37721. }
  37722. this._collider.radius = this.ellipsoid;
  37723. this._collider.collisionMask = this._collisionMask;
  37724. //no need for clone, as long as gravity is not on.
  37725. var actualDisplacement = displacement;
  37726. //add gravity to the direction to prevent the dual-collision checking
  37727. if (this.applyGravity) {
  37728. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37729. actualDisplacement = displacement.add(this.getScene().gravity);
  37730. }
  37731. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37732. };
  37733. FreeCamera.prototype._checkInputs = function () {
  37734. if (!this._localDirection) {
  37735. this._localDirection = BABYLON.Vector3.Zero();
  37736. this._transformedDirection = BABYLON.Vector3.Zero();
  37737. }
  37738. this.inputs.checkInputs();
  37739. _super.prototype._checkInputs.call(this);
  37740. };
  37741. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37742. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37743. };
  37744. FreeCamera.prototype._updatePosition = function () {
  37745. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37746. this._collideWithWorld(this.cameraDirection);
  37747. }
  37748. else {
  37749. _super.prototype._updatePosition.call(this);
  37750. }
  37751. };
  37752. FreeCamera.prototype.dispose = function () {
  37753. this.inputs.clear();
  37754. _super.prototype.dispose.call(this);
  37755. };
  37756. FreeCamera.prototype.getClassName = function () {
  37757. return "FreeCamera";
  37758. };
  37759. __decorate([
  37760. BABYLON.serializeAsVector3()
  37761. ], FreeCamera.prototype, "ellipsoid", void 0);
  37762. __decorate([
  37763. BABYLON.serialize()
  37764. ], FreeCamera.prototype, "checkCollisions", void 0);
  37765. __decorate([
  37766. BABYLON.serialize()
  37767. ], FreeCamera.prototype, "applyGravity", void 0);
  37768. return FreeCamera;
  37769. }(BABYLON.TargetCamera));
  37770. BABYLON.FreeCamera = FreeCamera;
  37771. })(BABYLON || (BABYLON = {}));
  37772. //# sourceMappingURL=babylon.freeCamera.js.map
  37773. var BABYLON;
  37774. (function (BABYLON) {
  37775. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37776. function ArcRotateCameraKeyboardMoveInput() {
  37777. this._keys = new Array();
  37778. this.keysUp = [38];
  37779. this.keysDown = [40];
  37780. this.keysLeft = [37];
  37781. this.keysRight = [39];
  37782. this.keysReset = [220];
  37783. this.panningSensibility = 50.0;
  37784. this.zoomingSensibility = 25.0;
  37785. this.useAltToZoom = true;
  37786. }
  37787. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37788. var _this = this;
  37789. if (this._onCanvasBlurObserver) {
  37790. return;
  37791. }
  37792. this._scene = this.camera.getScene();
  37793. this._engine = this._scene.getEngine();
  37794. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37795. _this._keys = [];
  37796. });
  37797. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37798. var evt = info.event;
  37799. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37800. _this._ctrlPressed = evt.ctrlKey;
  37801. _this._altPressed = evt.altKey;
  37802. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37803. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37804. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37805. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37806. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37807. var index = _this._keys.indexOf(evt.keyCode);
  37808. if (index === -1) {
  37809. _this._keys.push(evt.keyCode);
  37810. }
  37811. if (evt.preventDefault) {
  37812. if (!noPreventDefault) {
  37813. evt.preventDefault();
  37814. }
  37815. }
  37816. }
  37817. }
  37818. else {
  37819. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37820. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37821. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37822. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37823. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37824. var index = _this._keys.indexOf(evt.keyCode);
  37825. if (index >= 0) {
  37826. _this._keys.splice(index, 1);
  37827. }
  37828. if (evt.preventDefault) {
  37829. if (!noPreventDefault) {
  37830. evt.preventDefault();
  37831. }
  37832. }
  37833. }
  37834. }
  37835. });
  37836. };
  37837. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37838. if (this._scene) {
  37839. if (this._onKeyboardObserver) {
  37840. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37841. }
  37842. if (this._onCanvasBlurObserver) {
  37843. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37844. }
  37845. this._onKeyboardObserver = null;
  37846. this._onCanvasBlurObserver = null;
  37847. }
  37848. this._keys = [];
  37849. };
  37850. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37851. if (this._onKeyboardObserver) {
  37852. var camera = this.camera;
  37853. for (var index = 0; index < this._keys.length; index++) {
  37854. var keyCode = this._keys[index];
  37855. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37856. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37857. camera.inertialPanningX -= 1 / this.panningSensibility;
  37858. }
  37859. else {
  37860. camera.inertialAlphaOffset -= 0.01;
  37861. }
  37862. }
  37863. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37864. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37865. camera.inertialPanningY += 1 / this.panningSensibility;
  37866. }
  37867. else if (this._altPressed && this.useAltToZoom) {
  37868. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37869. }
  37870. else {
  37871. camera.inertialBetaOffset -= 0.01;
  37872. }
  37873. }
  37874. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37875. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37876. camera.inertialPanningX += 1 / this.panningSensibility;
  37877. }
  37878. else {
  37879. camera.inertialAlphaOffset += 0.01;
  37880. }
  37881. }
  37882. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37883. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37884. camera.inertialPanningY -= 1 / this.panningSensibility;
  37885. }
  37886. else if (this._altPressed && this.useAltToZoom) {
  37887. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37888. }
  37889. else {
  37890. camera.inertialBetaOffset += 0.01;
  37891. }
  37892. }
  37893. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37894. camera.restoreState();
  37895. }
  37896. }
  37897. }
  37898. };
  37899. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37900. return "ArcRotateCameraKeyboardMoveInput";
  37901. };
  37902. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37903. return "keyboard";
  37904. };
  37905. __decorate([
  37906. BABYLON.serialize()
  37907. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37908. __decorate([
  37909. BABYLON.serialize()
  37910. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37911. __decorate([
  37912. BABYLON.serialize()
  37913. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37914. __decorate([
  37915. BABYLON.serialize()
  37916. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37917. __decorate([
  37918. BABYLON.serialize()
  37919. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37920. __decorate([
  37921. BABYLON.serialize()
  37922. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37923. __decorate([
  37924. BABYLON.serialize()
  37925. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37926. __decorate([
  37927. BABYLON.serialize()
  37928. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37929. return ArcRotateCameraKeyboardMoveInput;
  37930. }());
  37931. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37932. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37933. })(BABYLON || (BABYLON = {}));
  37934. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37935. var BABYLON;
  37936. (function (BABYLON) {
  37937. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37938. function ArcRotateCameraMouseWheelInput() {
  37939. this.wheelPrecision = 3.0;
  37940. /**
  37941. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37942. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37943. */
  37944. this.wheelDeltaPercentage = 0;
  37945. }
  37946. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37947. var _this = this;
  37948. this._wheel = function (p, s) {
  37949. //sanity check - this should be a PointerWheel event.
  37950. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37951. return;
  37952. var event = p.event;
  37953. var delta = 0;
  37954. if (event.wheelDelta) {
  37955. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37956. }
  37957. else if (event.detail) {
  37958. delta = -event.detail / _this.wheelPrecision;
  37959. }
  37960. if (delta)
  37961. _this.camera.inertialRadiusOffset += delta;
  37962. if (event.preventDefault) {
  37963. if (!noPreventDefault) {
  37964. event.preventDefault();
  37965. }
  37966. }
  37967. };
  37968. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37969. };
  37970. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37971. if (this._observer && element) {
  37972. this.camera.getScene().onPointerObservable.remove(this._observer);
  37973. this._observer = null;
  37974. this._wheel = null;
  37975. }
  37976. };
  37977. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37978. return "ArcRotateCameraMouseWheelInput";
  37979. };
  37980. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37981. return "mousewheel";
  37982. };
  37983. __decorate([
  37984. BABYLON.serialize()
  37985. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37986. __decorate([
  37987. BABYLON.serialize()
  37988. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37989. return ArcRotateCameraMouseWheelInput;
  37990. }());
  37991. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37992. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37993. })(BABYLON || (BABYLON = {}));
  37994. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37995. var BABYLON;
  37996. (function (BABYLON) {
  37997. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37998. function ArcRotateCameraPointersInput() {
  37999. this.buttons = [0, 1, 2];
  38000. this.angularSensibilityX = 1000.0;
  38001. this.angularSensibilityY = 1000.0;
  38002. this.pinchPrecision = 12.0;
  38003. /**
  38004. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38005. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38006. */
  38007. this.pinchDeltaPercentage = 0;
  38008. this.panningSensibility = 1000.0;
  38009. this.multiTouchPanning = true;
  38010. this.multiTouchPanAndZoom = true;
  38011. this._isPanClick = false;
  38012. this.pinchInwards = true;
  38013. }
  38014. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38015. var _this = this;
  38016. var engine = this.camera.getEngine();
  38017. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38018. var pointA = null;
  38019. var pointB = null;
  38020. var previousPinchSquaredDistance = 0;
  38021. var initialDistance = 0;
  38022. var twoFingerActivityCount = 0;
  38023. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38024. this._pointerInput = function (p, s) {
  38025. var evt = p.event;
  38026. if (engine.isInVRExclusivePointerMode) {
  38027. return;
  38028. }
  38029. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38030. return;
  38031. }
  38032. var srcElement = (evt.srcElement || evt.target);
  38033. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38034. try {
  38035. srcElement.setPointerCapture(evt.pointerId);
  38036. }
  38037. catch (e) {
  38038. //Nothing to do with the error. Execution will continue.
  38039. }
  38040. // Manage panning with pan button click
  38041. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38042. // manage pointers
  38043. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38044. if (pointA === null) {
  38045. pointA = cacheSoloPointer;
  38046. }
  38047. else if (pointB === null) {
  38048. pointB = cacheSoloPointer;
  38049. }
  38050. if (!noPreventDefault) {
  38051. evt.preventDefault();
  38052. element.focus();
  38053. }
  38054. }
  38055. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38056. _this.camera.restoreState();
  38057. }
  38058. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38059. try {
  38060. srcElement.releasePointerCapture(evt.pointerId);
  38061. }
  38062. catch (e) {
  38063. //Nothing to do with the error.
  38064. }
  38065. cacheSoloPointer = null;
  38066. previousPinchSquaredDistance = 0;
  38067. previousMultiTouchPanPosition.isPaning = false;
  38068. previousMultiTouchPanPosition.isPinching = false;
  38069. twoFingerActivityCount = 0;
  38070. initialDistance = 0;
  38071. if (p.event.pointerType !== "touch") {
  38072. pointB = null; // Mouse and pen are mono pointer
  38073. }
  38074. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38075. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38076. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38077. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38078. if (engine.badOS) {
  38079. pointA = pointB = null;
  38080. }
  38081. else {
  38082. //only remove the impacted pointer in case of multitouch allowing on most
  38083. //platforms switching from rotate to zoom and pan seamlessly.
  38084. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38085. pointA = pointB;
  38086. pointB = null;
  38087. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38088. }
  38089. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38090. pointB = null;
  38091. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38092. }
  38093. else {
  38094. pointA = pointB = null;
  38095. }
  38096. }
  38097. if (!noPreventDefault) {
  38098. evt.preventDefault();
  38099. }
  38100. }
  38101. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38102. if (!noPreventDefault) {
  38103. evt.preventDefault();
  38104. }
  38105. // One button down
  38106. if (pointA && pointB === null && cacheSoloPointer) {
  38107. if (_this.panningSensibility !== 0 &&
  38108. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38109. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38110. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38111. }
  38112. else {
  38113. var offsetX = evt.clientX - cacheSoloPointer.x;
  38114. var offsetY = evt.clientY - cacheSoloPointer.y;
  38115. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38116. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38117. }
  38118. cacheSoloPointer.x = evt.clientX;
  38119. cacheSoloPointer.y = evt.clientY;
  38120. }
  38121. else if (pointA && pointB) {
  38122. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38123. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38124. ed.x = evt.clientX;
  38125. ed.y = evt.clientY;
  38126. var direction = _this.pinchInwards ? 1 : -1;
  38127. var distX = pointA.x - pointB.x;
  38128. var distY = pointA.y - pointB.y;
  38129. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38130. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38131. if (previousPinchSquaredDistance === 0) {
  38132. initialDistance = pinchDistance;
  38133. previousPinchSquaredDistance = pinchSquaredDistance;
  38134. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38135. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38136. return;
  38137. }
  38138. if (_this.multiTouchPanAndZoom) {
  38139. if (_this.pinchDeltaPercentage) {
  38140. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38141. }
  38142. else {
  38143. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38144. (_this.pinchPrecision *
  38145. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38146. direction);
  38147. }
  38148. if (_this.panningSensibility !== 0) {
  38149. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38150. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38151. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38152. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38153. previousMultiTouchPanPosition.x = pointersCenterX;
  38154. previousMultiTouchPanPosition.y = pointersCenterY;
  38155. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38156. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38157. }
  38158. }
  38159. else {
  38160. twoFingerActivityCount++;
  38161. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38162. if (_this.pinchDeltaPercentage) {
  38163. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38164. }
  38165. else {
  38166. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38167. (_this.pinchPrecision *
  38168. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38169. direction);
  38170. }
  38171. previousMultiTouchPanPosition.isPaning = false;
  38172. previousMultiTouchPanPosition.isPinching = true;
  38173. }
  38174. else {
  38175. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38176. if (!previousMultiTouchPanPosition.isPaning) {
  38177. previousMultiTouchPanPosition.isPaning = true;
  38178. previousMultiTouchPanPosition.isPinching = false;
  38179. previousMultiTouchPanPosition.x = ed.x;
  38180. previousMultiTouchPanPosition.y = ed.y;
  38181. return;
  38182. }
  38183. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38184. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38185. }
  38186. }
  38187. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38188. previousMultiTouchPanPosition.x = ed.x;
  38189. previousMultiTouchPanPosition.y = ed.y;
  38190. }
  38191. }
  38192. previousPinchSquaredDistance = pinchSquaredDistance;
  38193. }
  38194. }
  38195. };
  38196. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38197. this._onContextMenu = function (evt) {
  38198. evt.preventDefault();
  38199. };
  38200. if (!this.camera._useCtrlForPanning) {
  38201. element.addEventListener("contextmenu", this._onContextMenu, false);
  38202. }
  38203. this._onLostFocus = function () {
  38204. //this._keys = [];
  38205. pointA = pointB = null;
  38206. previousPinchSquaredDistance = 0;
  38207. previousMultiTouchPanPosition.isPaning = false;
  38208. previousMultiTouchPanPosition.isPinching = false;
  38209. twoFingerActivityCount = 0;
  38210. cacheSoloPointer = null;
  38211. initialDistance = 0;
  38212. };
  38213. this._onMouseMove = function (evt) {
  38214. if (!engine.isPointerLock) {
  38215. return;
  38216. }
  38217. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38218. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38219. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38220. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38221. if (!noPreventDefault) {
  38222. evt.preventDefault();
  38223. }
  38224. };
  38225. this._onGestureStart = function (e) {
  38226. if (window.MSGesture === undefined) {
  38227. return;
  38228. }
  38229. if (!_this._MSGestureHandler) {
  38230. _this._MSGestureHandler = new MSGesture();
  38231. _this._MSGestureHandler.target = element;
  38232. }
  38233. _this._MSGestureHandler.addPointer(e.pointerId);
  38234. };
  38235. this._onGesture = function (e) {
  38236. _this.camera.radius *= e.scale;
  38237. if (e.preventDefault) {
  38238. if (!noPreventDefault) {
  38239. e.stopPropagation();
  38240. e.preventDefault();
  38241. }
  38242. }
  38243. };
  38244. element.addEventListener("mousemove", this._onMouseMove, false);
  38245. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38246. element.addEventListener("MSGestureChange", this._onGesture, false);
  38247. BABYLON.Tools.RegisterTopRootEvents([
  38248. { name: "blur", handler: this._onLostFocus }
  38249. ]);
  38250. };
  38251. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38252. if (this._onLostFocus) {
  38253. BABYLON.Tools.UnregisterTopRootEvents([
  38254. { name: "blur", handler: this._onLostFocus }
  38255. ]);
  38256. }
  38257. if (element && this._observer) {
  38258. this.camera.getScene().onPointerObservable.remove(this._observer);
  38259. this._observer = null;
  38260. if (this._onContextMenu) {
  38261. element.removeEventListener("contextmenu", this._onContextMenu);
  38262. }
  38263. if (this._onMouseMove) {
  38264. element.removeEventListener("mousemove", this._onMouseMove);
  38265. }
  38266. if (this._onGestureStart) {
  38267. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38268. }
  38269. if (this._onGesture) {
  38270. element.removeEventListener("MSGestureChange", this._onGesture);
  38271. }
  38272. this._isPanClick = false;
  38273. this.pinchInwards = true;
  38274. this._onMouseMove = null;
  38275. this._onGestureStart = null;
  38276. this._onGesture = null;
  38277. this._MSGestureHandler = null;
  38278. this._onLostFocus = null;
  38279. this._onContextMenu = null;
  38280. }
  38281. };
  38282. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38283. return "ArcRotateCameraPointersInput";
  38284. };
  38285. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38286. return "pointers";
  38287. };
  38288. __decorate([
  38289. BABYLON.serialize()
  38290. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38291. __decorate([
  38292. BABYLON.serialize()
  38293. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38294. __decorate([
  38295. BABYLON.serialize()
  38296. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38297. __decorate([
  38298. BABYLON.serialize()
  38299. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38300. __decorate([
  38301. BABYLON.serialize()
  38302. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38303. __decorate([
  38304. BABYLON.serialize()
  38305. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38306. __decorate([
  38307. BABYLON.serialize()
  38308. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38309. __decorate([
  38310. BABYLON.serialize()
  38311. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38312. return ArcRotateCameraPointersInput;
  38313. }());
  38314. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38315. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38316. })(BABYLON || (BABYLON = {}));
  38317. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38318. var BABYLON;
  38319. (function (BABYLON) {
  38320. var ArcRotateCamera = /** @class */ (function (_super) {
  38321. __extends(ArcRotateCamera, _super);
  38322. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38323. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38324. _this.inertialAlphaOffset = 0;
  38325. _this.inertialBetaOffset = 0;
  38326. _this.inertialRadiusOffset = 0;
  38327. _this.lowerAlphaLimit = null;
  38328. _this.upperAlphaLimit = null;
  38329. _this.lowerBetaLimit = 0.01;
  38330. _this.upperBetaLimit = Math.PI;
  38331. _this.lowerRadiusLimit = null;
  38332. _this.upperRadiusLimit = null;
  38333. _this.inertialPanningX = 0;
  38334. _this.inertialPanningY = 0;
  38335. _this.pinchToPanMaxDistance = 20;
  38336. _this.panningDistanceLimit = null;
  38337. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38338. _this.panningInertia = 0.9;
  38339. //-- end properties for backward compatibility for inputs
  38340. _this.zoomOnFactor = 1;
  38341. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38342. _this.allowUpsideDown = true;
  38343. _this._viewMatrix = new BABYLON.Matrix();
  38344. // Panning
  38345. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38346. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38347. _this.checkCollisions = false;
  38348. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38349. _this._previousPosition = BABYLON.Vector3.Zero();
  38350. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38351. _this._newPosition = BABYLON.Vector3.Zero();
  38352. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38353. if (collidedMesh === void 0) { collidedMesh = null; }
  38354. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38355. newPosition.multiplyInPlace(_this._collider.radius);
  38356. }
  38357. if (!collidedMesh) {
  38358. _this._previousPosition.copyFrom(_this.position);
  38359. }
  38360. else {
  38361. _this.setPosition(newPosition);
  38362. if (_this.onCollide) {
  38363. _this.onCollide(collidedMesh);
  38364. }
  38365. }
  38366. // Recompute because of constraints
  38367. var cosa = Math.cos(_this.alpha);
  38368. var sina = Math.sin(_this.alpha);
  38369. var cosb = Math.cos(_this.beta);
  38370. var sinb = Math.sin(_this.beta);
  38371. if (sinb === 0) {
  38372. sinb = 0.0001;
  38373. }
  38374. var target = _this._getTargetPosition();
  38375. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38376. _this.position.copyFrom(_this._newPosition);
  38377. var up = _this.upVector;
  38378. if (_this.allowUpsideDown && _this.beta < 0) {
  38379. up = up.clone();
  38380. up = up.negate();
  38381. }
  38382. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38383. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38384. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38385. _this._collisionTriggered = false;
  38386. };
  38387. _this._target = BABYLON.Vector3.Zero();
  38388. if (target) {
  38389. _this.setTarget(target);
  38390. }
  38391. _this.alpha = alpha;
  38392. _this.beta = beta;
  38393. _this.radius = radius;
  38394. _this.getViewMatrix();
  38395. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38396. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38397. return _this;
  38398. }
  38399. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38400. get: function () {
  38401. return this._target;
  38402. },
  38403. set: function (value) {
  38404. this.setTarget(value);
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38410. //-- begin properties for backward compatibility for inputs
  38411. get: function () {
  38412. var pointers = this.inputs.attached["pointers"];
  38413. if (pointers)
  38414. return pointers.angularSensibilityX;
  38415. return 0;
  38416. },
  38417. set: function (value) {
  38418. var pointers = this.inputs.attached["pointers"];
  38419. if (pointers) {
  38420. pointers.angularSensibilityX = value;
  38421. }
  38422. },
  38423. enumerable: true,
  38424. configurable: true
  38425. });
  38426. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38427. get: function () {
  38428. var pointers = this.inputs.attached["pointers"];
  38429. if (pointers)
  38430. return pointers.angularSensibilityY;
  38431. return 0;
  38432. },
  38433. set: function (value) {
  38434. var pointers = this.inputs.attached["pointers"];
  38435. if (pointers) {
  38436. pointers.angularSensibilityY = value;
  38437. }
  38438. },
  38439. enumerable: true,
  38440. configurable: true
  38441. });
  38442. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38443. get: function () {
  38444. var pointers = this.inputs.attached["pointers"];
  38445. if (pointers)
  38446. return pointers.pinchPrecision;
  38447. return 0;
  38448. },
  38449. set: function (value) {
  38450. var pointers = this.inputs.attached["pointers"];
  38451. if (pointers) {
  38452. pointers.pinchPrecision = value;
  38453. }
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38459. get: function () {
  38460. var pointers = this.inputs.attached["pointers"];
  38461. if (pointers)
  38462. return pointers.pinchDeltaPercentage;
  38463. return 0;
  38464. },
  38465. set: function (value) {
  38466. var pointers = this.inputs.attached["pointers"];
  38467. if (pointers) {
  38468. pointers.pinchDeltaPercentage = value;
  38469. }
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38475. get: function () {
  38476. var pointers = this.inputs.attached["pointers"];
  38477. if (pointers)
  38478. return pointers.panningSensibility;
  38479. return 0;
  38480. },
  38481. set: function (value) {
  38482. var pointers = this.inputs.attached["pointers"];
  38483. if (pointers) {
  38484. pointers.panningSensibility = value;
  38485. }
  38486. },
  38487. enumerable: true,
  38488. configurable: true
  38489. });
  38490. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38491. get: function () {
  38492. var keyboard = this.inputs.attached["keyboard"];
  38493. if (keyboard)
  38494. return keyboard.keysUp;
  38495. return [];
  38496. },
  38497. set: function (value) {
  38498. var keyboard = this.inputs.attached["keyboard"];
  38499. if (keyboard)
  38500. keyboard.keysUp = value;
  38501. },
  38502. enumerable: true,
  38503. configurable: true
  38504. });
  38505. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38506. get: function () {
  38507. var keyboard = this.inputs.attached["keyboard"];
  38508. if (keyboard)
  38509. return keyboard.keysDown;
  38510. return [];
  38511. },
  38512. set: function (value) {
  38513. var keyboard = this.inputs.attached["keyboard"];
  38514. if (keyboard)
  38515. keyboard.keysDown = value;
  38516. },
  38517. enumerable: true,
  38518. configurable: true
  38519. });
  38520. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38521. get: function () {
  38522. var keyboard = this.inputs.attached["keyboard"];
  38523. if (keyboard)
  38524. return keyboard.keysLeft;
  38525. return [];
  38526. },
  38527. set: function (value) {
  38528. var keyboard = this.inputs.attached["keyboard"];
  38529. if (keyboard)
  38530. keyboard.keysLeft = value;
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38536. get: function () {
  38537. var keyboard = this.inputs.attached["keyboard"];
  38538. if (keyboard)
  38539. return keyboard.keysRight;
  38540. return [];
  38541. },
  38542. set: function (value) {
  38543. var keyboard = this.inputs.attached["keyboard"];
  38544. if (keyboard)
  38545. keyboard.keysRight = value;
  38546. },
  38547. enumerable: true,
  38548. configurable: true
  38549. });
  38550. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38551. get: function () {
  38552. var mousewheel = this.inputs.attached["mousewheel"];
  38553. if (mousewheel)
  38554. return mousewheel.wheelPrecision;
  38555. return 0;
  38556. },
  38557. set: function (value) {
  38558. var mousewheel = this.inputs.attached["mousewheel"];
  38559. if (mousewheel)
  38560. mousewheel.wheelPrecision = value;
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38566. get: function () {
  38567. var mousewheel = this.inputs.attached["mousewheel"];
  38568. if (mousewheel)
  38569. return mousewheel.wheelDeltaPercentage;
  38570. return 0;
  38571. },
  38572. set: function (value) {
  38573. var mousewheel = this.inputs.attached["mousewheel"];
  38574. if (mousewheel)
  38575. mousewheel.wheelDeltaPercentage = value;
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38581. get: function () {
  38582. return this._bouncingBehavior;
  38583. },
  38584. enumerable: true,
  38585. configurable: true
  38586. });
  38587. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38588. get: function () {
  38589. return this._bouncingBehavior != null;
  38590. },
  38591. set: function (value) {
  38592. if (value === this.useBouncingBehavior) {
  38593. return;
  38594. }
  38595. if (value) {
  38596. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38597. this.addBehavior(this._bouncingBehavior);
  38598. }
  38599. else if (this._bouncingBehavior) {
  38600. this.removeBehavior(this._bouncingBehavior);
  38601. this._bouncingBehavior = null;
  38602. }
  38603. },
  38604. enumerable: true,
  38605. configurable: true
  38606. });
  38607. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38608. get: function () {
  38609. return this._framingBehavior;
  38610. },
  38611. enumerable: true,
  38612. configurable: true
  38613. });
  38614. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38615. get: function () {
  38616. return this._framingBehavior != null;
  38617. },
  38618. set: function (value) {
  38619. if (value === this.useFramingBehavior) {
  38620. return;
  38621. }
  38622. if (value) {
  38623. this._framingBehavior = new BABYLON.FramingBehavior();
  38624. this.addBehavior(this._framingBehavior);
  38625. }
  38626. else if (this._framingBehavior) {
  38627. this.removeBehavior(this._framingBehavior);
  38628. this._framingBehavior = null;
  38629. }
  38630. },
  38631. enumerable: true,
  38632. configurable: true
  38633. });
  38634. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38635. get: function () {
  38636. return this._autoRotationBehavior;
  38637. },
  38638. enumerable: true,
  38639. configurable: true
  38640. });
  38641. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38642. get: function () {
  38643. return this._autoRotationBehavior != null;
  38644. },
  38645. set: function (value) {
  38646. if (value === this.useAutoRotationBehavior) {
  38647. return;
  38648. }
  38649. if (value) {
  38650. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38651. this.addBehavior(this._autoRotationBehavior);
  38652. }
  38653. else if (this._autoRotationBehavior) {
  38654. this.removeBehavior(this._autoRotationBehavior);
  38655. this._autoRotationBehavior = null;
  38656. }
  38657. },
  38658. enumerable: true,
  38659. configurable: true
  38660. });
  38661. // Cache
  38662. ArcRotateCamera.prototype._initCache = function () {
  38663. _super.prototype._initCache.call(this);
  38664. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38665. this._cache.alpha = undefined;
  38666. this._cache.beta = undefined;
  38667. this._cache.radius = undefined;
  38668. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38669. };
  38670. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38671. if (!ignoreParentClass) {
  38672. _super.prototype._updateCache.call(this);
  38673. }
  38674. this._cache._target.copyFrom(this._getTargetPosition());
  38675. this._cache.alpha = this.alpha;
  38676. this._cache.beta = this.beta;
  38677. this._cache.radius = this.radius;
  38678. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38679. };
  38680. ArcRotateCamera.prototype._getTargetPosition = function () {
  38681. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38682. var pos = this._targetHost.getAbsolutePosition();
  38683. if (this._targetBoundingCenter) {
  38684. pos.addToRef(this._targetBoundingCenter, this._target);
  38685. }
  38686. else {
  38687. this._target.copyFrom(pos);
  38688. }
  38689. }
  38690. var lockedTargetPosition = this._getLockedTargetPosition();
  38691. if (lockedTargetPosition) {
  38692. return lockedTargetPosition;
  38693. }
  38694. return this._target;
  38695. };
  38696. ArcRotateCamera.prototype.storeState = function () {
  38697. this._storedAlpha = this.alpha;
  38698. this._storedBeta = this.beta;
  38699. this._storedRadius = this.radius;
  38700. this._storedTarget = this._getTargetPosition().clone();
  38701. return _super.prototype.storeState.call(this);
  38702. };
  38703. /**
  38704. * Restored camera state. You must call storeState() first
  38705. */
  38706. ArcRotateCamera.prototype._restoreStateValues = function () {
  38707. if (!_super.prototype._restoreStateValues.call(this)) {
  38708. return false;
  38709. }
  38710. this.alpha = this._storedAlpha;
  38711. this.beta = this._storedBeta;
  38712. this.radius = this._storedRadius;
  38713. this.setTarget(this._storedTarget.clone());
  38714. this.inertialAlphaOffset = 0;
  38715. this.inertialBetaOffset = 0;
  38716. this.inertialRadiusOffset = 0;
  38717. this.inertialPanningX = 0;
  38718. this.inertialPanningY = 0;
  38719. return true;
  38720. };
  38721. // Synchronized
  38722. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38723. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38724. return false;
  38725. return this._cache._target.equals(this._getTargetPosition())
  38726. && this._cache.alpha === this.alpha
  38727. && this._cache.beta === this.beta
  38728. && this._cache.radius === this.radius
  38729. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38730. };
  38731. // Methods
  38732. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38733. var _this = this;
  38734. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38735. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38736. this._useCtrlForPanning = useCtrlForPanning;
  38737. this._panningMouseButton = panningMouseButton;
  38738. this.inputs.attachElement(element, noPreventDefault);
  38739. this._reset = function () {
  38740. _this.inertialAlphaOffset = 0;
  38741. _this.inertialBetaOffset = 0;
  38742. _this.inertialRadiusOffset = 0;
  38743. _this.inertialPanningX = 0;
  38744. _this.inertialPanningY = 0;
  38745. };
  38746. };
  38747. ArcRotateCamera.prototype.detachControl = function (element) {
  38748. this.inputs.detachElement(element);
  38749. if (this._reset) {
  38750. this._reset();
  38751. }
  38752. };
  38753. ArcRotateCamera.prototype._checkInputs = function () {
  38754. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38755. if (this._collisionTriggered) {
  38756. return;
  38757. }
  38758. this.inputs.checkInputs();
  38759. // Inertia
  38760. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38761. if (this.getScene().useRightHandedSystem) {
  38762. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38763. }
  38764. else {
  38765. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38766. }
  38767. this.beta += this.inertialBetaOffset;
  38768. this.radius -= this.inertialRadiusOffset;
  38769. this.inertialAlphaOffset *= this.inertia;
  38770. this.inertialBetaOffset *= this.inertia;
  38771. this.inertialRadiusOffset *= this.inertia;
  38772. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38773. this.inertialAlphaOffset = 0;
  38774. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38775. this.inertialBetaOffset = 0;
  38776. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38777. this.inertialRadiusOffset = 0;
  38778. }
  38779. // Panning inertia
  38780. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38781. if (!this._localDirection) {
  38782. this._localDirection = BABYLON.Vector3.Zero();
  38783. this._transformedDirection = BABYLON.Vector3.Zero();
  38784. }
  38785. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38786. this._localDirection.multiplyInPlace(this.panningAxis);
  38787. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38788. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38789. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38790. if (!this.panningAxis.y) {
  38791. this._transformedDirection.y = 0;
  38792. }
  38793. if (!this._targetHost) {
  38794. if (this.panningDistanceLimit) {
  38795. this._transformedDirection.addInPlace(this._target);
  38796. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38797. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38798. this._target.copyFrom(this._transformedDirection);
  38799. }
  38800. }
  38801. else {
  38802. this._target.addInPlace(this._transformedDirection);
  38803. }
  38804. }
  38805. this.inertialPanningX *= this.panningInertia;
  38806. this.inertialPanningY *= this.panningInertia;
  38807. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38808. this.inertialPanningX = 0;
  38809. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38810. this.inertialPanningY = 0;
  38811. }
  38812. // Limits
  38813. this._checkLimits();
  38814. _super.prototype._checkInputs.call(this);
  38815. };
  38816. ArcRotateCamera.prototype._checkLimits = function () {
  38817. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38818. if (this.allowUpsideDown && this.beta > Math.PI) {
  38819. this.beta = this.beta - (2 * Math.PI);
  38820. }
  38821. }
  38822. else {
  38823. if (this.beta < this.lowerBetaLimit) {
  38824. this.beta = this.lowerBetaLimit;
  38825. }
  38826. }
  38827. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38828. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38829. this.beta = this.beta + (2 * Math.PI);
  38830. }
  38831. }
  38832. else {
  38833. if (this.beta > this.upperBetaLimit) {
  38834. this.beta = this.upperBetaLimit;
  38835. }
  38836. }
  38837. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38838. this.alpha = this.lowerAlphaLimit;
  38839. }
  38840. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38841. this.alpha = this.upperAlphaLimit;
  38842. }
  38843. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38844. this.radius = this.lowerRadiusLimit;
  38845. }
  38846. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38847. this.radius = this.upperRadiusLimit;
  38848. }
  38849. };
  38850. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38851. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38852. this.radius = radiusv3.length();
  38853. if (this.radius === 0) {
  38854. this.radius = 0.0001; // Just to avoid division by zero
  38855. }
  38856. // Alpha
  38857. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38858. if (radiusv3.z < 0) {
  38859. this.alpha = 2 * Math.PI - this.alpha;
  38860. }
  38861. // Beta
  38862. this.beta = Math.acos(radiusv3.y / this.radius);
  38863. this._checkLimits();
  38864. };
  38865. ArcRotateCamera.prototype.setPosition = function (position) {
  38866. if (this.position.equals(position)) {
  38867. return;
  38868. }
  38869. this.position.copyFrom(position);
  38870. this.rebuildAnglesAndRadius();
  38871. };
  38872. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38873. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38874. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38875. if (target.getBoundingInfo) {
  38876. if (toBoundingCenter) {
  38877. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38878. }
  38879. else {
  38880. this._targetBoundingCenter = null;
  38881. }
  38882. this._targetHost = target;
  38883. this._target = this._getTargetPosition();
  38884. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38885. }
  38886. else {
  38887. var newTarget = target;
  38888. var currentTarget = this._getTargetPosition();
  38889. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38890. return;
  38891. }
  38892. this._targetHost = null;
  38893. this._target = newTarget;
  38894. this._targetBoundingCenter = null;
  38895. this.onMeshTargetChangedObservable.notifyObservers(null);
  38896. }
  38897. this.rebuildAnglesAndRadius();
  38898. };
  38899. ArcRotateCamera.prototype._getViewMatrix = function () {
  38900. // Compute
  38901. var cosa = Math.cos(this.alpha);
  38902. var sina = Math.sin(this.alpha);
  38903. var cosb = Math.cos(this.beta);
  38904. var sinb = Math.sin(this.beta);
  38905. if (sinb === 0) {
  38906. sinb = 0.0001;
  38907. }
  38908. var target = this._getTargetPosition();
  38909. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38910. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38911. if (!this._collider) {
  38912. this._collider = new BABYLON.Collider();
  38913. }
  38914. this._collider.radius = this.collisionRadius;
  38915. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38916. this._collisionTriggered = true;
  38917. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38918. }
  38919. else {
  38920. this.position.copyFrom(this._newPosition);
  38921. var up = this.upVector;
  38922. if (this.allowUpsideDown && sinb < 0) {
  38923. up = up.clone();
  38924. up = up.negate();
  38925. }
  38926. if (this.getScene().useRightHandedSystem) {
  38927. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38928. }
  38929. else {
  38930. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38931. }
  38932. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38933. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38934. }
  38935. this._currentTarget = target;
  38936. return this._viewMatrix;
  38937. };
  38938. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38939. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38940. meshes = meshes || this.getScene().meshes;
  38941. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38942. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38943. this.radius = distance * this.zoomOnFactor;
  38944. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38945. };
  38946. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38947. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38948. var meshesOrMinMaxVector;
  38949. var distance;
  38950. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38951. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38952. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38953. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38954. }
  38955. else {
  38956. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38957. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38958. distance = minMaxVectorAndDistance.distance;
  38959. }
  38960. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38961. if (!doNotUpdateMaxZ) {
  38962. this.maxZ = distance * 2;
  38963. }
  38964. };
  38965. /**
  38966. * @override
  38967. * Override Camera.createRigCamera
  38968. */
  38969. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38970. var alphaShift = 0;
  38971. switch (this.cameraRigMode) {
  38972. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38975. case BABYLON.Camera.RIG_MODE_VR:
  38976. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38977. break;
  38978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38979. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38980. break;
  38981. }
  38982. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38983. rigCam._cameraRigParams = {};
  38984. return rigCam;
  38985. };
  38986. /**
  38987. * @override
  38988. * Override Camera._updateRigCameras
  38989. */
  38990. ArcRotateCamera.prototype._updateRigCameras = function () {
  38991. var camLeft = this._rigCameras[0];
  38992. var camRight = this._rigCameras[1];
  38993. camLeft.beta = camRight.beta = this.beta;
  38994. camLeft.radius = camRight.radius = this.radius;
  38995. switch (this.cameraRigMode) {
  38996. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38999. case BABYLON.Camera.RIG_MODE_VR:
  39000. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39001. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39002. break;
  39003. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39004. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39005. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39006. break;
  39007. }
  39008. _super.prototype._updateRigCameras.call(this);
  39009. };
  39010. ArcRotateCamera.prototype.dispose = function () {
  39011. this.inputs.clear();
  39012. _super.prototype.dispose.call(this);
  39013. };
  39014. ArcRotateCamera.prototype.getClassName = function () {
  39015. return "ArcRotateCamera";
  39016. };
  39017. __decorate([
  39018. BABYLON.serialize()
  39019. ], ArcRotateCamera.prototype, "alpha", void 0);
  39020. __decorate([
  39021. BABYLON.serialize()
  39022. ], ArcRotateCamera.prototype, "beta", void 0);
  39023. __decorate([
  39024. BABYLON.serialize()
  39025. ], ArcRotateCamera.prototype, "radius", void 0);
  39026. __decorate([
  39027. BABYLON.serializeAsVector3("target")
  39028. ], ArcRotateCamera.prototype, "_target", void 0);
  39029. __decorate([
  39030. BABYLON.serialize()
  39031. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39032. __decorate([
  39033. BABYLON.serialize()
  39034. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39035. __decorate([
  39036. BABYLON.serialize()
  39037. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39038. __decorate([
  39039. BABYLON.serialize()
  39040. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39041. __decorate([
  39042. BABYLON.serialize()
  39043. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39044. __decorate([
  39045. BABYLON.serialize()
  39046. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39047. __decorate([
  39048. BABYLON.serialize()
  39049. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39050. __decorate([
  39051. BABYLON.serialize()
  39052. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39053. __decorate([
  39054. BABYLON.serialize()
  39055. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39056. __decorate([
  39057. BABYLON.serialize()
  39058. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39059. __decorate([
  39060. BABYLON.serialize()
  39061. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39062. __decorate([
  39063. BABYLON.serialize()
  39064. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39065. __decorate([
  39066. BABYLON.serialize()
  39067. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39068. __decorate([
  39069. BABYLON.serializeAsVector3()
  39070. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39071. __decorate([
  39072. BABYLON.serialize()
  39073. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39074. __decorate([
  39075. BABYLON.serialize()
  39076. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39077. __decorate([
  39078. BABYLON.serialize()
  39079. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39080. return ArcRotateCamera;
  39081. }(BABYLON.TargetCamera));
  39082. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39083. })(BABYLON || (BABYLON = {}));
  39084. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39085. var BABYLON;
  39086. (function (BABYLON) {
  39087. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39088. __extends(ArcRotateCameraInputsManager, _super);
  39089. function ArcRotateCameraInputsManager(camera) {
  39090. return _super.call(this, camera) || this;
  39091. }
  39092. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39093. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39094. return this;
  39095. };
  39096. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39097. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39098. return this;
  39099. };
  39100. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39101. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39102. return this;
  39103. };
  39104. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39105. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39106. return this;
  39107. };
  39108. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39109. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39110. return this;
  39111. };
  39112. return ArcRotateCameraInputsManager;
  39113. }(BABYLON.CameraInputsManager));
  39114. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39115. })(BABYLON || (BABYLON = {}));
  39116. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39117. var BABYLON;
  39118. (function (BABYLON) {
  39119. var HemisphericLight = /** @class */ (function (_super) {
  39120. __extends(HemisphericLight, _super);
  39121. /**
  39122. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39123. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39124. * The HemisphericLight can't cast shadows.
  39125. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39126. */
  39127. function HemisphericLight(name, direction, scene) {
  39128. var _this = _super.call(this, name, scene) || this;
  39129. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39130. _this.direction = direction || BABYLON.Vector3.Up();
  39131. return _this;
  39132. }
  39133. HemisphericLight.prototype._buildUniformLayout = function () {
  39134. this._uniformBuffer.addUniform("vLightData", 4);
  39135. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39136. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39137. this._uniformBuffer.addUniform("vLightGround", 3);
  39138. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39139. this._uniformBuffer.addUniform("depthValues", 2);
  39140. this._uniformBuffer.create();
  39141. };
  39142. /**
  39143. * Returns the string "HemisphericLight".
  39144. */
  39145. HemisphericLight.prototype.getClassName = function () {
  39146. return "HemisphericLight";
  39147. };
  39148. /**
  39149. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39150. * Returns the updated direction.
  39151. */
  39152. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39153. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39154. return this.direction;
  39155. };
  39156. HemisphericLight.prototype.getShadowGenerator = function () {
  39157. return null;
  39158. };
  39159. /**
  39160. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39161. * Returns the HemisphericLight.
  39162. */
  39163. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39164. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39165. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39166. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39167. return this;
  39168. };
  39169. HemisphericLight.prototype._getWorldMatrix = function () {
  39170. if (!this._worldMatrix) {
  39171. this._worldMatrix = BABYLON.Matrix.Identity();
  39172. }
  39173. return this._worldMatrix;
  39174. };
  39175. /**
  39176. * Returns the integer 3.
  39177. */
  39178. HemisphericLight.prototype.getTypeID = function () {
  39179. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39180. };
  39181. __decorate([
  39182. BABYLON.serializeAsColor3()
  39183. ], HemisphericLight.prototype, "groundColor", void 0);
  39184. __decorate([
  39185. BABYLON.serializeAsVector3()
  39186. ], HemisphericLight.prototype, "direction", void 0);
  39187. return HemisphericLight;
  39188. }(BABYLON.Light));
  39189. BABYLON.HemisphericLight = HemisphericLight;
  39190. })(BABYLON || (BABYLON = {}));
  39191. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39192. var BABYLON;
  39193. (function (BABYLON) {
  39194. var ShadowLight = /** @class */ (function (_super) {
  39195. __extends(ShadowLight, _super);
  39196. function ShadowLight() {
  39197. var _this = _super !== null && _super.apply(this, arguments) || this;
  39198. _this._needProjectionMatrixCompute = true;
  39199. return _this;
  39200. }
  39201. Object.defineProperty(ShadowLight.prototype, "direction", {
  39202. get: function () {
  39203. return this._direction;
  39204. },
  39205. set: function (value) {
  39206. this._direction = value;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39212. get: function () {
  39213. return this._shadowMinZ;
  39214. },
  39215. set: function (value) {
  39216. this._shadowMinZ = value;
  39217. this.forceProjectionMatrixCompute();
  39218. },
  39219. enumerable: true,
  39220. configurable: true
  39221. });
  39222. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39223. get: function () {
  39224. return this._shadowMaxZ;
  39225. },
  39226. set: function (value) {
  39227. this._shadowMaxZ = value;
  39228. this.forceProjectionMatrixCompute();
  39229. },
  39230. enumerable: true,
  39231. configurable: true
  39232. });
  39233. /**
  39234. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39235. */
  39236. ShadowLight.prototype.computeTransformedInformation = function () {
  39237. if (this.parent && this.parent.getWorldMatrix) {
  39238. if (!this.transformedPosition) {
  39239. this.transformedPosition = BABYLON.Vector3.Zero();
  39240. }
  39241. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39242. // In case the direction is present.
  39243. if (this.direction) {
  39244. if (!this.transformedDirection) {
  39245. this.transformedDirection = BABYLON.Vector3.Zero();
  39246. }
  39247. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39248. }
  39249. return true;
  39250. }
  39251. return false;
  39252. };
  39253. /**
  39254. * Return the depth scale used for the shadow map.
  39255. */
  39256. ShadowLight.prototype.getDepthScale = function () {
  39257. return 50.0;
  39258. };
  39259. /**
  39260. * Returns the light direction (Vector3) for any passed face index.
  39261. */
  39262. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39263. return this.transformedDirection ? this.transformedDirection : this.direction;
  39264. };
  39265. /**
  39266. * Returns the DirectionalLight absolute position in the World.
  39267. */
  39268. ShadowLight.prototype.getAbsolutePosition = function () {
  39269. return this.transformedPosition ? this.transformedPosition : this.position;
  39270. };
  39271. /**
  39272. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39273. * Returns the updated DirectionalLight direction (Vector3).
  39274. */
  39275. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39276. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39277. return this.direction;
  39278. };
  39279. /**
  39280. * Returns the light rotation (Vector3).
  39281. */
  39282. ShadowLight.prototype.getRotation = function () {
  39283. this.direction.normalize();
  39284. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39285. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39286. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39287. };
  39288. /**
  39289. * Boolean : false by default.
  39290. */
  39291. ShadowLight.prototype.needCube = function () {
  39292. return false;
  39293. };
  39294. /**
  39295. * Specifies wether or not the projection matrix should be recomputed this frame.
  39296. */
  39297. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39298. return this._needProjectionMatrixCompute;
  39299. };
  39300. /**
  39301. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39302. */
  39303. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39304. this._needProjectionMatrixCompute = true;
  39305. };
  39306. /**
  39307. * Get the world matrix of the sahdow lights.
  39308. */
  39309. ShadowLight.prototype._getWorldMatrix = function () {
  39310. if (!this._worldMatrix) {
  39311. this._worldMatrix = BABYLON.Matrix.Identity();
  39312. }
  39313. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39314. return this._worldMatrix;
  39315. };
  39316. /**
  39317. * Gets the minZ used for shadow according to both the scene and the light.
  39318. * @param activeCamera
  39319. */
  39320. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39321. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39322. };
  39323. /**
  39324. * Gets the maxZ used for shadow according to both the scene and the light.
  39325. * @param activeCamera
  39326. */
  39327. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39328. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39329. };
  39330. /**
  39331. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39332. * Returns the light.
  39333. */
  39334. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39335. if (this.customProjectionMatrixBuilder) {
  39336. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39337. }
  39338. else {
  39339. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39340. }
  39341. return this;
  39342. };
  39343. __decorate([
  39344. BABYLON.serializeAsVector3()
  39345. ], ShadowLight.prototype, "position", void 0);
  39346. __decorate([
  39347. BABYLON.serializeAsVector3()
  39348. ], ShadowLight.prototype, "direction", null);
  39349. __decorate([
  39350. BABYLON.serialize()
  39351. ], ShadowLight.prototype, "shadowMinZ", null);
  39352. __decorate([
  39353. BABYLON.serialize()
  39354. ], ShadowLight.prototype, "shadowMaxZ", null);
  39355. return ShadowLight;
  39356. }(BABYLON.Light));
  39357. BABYLON.ShadowLight = ShadowLight;
  39358. })(BABYLON || (BABYLON = {}));
  39359. //# sourceMappingURL=babylon.shadowLight.js.map
  39360. var BABYLON;
  39361. (function (BABYLON) {
  39362. var PointLight = /** @class */ (function (_super) {
  39363. __extends(PointLight, _super);
  39364. /**
  39365. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39366. * A PointLight emits the light in every direction.
  39367. * It can cast shadows.
  39368. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39369. * ```javascript
  39370. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39371. * ```
  39372. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39373. */
  39374. function PointLight(name, position, scene) {
  39375. var _this = _super.call(this, name, scene) || this;
  39376. _this._shadowAngle = Math.PI / 2;
  39377. _this.position = position;
  39378. return _this;
  39379. }
  39380. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39381. /**
  39382. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39383. * This specifies what angle the shadow will use to be created.
  39384. *
  39385. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39386. */
  39387. get: function () {
  39388. return this._shadowAngle;
  39389. },
  39390. /**
  39391. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39392. * This specifies what angle the shadow will use to be created.
  39393. *
  39394. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39395. */
  39396. set: function (value) {
  39397. this._shadowAngle = value;
  39398. this.forceProjectionMatrixCompute();
  39399. },
  39400. enumerable: true,
  39401. configurable: true
  39402. });
  39403. Object.defineProperty(PointLight.prototype, "direction", {
  39404. get: function () {
  39405. return this._direction;
  39406. },
  39407. /**
  39408. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39409. */
  39410. set: function (value) {
  39411. var previousNeedCube = this.needCube();
  39412. this._direction = value;
  39413. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39414. this._shadowGenerator.recreateShadowMap();
  39415. }
  39416. },
  39417. enumerable: true,
  39418. configurable: true
  39419. });
  39420. /**
  39421. * Returns the string "PointLight"
  39422. */
  39423. PointLight.prototype.getClassName = function () {
  39424. return "PointLight";
  39425. };
  39426. /**
  39427. * Returns the integer 0.
  39428. */
  39429. PointLight.prototype.getTypeID = function () {
  39430. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39431. };
  39432. /**
  39433. * Specifies wether or not the shadowmap should be a cube texture.
  39434. */
  39435. PointLight.prototype.needCube = function () {
  39436. return !this.direction;
  39437. };
  39438. /**
  39439. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39440. */
  39441. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39442. if (this.direction) {
  39443. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39444. }
  39445. else {
  39446. switch (faceIndex) {
  39447. case 0:
  39448. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39449. case 1:
  39450. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39451. case 2:
  39452. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39453. case 3:
  39454. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39455. case 4:
  39456. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39457. case 5:
  39458. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39459. }
  39460. }
  39461. return BABYLON.Vector3.Zero();
  39462. };
  39463. /**
  39464. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39465. * - fov = PI / 2
  39466. * - aspect ratio : 1.0
  39467. * - z-near and far equal to the active camera minZ and maxZ.
  39468. * Returns the PointLight.
  39469. */
  39470. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39471. var activeCamera = this.getScene().activeCamera;
  39472. if (!activeCamera) {
  39473. return;
  39474. }
  39475. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39476. };
  39477. PointLight.prototype._buildUniformLayout = function () {
  39478. this._uniformBuffer.addUniform("vLightData", 4);
  39479. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39480. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39481. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39482. this._uniformBuffer.addUniform("depthValues", 2);
  39483. this._uniformBuffer.create();
  39484. };
  39485. /**
  39486. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39487. * Returns the PointLight.
  39488. */
  39489. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39490. if (this.computeTransformedInformation()) {
  39491. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39492. return this;
  39493. }
  39494. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39495. return this;
  39496. };
  39497. __decorate([
  39498. BABYLON.serialize()
  39499. ], PointLight.prototype, "shadowAngle", null);
  39500. return PointLight;
  39501. }(BABYLON.ShadowLight));
  39502. BABYLON.PointLight = PointLight;
  39503. })(BABYLON || (BABYLON = {}));
  39504. //# sourceMappingURL=babylon.pointLight.js.map
  39505. var BABYLON;
  39506. (function (BABYLON) {
  39507. var DirectionalLight = /** @class */ (function (_super) {
  39508. __extends(DirectionalLight, _super);
  39509. /**
  39510. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39511. * The directional light is emitted from everywhere in the given direction.
  39512. * It can cast shawdows.
  39513. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39514. */
  39515. function DirectionalLight(name, direction, scene) {
  39516. var _this = _super.call(this, name, scene) || this;
  39517. _this._shadowFrustumSize = 0;
  39518. _this._shadowOrthoScale = 0.5;
  39519. _this.autoUpdateExtends = true;
  39520. // Cache
  39521. _this._orthoLeft = Number.MAX_VALUE;
  39522. _this._orthoRight = Number.MIN_VALUE;
  39523. _this._orthoTop = Number.MIN_VALUE;
  39524. _this._orthoBottom = Number.MAX_VALUE;
  39525. _this.position = direction.scale(-1.0);
  39526. _this.direction = direction;
  39527. return _this;
  39528. }
  39529. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39530. /**
  39531. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39532. */
  39533. get: function () {
  39534. return this._shadowFrustumSize;
  39535. },
  39536. /**
  39537. * Specifies a fix frustum size for the shadow generation.
  39538. */
  39539. set: function (value) {
  39540. this._shadowFrustumSize = value;
  39541. this.forceProjectionMatrixCompute();
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39547. get: function () {
  39548. return this._shadowOrthoScale;
  39549. },
  39550. set: function (value) {
  39551. this._shadowOrthoScale = value;
  39552. this.forceProjectionMatrixCompute();
  39553. },
  39554. enumerable: true,
  39555. configurable: true
  39556. });
  39557. /**
  39558. * Returns the string "DirectionalLight".
  39559. */
  39560. DirectionalLight.prototype.getClassName = function () {
  39561. return "DirectionalLight";
  39562. };
  39563. /**
  39564. * Returns the integer 1.
  39565. */
  39566. DirectionalLight.prototype.getTypeID = function () {
  39567. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39568. };
  39569. /**
  39570. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39571. * Returns the DirectionalLight Shadow projection matrix.
  39572. */
  39573. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39574. if (this.shadowFrustumSize > 0) {
  39575. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39576. }
  39577. else {
  39578. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39579. }
  39580. };
  39581. /**
  39582. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39583. * Returns the DirectionalLight Shadow projection matrix.
  39584. */
  39585. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39586. var activeCamera = this.getScene().activeCamera;
  39587. if (!activeCamera) {
  39588. return;
  39589. }
  39590. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39591. };
  39592. /**
  39593. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39594. * Returns the DirectionalLight Shadow projection matrix.
  39595. */
  39596. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39597. var activeCamera = this.getScene().activeCamera;
  39598. if (!activeCamera) {
  39599. return;
  39600. }
  39601. // Check extends
  39602. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39603. var tempVector3 = BABYLON.Vector3.Zero();
  39604. this._orthoLeft = Number.MAX_VALUE;
  39605. this._orthoRight = Number.MIN_VALUE;
  39606. this._orthoTop = Number.MIN_VALUE;
  39607. this._orthoBottom = Number.MAX_VALUE;
  39608. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39609. var mesh = renderList[meshIndex];
  39610. if (!mesh) {
  39611. continue;
  39612. }
  39613. var boundingInfo = mesh.getBoundingInfo();
  39614. if (!boundingInfo) {
  39615. continue;
  39616. }
  39617. var boundingBox = boundingInfo.boundingBox;
  39618. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39619. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39620. if (tempVector3.x < this._orthoLeft)
  39621. this._orthoLeft = tempVector3.x;
  39622. if (tempVector3.y < this._orthoBottom)
  39623. this._orthoBottom = tempVector3.y;
  39624. if (tempVector3.x > this._orthoRight)
  39625. this._orthoRight = tempVector3.x;
  39626. if (tempVector3.y > this._orthoTop)
  39627. this._orthoTop = tempVector3.y;
  39628. }
  39629. }
  39630. }
  39631. var xOffset = this._orthoRight - this._orthoLeft;
  39632. var yOffset = this._orthoTop - this._orthoBottom;
  39633. 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);
  39634. };
  39635. DirectionalLight.prototype._buildUniformLayout = function () {
  39636. this._uniformBuffer.addUniform("vLightData", 4);
  39637. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39638. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39639. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39640. this._uniformBuffer.addUniform("depthValues", 2);
  39641. this._uniformBuffer.create();
  39642. };
  39643. /**
  39644. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39645. * Returns the DirectionalLight.
  39646. */
  39647. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39648. if (this.computeTransformedInformation()) {
  39649. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39650. return this;
  39651. }
  39652. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39653. return this;
  39654. };
  39655. /**
  39656. * Gets the minZ used for shadow according to both the scene and the light.
  39657. *
  39658. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39659. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39660. * @param activeCamera
  39661. */
  39662. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39663. return 1;
  39664. };
  39665. /**
  39666. * Gets the maxZ used for shadow according to both the scene and the light.
  39667. *
  39668. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39669. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39670. * @param activeCamera
  39671. */
  39672. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39673. return 1;
  39674. };
  39675. __decorate([
  39676. BABYLON.serialize()
  39677. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39678. __decorate([
  39679. BABYLON.serialize()
  39680. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39681. __decorate([
  39682. BABYLON.serialize()
  39683. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39684. return DirectionalLight;
  39685. }(BABYLON.ShadowLight));
  39686. BABYLON.DirectionalLight = DirectionalLight;
  39687. })(BABYLON || (BABYLON = {}));
  39688. //# sourceMappingURL=babylon.directionalLight.js.map
  39689. var BABYLON;
  39690. (function (BABYLON) {
  39691. var SpotLight = /** @class */ (function (_super) {
  39692. __extends(SpotLight, _super);
  39693. /**
  39694. * Creates a SpotLight object in the scene with the passed parameters :
  39695. * - `position` (Vector3) is the initial SpotLight position,
  39696. * - `direction` (Vector3) is the initial SpotLight direction,
  39697. * - `angle` (float, in radians) is the spot light cone angle,
  39698. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39699. * A spot light is a simply light oriented cone.
  39700. * It can cast shadows.
  39701. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39702. */
  39703. function SpotLight(name, position, direction, angle, exponent, scene) {
  39704. var _this = _super.call(this, name, scene) || this;
  39705. _this.position = position;
  39706. _this.direction = direction;
  39707. _this.angle = angle;
  39708. _this.exponent = exponent;
  39709. return _this;
  39710. }
  39711. Object.defineProperty(SpotLight.prototype, "angle", {
  39712. get: function () {
  39713. return this._angle;
  39714. },
  39715. set: function (value) {
  39716. this._angle = value;
  39717. this.forceProjectionMatrixCompute();
  39718. },
  39719. enumerable: true,
  39720. configurable: true
  39721. });
  39722. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39723. get: function () {
  39724. return this._shadowAngleScale;
  39725. },
  39726. /**
  39727. * Allows scaling the angle of the light for shadow generation only.
  39728. */
  39729. set: function (value) {
  39730. this._shadowAngleScale = value;
  39731. this.forceProjectionMatrixCompute();
  39732. },
  39733. enumerable: true,
  39734. configurable: true
  39735. });
  39736. /**
  39737. * Returns the string "SpotLight".
  39738. */
  39739. SpotLight.prototype.getClassName = function () {
  39740. return "SpotLight";
  39741. };
  39742. /**
  39743. * Returns the integer 2.
  39744. */
  39745. SpotLight.prototype.getTypeID = function () {
  39746. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39747. };
  39748. /**
  39749. * 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.
  39750. * Returns the SpotLight.
  39751. */
  39752. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39753. var activeCamera = this.getScene().activeCamera;
  39754. if (!activeCamera) {
  39755. return;
  39756. }
  39757. this._shadowAngleScale = this._shadowAngleScale || 1;
  39758. var angle = this._shadowAngleScale * this._angle;
  39759. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39760. };
  39761. SpotLight.prototype._buildUniformLayout = function () {
  39762. this._uniformBuffer.addUniform("vLightData", 4);
  39763. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39764. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39765. this._uniformBuffer.addUniform("vLightDirection", 3);
  39766. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39767. this._uniformBuffer.addUniform("depthValues", 2);
  39768. this._uniformBuffer.create();
  39769. };
  39770. /**
  39771. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39772. * Return the SpotLight.
  39773. */
  39774. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39775. var normalizeDirection;
  39776. if (this.computeTransformedInformation()) {
  39777. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39778. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39779. }
  39780. else {
  39781. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39782. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39783. }
  39784. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39785. return this;
  39786. };
  39787. __decorate([
  39788. BABYLON.serialize()
  39789. ], SpotLight.prototype, "angle", null);
  39790. __decorate([
  39791. BABYLON.serialize()
  39792. /**
  39793. * Allows scaling the angle of the light for shadow generation only.
  39794. */
  39795. ], SpotLight.prototype, "shadowAngleScale", null);
  39796. __decorate([
  39797. BABYLON.serialize()
  39798. ], SpotLight.prototype, "exponent", void 0);
  39799. return SpotLight;
  39800. }(BABYLON.ShadowLight));
  39801. BABYLON.SpotLight = SpotLight;
  39802. })(BABYLON || (BABYLON = {}));
  39803. //# sourceMappingURL=babylon.spotLight.js.map
  39804. var BABYLON;
  39805. (function (BABYLON) {
  39806. var AnimationRange = /** @class */ (function () {
  39807. function AnimationRange(name, from, to) {
  39808. this.name = name;
  39809. this.from = from;
  39810. this.to = to;
  39811. }
  39812. AnimationRange.prototype.clone = function () {
  39813. return new AnimationRange(this.name, this.from, this.to);
  39814. };
  39815. return AnimationRange;
  39816. }());
  39817. BABYLON.AnimationRange = AnimationRange;
  39818. /**
  39819. * Composed of a frame, and an action function
  39820. */
  39821. var AnimationEvent = /** @class */ (function () {
  39822. function AnimationEvent(frame, action, onlyOnce) {
  39823. this.frame = frame;
  39824. this.action = action;
  39825. this.onlyOnce = onlyOnce;
  39826. this.isDone = false;
  39827. }
  39828. return AnimationEvent;
  39829. }());
  39830. BABYLON.AnimationEvent = AnimationEvent;
  39831. var PathCursor = /** @class */ (function () {
  39832. function PathCursor(path) {
  39833. this.path = path;
  39834. this._onchange = new Array();
  39835. this.value = 0;
  39836. this.animations = new Array();
  39837. }
  39838. PathCursor.prototype.getPoint = function () {
  39839. var point = this.path.getPointAtLengthPosition(this.value);
  39840. return new BABYLON.Vector3(point.x, 0, point.y);
  39841. };
  39842. PathCursor.prototype.moveAhead = function (step) {
  39843. if (step === void 0) { step = 0.002; }
  39844. this.move(step);
  39845. return this;
  39846. };
  39847. PathCursor.prototype.moveBack = function (step) {
  39848. if (step === void 0) { step = 0.002; }
  39849. this.move(-step);
  39850. return this;
  39851. };
  39852. PathCursor.prototype.move = function (step) {
  39853. if (Math.abs(step) > 1) {
  39854. throw "step size should be less than 1.";
  39855. }
  39856. this.value += step;
  39857. this.ensureLimits();
  39858. this.raiseOnChange();
  39859. return this;
  39860. };
  39861. PathCursor.prototype.ensureLimits = function () {
  39862. while (this.value > 1) {
  39863. this.value -= 1;
  39864. }
  39865. while (this.value < 0) {
  39866. this.value += 1;
  39867. }
  39868. return this;
  39869. };
  39870. // used by animation engine
  39871. PathCursor.prototype.raiseOnChange = function () {
  39872. var _this = this;
  39873. this._onchange.forEach(function (f) { return f(_this); });
  39874. return this;
  39875. };
  39876. PathCursor.prototype.onchange = function (f) {
  39877. this._onchange.push(f);
  39878. return this;
  39879. };
  39880. return PathCursor;
  39881. }());
  39882. BABYLON.PathCursor = PathCursor;
  39883. var Animation = /** @class */ (function () {
  39884. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39885. this.name = name;
  39886. this.targetProperty = targetProperty;
  39887. this.framePerSecond = framePerSecond;
  39888. this.dataType = dataType;
  39889. this.loopMode = loopMode;
  39890. this.enableBlending = enableBlending;
  39891. this._runtimeAnimations = new Array();
  39892. // The set of event that will be linked to this animation
  39893. this._events = new Array();
  39894. this.blendingSpeed = 0.01;
  39895. this._ranges = {};
  39896. this.targetPropertyPath = targetProperty.split(".");
  39897. this.dataType = dataType;
  39898. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39899. }
  39900. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39901. var dataType = undefined;
  39902. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39903. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39904. }
  39905. else if (from instanceof BABYLON.Quaternion) {
  39906. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39907. }
  39908. else if (from instanceof BABYLON.Vector3) {
  39909. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39910. }
  39911. else if (from instanceof BABYLON.Vector2) {
  39912. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39913. }
  39914. else if (from instanceof BABYLON.Color3) {
  39915. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39916. }
  39917. else if (from instanceof BABYLON.Size) {
  39918. dataType = Animation.ANIMATIONTYPE_SIZE;
  39919. }
  39920. if (dataType == undefined) {
  39921. return null;
  39922. }
  39923. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39924. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39925. animation.setKeys(keys);
  39926. if (easingFunction !== undefined) {
  39927. animation.setEasingFunction(easingFunction);
  39928. }
  39929. return animation;
  39930. };
  39931. /**
  39932. * Sets up an animation.
  39933. * @param property the property to animate
  39934. * @param animationType the animation type to apply
  39935. * @param easingFunction the easing function used in the animation
  39936. * @returns The created animation
  39937. */
  39938. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39939. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39940. animation.setEasingFunction(easingFunction);
  39941. return animation;
  39942. };
  39943. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39944. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39945. if (!animation) {
  39946. return null;
  39947. }
  39948. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39949. };
  39950. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39951. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39952. if (!animation) {
  39953. return null;
  39954. }
  39955. node.animations.push(animation);
  39956. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39957. };
  39958. /**
  39959. * Transition property of the Camera to the target Value.
  39960. * @param property The property to transition
  39961. * @param targetValue The target Value of the property
  39962. * @param host The object where the property to animate belongs
  39963. * @param scene Scene used to run the animation
  39964. * @param frameRate Framerate (in frame/s) to use
  39965. * @param transition The transition type we want to use
  39966. * @param duration The duration of the animation, in milliseconds
  39967. * @param onAnimationEnd Call back trigger at the end of the animation.
  39968. */
  39969. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39970. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39971. if (duration <= 0) {
  39972. host[property] = targetValue;
  39973. if (onAnimationEnd) {
  39974. onAnimationEnd();
  39975. }
  39976. return null;
  39977. }
  39978. var endFrame = frameRate * (duration / 1000);
  39979. transition.setKeys([{
  39980. frame: 0,
  39981. value: host[property].clone ? host[property].clone() : host[property]
  39982. },
  39983. {
  39984. frame: endFrame,
  39985. value: targetValue
  39986. }]);
  39987. if (!host.animations) {
  39988. host.animations = [];
  39989. }
  39990. host.animations.push(transition);
  39991. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39992. animation.onAnimationEnd = onAnimationEnd;
  39993. return animation;
  39994. };
  39995. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39996. /**
  39997. * Return the array of runtime animations currently using this animation
  39998. */
  39999. get: function () {
  40000. return this._runtimeAnimations;
  40001. },
  40002. enumerable: true,
  40003. configurable: true
  40004. });
  40005. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40006. get: function () {
  40007. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40008. var runtimeAnimation = _a[_i];
  40009. if (!runtimeAnimation.isStopped) {
  40010. return true;
  40011. }
  40012. }
  40013. return false;
  40014. },
  40015. enumerable: true,
  40016. configurable: true
  40017. });
  40018. // Methods
  40019. /**
  40020. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40021. */
  40022. Animation.prototype.toString = function (fullDetails) {
  40023. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40024. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40025. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40026. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40027. if (fullDetails) {
  40028. ret += ", Ranges: {";
  40029. var first = true;
  40030. for (var name in this._ranges) {
  40031. if (first) {
  40032. ret += ", ";
  40033. first = false;
  40034. }
  40035. ret += name;
  40036. }
  40037. ret += "}";
  40038. }
  40039. return ret;
  40040. };
  40041. /**
  40042. * Add an event to this animation.
  40043. */
  40044. Animation.prototype.addEvent = function (event) {
  40045. this._events.push(event);
  40046. };
  40047. /**
  40048. * Remove all events found at the given frame
  40049. * @param frame
  40050. */
  40051. Animation.prototype.removeEvents = function (frame) {
  40052. for (var index = 0; index < this._events.length; index++) {
  40053. if (this._events[index].frame === frame) {
  40054. this._events.splice(index, 1);
  40055. index--;
  40056. }
  40057. }
  40058. };
  40059. Animation.prototype.getEvents = function () {
  40060. return this._events;
  40061. };
  40062. Animation.prototype.createRange = function (name, from, to) {
  40063. // check name not already in use; could happen for bones after serialized
  40064. if (!this._ranges[name]) {
  40065. this._ranges[name] = new AnimationRange(name, from, to);
  40066. }
  40067. };
  40068. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40069. if (deleteFrames === void 0) { deleteFrames = true; }
  40070. var range = this._ranges[name];
  40071. if (!range) {
  40072. return;
  40073. }
  40074. if (deleteFrames) {
  40075. var from = range.from;
  40076. var to = range.to;
  40077. // this loop MUST go high to low for multiple splices to work
  40078. for (var key = this._keys.length - 1; key >= 0; key--) {
  40079. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40080. this._keys.splice(key, 1);
  40081. }
  40082. }
  40083. }
  40084. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40085. };
  40086. Animation.prototype.getRange = function (name) {
  40087. return this._ranges[name];
  40088. };
  40089. Animation.prototype.getKeys = function () {
  40090. return this._keys;
  40091. };
  40092. Animation.prototype.getHighestFrame = function () {
  40093. var ret = 0;
  40094. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40095. if (ret < this._keys[key].frame) {
  40096. ret = this._keys[key].frame;
  40097. }
  40098. }
  40099. return ret;
  40100. };
  40101. Animation.prototype.getEasingFunction = function () {
  40102. return this._easingFunction;
  40103. };
  40104. Animation.prototype.setEasingFunction = function (easingFunction) {
  40105. this._easingFunction = easingFunction;
  40106. };
  40107. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40108. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40109. };
  40110. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40111. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40112. };
  40113. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40114. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40115. };
  40116. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40117. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40118. };
  40119. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40120. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40121. };
  40122. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40123. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40124. };
  40125. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40126. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40127. };
  40128. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40129. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40130. };
  40131. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40132. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40133. };
  40134. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40135. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40136. };
  40137. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40138. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40139. };
  40140. Animation.prototype.clone = function () {
  40141. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40142. clone.enableBlending = this.enableBlending;
  40143. clone.blendingSpeed = this.blendingSpeed;
  40144. if (this._keys) {
  40145. clone.setKeys(this._keys);
  40146. }
  40147. if (this._ranges) {
  40148. clone._ranges = {};
  40149. for (var name in this._ranges) {
  40150. var range = this._ranges[name];
  40151. if (!range) {
  40152. continue;
  40153. }
  40154. clone._ranges[name] = range.clone();
  40155. }
  40156. }
  40157. return clone;
  40158. };
  40159. Animation.prototype.setKeys = function (values) {
  40160. this._keys = values.slice(0);
  40161. };
  40162. Animation.prototype.serialize = function () {
  40163. var serializationObject = {};
  40164. serializationObject.name = this.name;
  40165. serializationObject.property = this.targetProperty;
  40166. serializationObject.framePerSecond = this.framePerSecond;
  40167. serializationObject.dataType = this.dataType;
  40168. serializationObject.loopBehavior = this.loopMode;
  40169. serializationObject.enableBlending = this.enableBlending;
  40170. serializationObject.blendingSpeed = this.blendingSpeed;
  40171. var dataType = this.dataType;
  40172. serializationObject.keys = [];
  40173. var keys = this.getKeys();
  40174. for (var index = 0; index < keys.length; index++) {
  40175. var animationKey = keys[index];
  40176. var key = {};
  40177. key.frame = animationKey.frame;
  40178. switch (dataType) {
  40179. case Animation.ANIMATIONTYPE_FLOAT:
  40180. key.values = [animationKey.value];
  40181. break;
  40182. case Animation.ANIMATIONTYPE_QUATERNION:
  40183. case Animation.ANIMATIONTYPE_MATRIX:
  40184. case Animation.ANIMATIONTYPE_VECTOR3:
  40185. case Animation.ANIMATIONTYPE_COLOR3:
  40186. key.values = animationKey.value.asArray();
  40187. break;
  40188. }
  40189. serializationObject.keys.push(key);
  40190. }
  40191. serializationObject.ranges = [];
  40192. for (var name in this._ranges) {
  40193. var source = this._ranges[name];
  40194. if (!source) {
  40195. continue;
  40196. }
  40197. var range = {};
  40198. range.name = name;
  40199. range.from = source.from;
  40200. range.to = source.to;
  40201. serializationObject.ranges.push(range);
  40202. }
  40203. return serializationObject;
  40204. };
  40205. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40206. get: function () {
  40207. return Animation._ANIMATIONTYPE_FLOAT;
  40208. },
  40209. enumerable: true,
  40210. configurable: true
  40211. });
  40212. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40213. get: function () {
  40214. return Animation._ANIMATIONTYPE_VECTOR3;
  40215. },
  40216. enumerable: true,
  40217. configurable: true
  40218. });
  40219. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40220. get: function () {
  40221. return Animation._ANIMATIONTYPE_VECTOR2;
  40222. },
  40223. enumerable: true,
  40224. configurable: true
  40225. });
  40226. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40227. get: function () {
  40228. return Animation._ANIMATIONTYPE_SIZE;
  40229. },
  40230. enumerable: true,
  40231. configurable: true
  40232. });
  40233. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40234. get: function () {
  40235. return Animation._ANIMATIONTYPE_QUATERNION;
  40236. },
  40237. enumerable: true,
  40238. configurable: true
  40239. });
  40240. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40241. get: function () {
  40242. return Animation._ANIMATIONTYPE_MATRIX;
  40243. },
  40244. enumerable: true,
  40245. configurable: true
  40246. });
  40247. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40248. get: function () {
  40249. return Animation._ANIMATIONTYPE_COLOR3;
  40250. },
  40251. enumerable: true,
  40252. configurable: true
  40253. });
  40254. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40255. get: function () {
  40256. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40262. get: function () {
  40263. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40264. },
  40265. enumerable: true,
  40266. configurable: true
  40267. });
  40268. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40269. get: function () {
  40270. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40271. },
  40272. enumerable: true,
  40273. configurable: true
  40274. });
  40275. Animation.Parse = function (parsedAnimation) {
  40276. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40277. var dataType = parsedAnimation.dataType;
  40278. var keys = [];
  40279. var data;
  40280. var index;
  40281. if (parsedAnimation.enableBlending) {
  40282. animation.enableBlending = parsedAnimation.enableBlending;
  40283. }
  40284. if (parsedAnimation.blendingSpeed) {
  40285. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40286. }
  40287. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40288. var key = parsedAnimation.keys[index];
  40289. var inTangent;
  40290. var outTangent;
  40291. switch (dataType) {
  40292. case Animation.ANIMATIONTYPE_FLOAT:
  40293. data = key.values[0];
  40294. if (key.values.length >= 1) {
  40295. inTangent = key.values[1];
  40296. }
  40297. if (key.values.length >= 2) {
  40298. outTangent = key.values[2];
  40299. }
  40300. break;
  40301. case Animation.ANIMATIONTYPE_QUATERNION:
  40302. data = BABYLON.Quaternion.FromArray(key.values);
  40303. if (key.values.length >= 8) {
  40304. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40305. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40306. inTangent = _inTangent;
  40307. }
  40308. }
  40309. if (key.values.length >= 12) {
  40310. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40311. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40312. outTangent = _outTangent;
  40313. }
  40314. }
  40315. break;
  40316. case Animation.ANIMATIONTYPE_MATRIX:
  40317. data = BABYLON.Matrix.FromArray(key.values);
  40318. break;
  40319. case Animation.ANIMATIONTYPE_COLOR3:
  40320. data = BABYLON.Color3.FromArray(key.values);
  40321. break;
  40322. case Animation.ANIMATIONTYPE_VECTOR3:
  40323. default:
  40324. data = BABYLON.Vector3.FromArray(key.values);
  40325. break;
  40326. }
  40327. var keyData = {};
  40328. keyData.frame = key.frame;
  40329. keyData.value = data;
  40330. if (inTangent != undefined) {
  40331. keyData.inTangent = inTangent;
  40332. }
  40333. if (outTangent != undefined) {
  40334. keyData.outTangent = outTangent;
  40335. }
  40336. keys.push(keyData);
  40337. }
  40338. animation.setKeys(keys);
  40339. if (parsedAnimation.ranges) {
  40340. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40341. data = parsedAnimation.ranges[index];
  40342. animation.createRange(data.name, data.from, data.to);
  40343. }
  40344. }
  40345. return animation;
  40346. };
  40347. Animation.AppendSerializedAnimations = function (source, destination) {
  40348. if (source.animations) {
  40349. destination.animations = [];
  40350. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40351. var animation = source.animations[animationIndex];
  40352. destination.animations.push(animation.serialize());
  40353. }
  40354. }
  40355. };
  40356. Animation.AllowMatricesInterpolation = false;
  40357. // Statics
  40358. Animation._ANIMATIONTYPE_FLOAT = 0;
  40359. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40360. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40361. Animation._ANIMATIONTYPE_MATRIX = 3;
  40362. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40363. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40364. Animation._ANIMATIONTYPE_SIZE = 6;
  40365. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40366. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40367. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40368. return Animation;
  40369. }());
  40370. BABYLON.Animation = Animation;
  40371. })(BABYLON || (BABYLON = {}));
  40372. //# sourceMappingURL=babylon.animation.js.map
  40373. var BABYLON;
  40374. (function (BABYLON) {
  40375. var RuntimeAnimation = /** @class */ (function () {
  40376. function RuntimeAnimation(target, animation) {
  40377. this._offsetsCache = {};
  40378. this._highLimitsCache = {};
  40379. this._stopped = false;
  40380. this._blendingFactor = 0;
  40381. this._ratioOffset = 0;
  40382. this._animation = animation;
  40383. this._target = target;
  40384. animation._runtimeAnimations.push(this);
  40385. }
  40386. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40387. get: function () {
  40388. return this._animation;
  40389. },
  40390. enumerable: true,
  40391. configurable: true
  40392. });
  40393. RuntimeAnimation.prototype.reset = function () {
  40394. this._offsetsCache = {};
  40395. this._highLimitsCache = {};
  40396. this.currentFrame = 0;
  40397. this._blendingFactor = 0;
  40398. this._originalBlendValue = null;
  40399. };
  40400. RuntimeAnimation.prototype.isStopped = function () {
  40401. return this._stopped;
  40402. };
  40403. RuntimeAnimation.prototype.dispose = function () {
  40404. var index = this._animation.runtimeAnimations.indexOf(this);
  40405. if (index > -1) {
  40406. this._animation.runtimeAnimations.splice(index, 1);
  40407. }
  40408. };
  40409. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40410. if (typeof value === "function") {
  40411. return value();
  40412. }
  40413. return value;
  40414. };
  40415. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40416. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40417. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40418. }
  40419. this.currentFrame = currentFrame;
  40420. var keys = this._animation.getKeys();
  40421. // Try to get a hash to find the right key
  40422. 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));
  40423. if (keys[startKeyIndex].frame >= currentFrame) {
  40424. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40425. startKeyIndex--;
  40426. }
  40427. }
  40428. for (var key = startKeyIndex; key < keys.length; key++) {
  40429. var endKey = keys[key + 1];
  40430. if (endKey.frame >= currentFrame) {
  40431. var startKey = keys[key];
  40432. var startValue = this._getKeyValue(startKey.value);
  40433. var endValue = this._getKeyValue(endKey.value);
  40434. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40435. var frameDelta = endKey.frame - startKey.frame;
  40436. // gradient : percent of currentFrame between the frame inf and the frame sup
  40437. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40438. // check for easingFunction and correction of gradient
  40439. var easingFunction = this._animation.getEasingFunction();
  40440. if (easingFunction != null) {
  40441. gradient = easingFunction.ease(gradient);
  40442. }
  40443. switch (this._animation.dataType) {
  40444. // Float
  40445. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40446. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40447. switch (loopMode) {
  40448. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40449. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40450. return floatValue;
  40451. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40452. return offsetValue * repeatCount + floatValue;
  40453. }
  40454. break;
  40455. // Quaternion
  40456. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40457. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40458. switch (loopMode) {
  40459. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40460. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40461. return quatValue;
  40462. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40463. return quatValue.add(offsetValue.scale(repeatCount));
  40464. }
  40465. return quatValue;
  40466. // Vector3
  40467. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40468. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40469. switch (loopMode) {
  40470. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40471. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40472. return vec3Value;
  40473. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40474. return vec3Value.add(offsetValue.scale(repeatCount));
  40475. }
  40476. // Vector2
  40477. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40478. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40479. switch (loopMode) {
  40480. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40481. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40482. return vec2Value;
  40483. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40484. return vec2Value.add(offsetValue.scale(repeatCount));
  40485. }
  40486. // Size
  40487. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40488. switch (loopMode) {
  40489. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40490. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40491. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40492. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40493. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40494. }
  40495. // Color3
  40496. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40497. switch (loopMode) {
  40498. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40499. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40500. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40501. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40502. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40503. }
  40504. // Matrix
  40505. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40506. switch (loopMode) {
  40507. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40508. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40509. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40510. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40511. }
  40512. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40513. return startValue;
  40514. }
  40515. default:
  40516. break;
  40517. }
  40518. break;
  40519. }
  40520. }
  40521. return this._getKeyValue(keys[keys.length - 1].value);
  40522. };
  40523. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40524. if (blend === void 0) { blend = false; }
  40525. // Set value
  40526. var path;
  40527. var destination;
  40528. var targetPropertyPath = this._animation.targetPropertyPath;
  40529. if (targetPropertyPath.length > 1) {
  40530. var property = this._target[targetPropertyPath[0]];
  40531. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40532. property = property[targetPropertyPath[index]];
  40533. }
  40534. path = targetPropertyPath[targetPropertyPath.length - 1];
  40535. destination = property;
  40536. }
  40537. else {
  40538. path = targetPropertyPath[0];
  40539. destination = this._target;
  40540. }
  40541. // Blending
  40542. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40543. if (!this._originalBlendValue) {
  40544. if (destination[path].clone) {
  40545. this._originalBlendValue = destination[path].clone();
  40546. }
  40547. else {
  40548. this._originalBlendValue = destination[path];
  40549. }
  40550. }
  40551. if (this._originalBlendValue.prototype) {
  40552. if (this._originalBlendValue.prototype.Lerp) {
  40553. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40554. }
  40555. else {
  40556. destination[path] = currentValue;
  40557. }
  40558. }
  40559. else if (this._originalBlendValue.m) {
  40560. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40561. }
  40562. else {
  40563. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40564. }
  40565. this._blendingFactor += this._animation.blendingSpeed;
  40566. }
  40567. else {
  40568. destination[path] = currentValue;
  40569. }
  40570. if (this._target.markAsDirty) {
  40571. this._target.markAsDirty(this._animation.targetProperty);
  40572. }
  40573. };
  40574. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40575. var keys = this._animation.getKeys();
  40576. if (frame < keys[0].frame) {
  40577. frame = keys[0].frame;
  40578. }
  40579. else if (frame > keys[keys.length - 1].frame) {
  40580. frame = keys[keys.length - 1].frame;
  40581. }
  40582. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40583. this.setValue(currentValue);
  40584. };
  40585. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40586. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40587. this._ratioOffset = this._previousRatio - newRatio;
  40588. };
  40589. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40590. if (blend === void 0) { blend = false; }
  40591. var targetPropertyPath = this._animation.targetPropertyPath;
  40592. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40593. this._stopped = true;
  40594. return false;
  40595. }
  40596. var returnValue = true;
  40597. var keys = this._animation.getKeys();
  40598. // Adding a start key at frame 0 if missing
  40599. if (keys[0].frame !== 0) {
  40600. var newKey = { frame: 0, value: keys[0].value };
  40601. keys.splice(0, 0, newKey);
  40602. }
  40603. // Check limits
  40604. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40605. from = keys[0].frame;
  40606. }
  40607. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40608. to = keys[keys.length - 1].frame;
  40609. }
  40610. //to and from cannot be the same key
  40611. if (from === to) {
  40612. if (from > keys[0].frame) {
  40613. from--;
  40614. }
  40615. else if (to < keys[keys.length - 1].frame) {
  40616. to++;
  40617. }
  40618. }
  40619. // Compute ratio
  40620. var range = to - from;
  40621. var offsetValue;
  40622. // ratio represents the frame delta between from and to
  40623. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40624. var highLimitValue = 0;
  40625. this._previousDelay = delay;
  40626. this._previousRatio = ratio;
  40627. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40628. returnValue = false;
  40629. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40630. }
  40631. else {
  40632. // Get max value if required
  40633. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40634. var keyOffset = to.toString() + from.toString();
  40635. if (!this._offsetsCache[keyOffset]) {
  40636. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40637. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40638. switch (this._animation.dataType) {
  40639. // Float
  40640. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40641. this._offsetsCache[keyOffset] = toValue - fromValue;
  40642. break;
  40643. // Quaternion
  40644. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40645. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40646. break;
  40647. // Vector3
  40648. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40649. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40650. // Vector2
  40651. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40652. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40653. // Size
  40654. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40655. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40656. // Color3
  40657. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40658. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40659. default:
  40660. break;
  40661. }
  40662. this._highLimitsCache[keyOffset] = toValue;
  40663. }
  40664. highLimitValue = this._highLimitsCache[keyOffset];
  40665. offsetValue = this._offsetsCache[keyOffset];
  40666. }
  40667. }
  40668. if (offsetValue === undefined) {
  40669. switch (this._animation.dataType) {
  40670. // Float
  40671. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40672. offsetValue = 0;
  40673. break;
  40674. // Quaternion
  40675. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40676. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40677. break;
  40678. // Vector3
  40679. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40680. offsetValue = BABYLON.Vector3.Zero();
  40681. break;
  40682. // Vector2
  40683. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40684. offsetValue = BABYLON.Vector2.Zero();
  40685. break;
  40686. // Size
  40687. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40688. offsetValue = BABYLON.Size.Zero();
  40689. break;
  40690. // Color3
  40691. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40692. offsetValue = BABYLON.Color3.Black();
  40693. }
  40694. }
  40695. // Compute value
  40696. var repeatCount = (ratio / range) >> 0;
  40697. var currentFrame = returnValue ? from + ratio % range : to;
  40698. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40699. // Set value
  40700. this.setValue(currentValue);
  40701. // Check events
  40702. var events = this._animation.getEvents();
  40703. for (var index = 0; index < events.length; index++) {
  40704. // Make sure current frame has passed event frame and that event frame is within the current range
  40705. // Also, handle both forward and reverse animations
  40706. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40707. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40708. var event = events[index];
  40709. if (!event.isDone) {
  40710. // If event should be done only once, remove it.
  40711. if (event.onlyOnce) {
  40712. events.splice(index, 1);
  40713. index--;
  40714. }
  40715. event.isDone = true;
  40716. event.action();
  40717. } // Don't do anything if the event has already be done.
  40718. }
  40719. else if (events[index].isDone && !events[index].onlyOnce) {
  40720. // reset event, the animation is looping
  40721. events[index].isDone = false;
  40722. }
  40723. }
  40724. if (!returnValue) {
  40725. this._stopped = true;
  40726. }
  40727. return returnValue;
  40728. };
  40729. return RuntimeAnimation;
  40730. }());
  40731. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40732. })(BABYLON || (BABYLON = {}));
  40733. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40734. var BABYLON;
  40735. (function (BABYLON) {
  40736. var Animatable = /** @class */ (function () {
  40737. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40738. if (fromFrame === void 0) { fromFrame = 0; }
  40739. if (toFrame === void 0) { toFrame = 100; }
  40740. if (loopAnimation === void 0) { loopAnimation = false; }
  40741. if (speedRatio === void 0) { speedRatio = 1.0; }
  40742. this.target = target;
  40743. this.fromFrame = fromFrame;
  40744. this.toFrame = toFrame;
  40745. this.loopAnimation = loopAnimation;
  40746. this.onAnimationEnd = onAnimationEnd;
  40747. this._localDelayOffset = null;
  40748. this._pausedDelay = null;
  40749. this._runtimeAnimations = new Array();
  40750. this._paused = false;
  40751. this._speedRatio = 1;
  40752. this.animationStarted = false;
  40753. if (animations) {
  40754. this.appendAnimations(target, animations);
  40755. }
  40756. this._speedRatio = speedRatio;
  40757. this._scene = scene;
  40758. scene._activeAnimatables.push(this);
  40759. }
  40760. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40761. get: function () {
  40762. return this._speedRatio;
  40763. },
  40764. set: function (value) {
  40765. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40766. var animation = this._runtimeAnimations[index];
  40767. animation._prepareForSpeedRatioChange(value);
  40768. }
  40769. this._speedRatio = value;
  40770. },
  40771. enumerable: true,
  40772. configurable: true
  40773. });
  40774. // Methods
  40775. Animatable.prototype.getAnimations = function () {
  40776. return this._runtimeAnimations;
  40777. };
  40778. Animatable.prototype.appendAnimations = function (target, animations) {
  40779. for (var index = 0; index < animations.length; index++) {
  40780. var animation = animations[index];
  40781. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40782. }
  40783. };
  40784. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40785. var runtimeAnimations = this._runtimeAnimations;
  40786. for (var index = 0; index < runtimeAnimations.length; index++) {
  40787. if (runtimeAnimations[index].animation.targetProperty === property) {
  40788. return runtimeAnimations[index].animation;
  40789. }
  40790. }
  40791. return null;
  40792. };
  40793. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40794. var runtimeAnimations = this._runtimeAnimations;
  40795. for (var index = 0; index < runtimeAnimations.length; index++) {
  40796. if (runtimeAnimations[index].animation.targetProperty === property) {
  40797. return runtimeAnimations[index];
  40798. }
  40799. }
  40800. return null;
  40801. };
  40802. Animatable.prototype.reset = function () {
  40803. var runtimeAnimations = this._runtimeAnimations;
  40804. for (var index = 0; index < runtimeAnimations.length; index++) {
  40805. runtimeAnimations[index].reset();
  40806. }
  40807. this._localDelayOffset = null;
  40808. this._pausedDelay = null;
  40809. };
  40810. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40811. var runtimeAnimations = this._runtimeAnimations;
  40812. for (var index = 0; index < runtimeAnimations.length; index++) {
  40813. runtimeAnimations[index].animation.enableBlending = true;
  40814. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40815. }
  40816. };
  40817. Animatable.prototype.disableBlending = function () {
  40818. var runtimeAnimations = this._runtimeAnimations;
  40819. for (var index = 0; index < runtimeAnimations.length; index++) {
  40820. runtimeAnimations[index].animation.enableBlending = false;
  40821. }
  40822. };
  40823. Animatable.prototype.goToFrame = function (frame) {
  40824. var runtimeAnimations = this._runtimeAnimations;
  40825. if (runtimeAnimations[0]) {
  40826. var fps = runtimeAnimations[0].animation.framePerSecond;
  40827. var currentFrame = runtimeAnimations[0].currentFrame;
  40828. var adjustTime = frame - currentFrame;
  40829. var delay = adjustTime * 1000 / fps;
  40830. if (this._localDelayOffset === null) {
  40831. this._localDelayOffset = 0;
  40832. }
  40833. this._localDelayOffset -= delay;
  40834. }
  40835. for (var index = 0; index < runtimeAnimations.length; index++) {
  40836. runtimeAnimations[index].goToFrame(frame);
  40837. }
  40838. };
  40839. Animatable.prototype.pause = function () {
  40840. if (this._paused) {
  40841. return;
  40842. }
  40843. this._paused = true;
  40844. };
  40845. Animatable.prototype.restart = function () {
  40846. this._paused = false;
  40847. };
  40848. Animatable.prototype.stop = function (animationName) {
  40849. if (animationName) {
  40850. var idx = this._scene._activeAnimatables.indexOf(this);
  40851. if (idx > -1) {
  40852. var runtimeAnimations = this._runtimeAnimations;
  40853. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40854. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40855. continue;
  40856. }
  40857. runtimeAnimations[index].dispose();
  40858. runtimeAnimations.splice(index, 1);
  40859. }
  40860. if (runtimeAnimations.length == 0) {
  40861. this._scene._activeAnimatables.splice(idx, 1);
  40862. if (this.onAnimationEnd) {
  40863. this.onAnimationEnd();
  40864. }
  40865. }
  40866. }
  40867. }
  40868. else {
  40869. var index = this._scene._activeAnimatables.indexOf(this);
  40870. if (index > -1) {
  40871. this._scene._activeAnimatables.splice(index, 1);
  40872. var runtimeAnimations = this._runtimeAnimations;
  40873. for (var index = 0; index < runtimeAnimations.length; index++) {
  40874. runtimeAnimations[index].dispose();
  40875. }
  40876. if (this.onAnimationEnd) {
  40877. this.onAnimationEnd();
  40878. }
  40879. }
  40880. }
  40881. };
  40882. Animatable.prototype._animate = function (delay) {
  40883. if (this._paused) {
  40884. this.animationStarted = false;
  40885. if (this._pausedDelay === null) {
  40886. this._pausedDelay = delay;
  40887. }
  40888. return true;
  40889. }
  40890. if (this._localDelayOffset === null) {
  40891. this._localDelayOffset = delay;
  40892. }
  40893. else if (this._pausedDelay !== null) {
  40894. this._localDelayOffset += delay - this._pausedDelay;
  40895. this._pausedDelay = null;
  40896. }
  40897. // Animating
  40898. var running = false;
  40899. var runtimeAnimations = this._runtimeAnimations;
  40900. var index;
  40901. for (index = 0; index < runtimeAnimations.length; index++) {
  40902. var animation = runtimeAnimations[index];
  40903. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40904. running = running || isRunning;
  40905. }
  40906. this.animationStarted = running;
  40907. if (!running) {
  40908. // Remove from active animatables
  40909. index = this._scene._activeAnimatables.indexOf(this);
  40910. this._scene._activeAnimatables.splice(index, 1);
  40911. // Dispose all runtime animations
  40912. for (index = 0; index < runtimeAnimations.length; index++) {
  40913. runtimeAnimations[index].dispose();
  40914. }
  40915. }
  40916. if (!running && this.onAnimationEnd) {
  40917. this.onAnimationEnd();
  40918. this.onAnimationEnd = null;
  40919. }
  40920. return running;
  40921. };
  40922. return Animatable;
  40923. }());
  40924. BABYLON.Animatable = Animatable;
  40925. })(BABYLON || (BABYLON = {}));
  40926. //# sourceMappingURL=babylon.animatable.js.map
  40927. var BABYLON;
  40928. (function (BABYLON) {
  40929. var EasingFunction = /** @class */ (function () {
  40930. function EasingFunction() {
  40931. // Properties
  40932. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40933. }
  40934. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40935. get: function () {
  40936. return EasingFunction._EASINGMODE_EASEIN;
  40937. },
  40938. enumerable: true,
  40939. configurable: true
  40940. });
  40941. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40942. get: function () {
  40943. return EasingFunction._EASINGMODE_EASEOUT;
  40944. },
  40945. enumerable: true,
  40946. configurable: true
  40947. });
  40948. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40949. get: function () {
  40950. return EasingFunction._EASINGMODE_EASEINOUT;
  40951. },
  40952. enumerable: true,
  40953. configurable: true
  40954. });
  40955. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40956. var n = Math.min(Math.max(easingMode, 0), 2);
  40957. this._easingMode = n;
  40958. };
  40959. EasingFunction.prototype.getEasingMode = function () {
  40960. return this._easingMode;
  40961. };
  40962. EasingFunction.prototype.easeInCore = function (gradient) {
  40963. throw new Error('You must implement this method');
  40964. };
  40965. EasingFunction.prototype.ease = function (gradient) {
  40966. switch (this._easingMode) {
  40967. case EasingFunction.EASINGMODE_EASEIN:
  40968. return this.easeInCore(gradient);
  40969. case EasingFunction.EASINGMODE_EASEOUT:
  40970. return (1 - this.easeInCore(1 - gradient));
  40971. }
  40972. if (gradient >= 0.5) {
  40973. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40974. }
  40975. return (this.easeInCore(gradient * 2) * 0.5);
  40976. };
  40977. //Statics
  40978. EasingFunction._EASINGMODE_EASEIN = 0;
  40979. EasingFunction._EASINGMODE_EASEOUT = 1;
  40980. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40981. return EasingFunction;
  40982. }());
  40983. BABYLON.EasingFunction = EasingFunction;
  40984. var CircleEase = /** @class */ (function (_super) {
  40985. __extends(CircleEase, _super);
  40986. function CircleEase() {
  40987. return _super !== null && _super.apply(this, arguments) || this;
  40988. }
  40989. CircleEase.prototype.easeInCore = function (gradient) {
  40990. gradient = Math.max(0, Math.min(1, gradient));
  40991. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40992. };
  40993. return CircleEase;
  40994. }(EasingFunction));
  40995. BABYLON.CircleEase = CircleEase;
  40996. var BackEase = /** @class */ (function (_super) {
  40997. __extends(BackEase, _super);
  40998. function BackEase(amplitude) {
  40999. if (amplitude === void 0) { amplitude = 1; }
  41000. var _this = _super.call(this) || this;
  41001. _this.amplitude = amplitude;
  41002. return _this;
  41003. }
  41004. BackEase.prototype.easeInCore = function (gradient) {
  41005. var num = Math.max(0, this.amplitude);
  41006. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41007. };
  41008. return BackEase;
  41009. }(EasingFunction));
  41010. BABYLON.BackEase = BackEase;
  41011. var BounceEase = /** @class */ (function (_super) {
  41012. __extends(BounceEase, _super);
  41013. function BounceEase(bounces, bounciness) {
  41014. if (bounces === void 0) { bounces = 3; }
  41015. if (bounciness === void 0) { bounciness = 2; }
  41016. var _this = _super.call(this) || this;
  41017. _this.bounces = bounces;
  41018. _this.bounciness = bounciness;
  41019. return _this;
  41020. }
  41021. BounceEase.prototype.easeInCore = function (gradient) {
  41022. var y = Math.max(0.0, this.bounces);
  41023. var bounciness = this.bounciness;
  41024. if (bounciness <= 1.0) {
  41025. bounciness = 1.001;
  41026. }
  41027. var num9 = Math.pow(bounciness, y);
  41028. var num5 = 1.0 - bounciness;
  41029. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41030. var num15 = gradient * num4;
  41031. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41032. var num3 = Math.floor(num65);
  41033. var num13 = num3 + 1.0;
  41034. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41035. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41036. var num7 = (num8 + num12) * 0.5;
  41037. var num6 = gradient - num7;
  41038. var num2 = num7 - num8;
  41039. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41040. };
  41041. return BounceEase;
  41042. }(EasingFunction));
  41043. BABYLON.BounceEase = BounceEase;
  41044. var CubicEase = /** @class */ (function (_super) {
  41045. __extends(CubicEase, _super);
  41046. function CubicEase() {
  41047. return _super !== null && _super.apply(this, arguments) || this;
  41048. }
  41049. CubicEase.prototype.easeInCore = function (gradient) {
  41050. return (gradient * gradient * gradient);
  41051. };
  41052. return CubicEase;
  41053. }(EasingFunction));
  41054. BABYLON.CubicEase = CubicEase;
  41055. var ElasticEase = /** @class */ (function (_super) {
  41056. __extends(ElasticEase, _super);
  41057. function ElasticEase(oscillations, springiness) {
  41058. if (oscillations === void 0) { oscillations = 3; }
  41059. if (springiness === void 0) { springiness = 3; }
  41060. var _this = _super.call(this) || this;
  41061. _this.oscillations = oscillations;
  41062. _this.springiness = springiness;
  41063. return _this;
  41064. }
  41065. ElasticEase.prototype.easeInCore = function (gradient) {
  41066. var num2;
  41067. var num3 = Math.max(0.0, this.oscillations);
  41068. var num = Math.max(0.0, this.springiness);
  41069. if (num == 0) {
  41070. num2 = gradient;
  41071. }
  41072. else {
  41073. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41074. }
  41075. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41076. };
  41077. return ElasticEase;
  41078. }(EasingFunction));
  41079. BABYLON.ElasticEase = ElasticEase;
  41080. var ExponentialEase = /** @class */ (function (_super) {
  41081. __extends(ExponentialEase, _super);
  41082. function ExponentialEase(exponent) {
  41083. if (exponent === void 0) { exponent = 2; }
  41084. var _this = _super.call(this) || this;
  41085. _this.exponent = exponent;
  41086. return _this;
  41087. }
  41088. ExponentialEase.prototype.easeInCore = function (gradient) {
  41089. if (this.exponent <= 0) {
  41090. return gradient;
  41091. }
  41092. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41093. };
  41094. return ExponentialEase;
  41095. }(EasingFunction));
  41096. BABYLON.ExponentialEase = ExponentialEase;
  41097. var PowerEase = /** @class */ (function (_super) {
  41098. __extends(PowerEase, _super);
  41099. function PowerEase(power) {
  41100. if (power === void 0) { power = 2; }
  41101. var _this = _super.call(this) || this;
  41102. _this.power = power;
  41103. return _this;
  41104. }
  41105. PowerEase.prototype.easeInCore = function (gradient) {
  41106. var y = Math.max(0.0, this.power);
  41107. return Math.pow(gradient, y);
  41108. };
  41109. return PowerEase;
  41110. }(EasingFunction));
  41111. BABYLON.PowerEase = PowerEase;
  41112. var QuadraticEase = /** @class */ (function (_super) {
  41113. __extends(QuadraticEase, _super);
  41114. function QuadraticEase() {
  41115. return _super !== null && _super.apply(this, arguments) || this;
  41116. }
  41117. QuadraticEase.prototype.easeInCore = function (gradient) {
  41118. return (gradient * gradient);
  41119. };
  41120. return QuadraticEase;
  41121. }(EasingFunction));
  41122. BABYLON.QuadraticEase = QuadraticEase;
  41123. var QuarticEase = /** @class */ (function (_super) {
  41124. __extends(QuarticEase, _super);
  41125. function QuarticEase() {
  41126. return _super !== null && _super.apply(this, arguments) || this;
  41127. }
  41128. QuarticEase.prototype.easeInCore = function (gradient) {
  41129. return (gradient * gradient * gradient * gradient);
  41130. };
  41131. return QuarticEase;
  41132. }(EasingFunction));
  41133. BABYLON.QuarticEase = QuarticEase;
  41134. var QuinticEase = /** @class */ (function (_super) {
  41135. __extends(QuinticEase, _super);
  41136. function QuinticEase() {
  41137. return _super !== null && _super.apply(this, arguments) || this;
  41138. }
  41139. QuinticEase.prototype.easeInCore = function (gradient) {
  41140. return (gradient * gradient * gradient * gradient * gradient);
  41141. };
  41142. return QuinticEase;
  41143. }(EasingFunction));
  41144. BABYLON.QuinticEase = QuinticEase;
  41145. var SineEase = /** @class */ (function (_super) {
  41146. __extends(SineEase, _super);
  41147. function SineEase() {
  41148. return _super !== null && _super.apply(this, arguments) || this;
  41149. }
  41150. SineEase.prototype.easeInCore = function (gradient) {
  41151. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41152. };
  41153. return SineEase;
  41154. }(EasingFunction));
  41155. BABYLON.SineEase = SineEase;
  41156. var BezierCurveEase = /** @class */ (function (_super) {
  41157. __extends(BezierCurveEase, _super);
  41158. function BezierCurveEase(x1, y1, x2, y2) {
  41159. if (x1 === void 0) { x1 = 0; }
  41160. if (y1 === void 0) { y1 = 0; }
  41161. if (x2 === void 0) { x2 = 1; }
  41162. if (y2 === void 0) { y2 = 1; }
  41163. var _this = _super.call(this) || this;
  41164. _this.x1 = x1;
  41165. _this.y1 = y1;
  41166. _this.x2 = x2;
  41167. _this.y2 = y2;
  41168. return _this;
  41169. }
  41170. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41171. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41172. };
  41173. return BezierCurveEase;
  41174. }(EasingFunction));
  41175. BABYLON.BezierCurveEase = BezierCurveEase;
  41176. })(BABYLON || (BABYLON = {}));
  41177. //# sourceMappingURL=babylon.easing.js.map
  41178. var BABYLON;
  41179. (function (BABYLON) {
  41180. var Condition = /** @class */ (function () {
  41181. function Condition(actionManager) {
  41182. this._actionManager = actionManager;
  41183. }
  41184. Condition.prototype.isValid = function () {
  41185. return true;
  41186. };
  41187. Condition.prototype._getProperty = function (propertyPath) {
  41188. return this._actionManager._getProperty(propertyPath);
  41189. };
  41190. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41191. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41192. };
  41193. Condition.prototype.serialize = function () {
  41194. };
  41195. Condition.prototype._serialize = function (serializedCondition) {
  41196. return {
  41197. type: 2,
  41198. children: [],
  41199. name: serializedCondition.name,
  41200. properties: serializedCondition.properties
  41201. };
  41202. };
  41203. return Condition;
  41204. }());
  41205. BABYLON.Condition = Condition;
  41206. var ValueCondition = /** @class */ (function (_super) {
  41207. __extends(ValueCondition, _super);
  41208. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41209. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41210. var _this = _super.call(this, actionManager) || this;
  41211. _this.propertyPath = propertyPath;
  41212. _this.value = value;
  41213. _this.operator = operator;
  41214. _this._target = target;
  41215. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41216. _this._property = _this._getProperty(_this.propertyPath);
  41217. return _this;
  41218. }
  41219. Object.defineProperty(ValueCondition, "IsEqual", {
  41220. get: function () {
  41221. return ValueCondition._IsEqual;
  41222. },
  41223. enumerable: true,
  41224. configurable: true
  41225. });
  41226. Object.defineProperty(ValueCondition, "IsDifferent", {
  41227. get: function () {
  41228. return ValueCondition._IsDifferent;
  41229. },
  41230. enumerable: true,
  41231. configurable: true
  41232. });
  41233. Object.defineProperty(ValueCondition, "IsGreater", {
  41234. get: function () {
  41235. return ValueCondition._IsGreater;
  41236. },
  41237. enumerable: true,
  41238. configurable: true
  41239. });
  41240. Object.defineProperty(ValueCondition, "IsLesser", {
  41241. get: function () {
  41242. return ValueCondition._IsLesser;
  41243. },
  41244. enumerable: true,
  41245. configurable: true
  41246. });
  41247. // Methods
  41248. ValueCondition.prototype.isValid = function () {
  41249. switch (this.operator) {
  41250. case ValueCondition.IsGreater:
  41251. return this._effectiveTarget[this._property] > this.value;
  41252. case ValueCondition.IsLesser:
  41253. return this._effectiveTarget[this._property] < this.value;
  41254. case ValueCondition.IsEqual:
  41255. case ValueCondition.IsDifferent:
  41256. var check;
  41257. if (this.value.equals) {
  41258. check = this.value.equals(this._effectiveTarget[this._property]);
  41259. }
  41260. else {
  41261. check = this.value === this._effectiveTarget[this._property];
  41262. }
  41263. return this.operator === ValueCondition.IsEqual ? check : !check;
  41264. }
  41265. return false;
  41266. };
  41267. ValueCondition.prototype.serialize = function () {
  41268. return this._serialize({
  41269. name: "ValueCondition",
  41270. properties: [
  41271. BABYLON.Action._GetTargetProperty(this._target),
  41272. { name: "propertyPath", value: this.propertyPath },
  41273. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41274. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41275. ]
  41276. });
  41277. };
  41278. ValueCondition.GetOperatorName = function (operator) {
  41279. switch (operator) {
  41280. case ValueCondition._IsEqual: return "IsEqual";
  41281. case ValueCondition._IsDifferent: return "IsDifferent";
  41282. case ValueCondition._IsGreater: return "IsGreater";
  41283. case ValueCondition._IsLesser: return "IsLesser";
  41284. default: return "";
  41285. }
  41286. };
  41287. // Statics
  41288. ValueCondition._IsEqual = 0;
  41289. ValueCondition._IsDifferent = 1;
  41290. ValueCondition._IsGreater = 2;
  41291. ValueCondition._IsLesser = 3;
  41292. return ValueCondition;
  41293. }(Condition));
  41294. BABYLON.ValueCondition = ValueCondition;
  41295. var PredicateCondition = /** @class */ (function (_super) {
  41296. __extends(PredicateCondition, _super);
  41297. function PredicateCondition(actionManager, predicate) {
  41298. var _this = _super.call(this, actionManager) || this;
  41299. _this.predicate = predicate;
  41300. return _this;
  41301. }
  41302. PredicateCondition.prototype.isValid = function () {
  41303. return this.predicate();
  41304. };
  41305. return PredicateCondition;
  41306. }(Condition));
  41307. BABYLON.PredicateCondition = PredicateCondition;
  41308. var StateCondition = /** @class */ (function (_super) {
  41309. __extends(StateCondition, _super);
  41310. function StateCondition(actionManager, target, value) {
  41311. var _this = _super.call(this, actionManager) || this;
  41312. _this.value = value;
  41313. _this._target = target;
  41314. return _this;
  41315. }
  41316. // Methods
  41317. StateCondition.prototype.isValid = function () {
  41318. return this._target.state === this.value;
  41319. };
  41320. StateCondition.prototype.serialize = function () {
  41321. return this._serialize({
  41322. name: "StateCondition",
  41323. properties: [
  41324. BABYLON.Action._GetTargetProperty(this._target),
  41325. { name: "value", value: this.value }
  41326. ]
  41327. });
  41328. };
  41329. return StateCondition;
  41330. }(Condition));
  41331. BABYLON.StateCondition = StateCondition;
  41332. })(BABYLON || (BABYLON = {}));
  41333. //# sourceMappingURL=babylon.condition.js.map
  41334. var BABYLON;
  41335. (function (BABYLON) {
  41336. var Action = /** @class */ (function () {
  41337. function Action(triggerOptions, condition) {
  41338. this.triggerOptions = triggerOptions;
  41339. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41340. if (triggerOptions.parameter) {
  41341. this.trigger = triggerOptions.trigger;
  41342. this._triggerParameter = triggerOptions.parameter;
  41343. }
  41344. else {
  41345. this.trigger = triggerOptions;
  41346. }
  41347. this._nextActiveAction = this;
  41348. this._condition = condition;
  41349. }
  41350. // Methods
  41351. Action.prototype._prepare = function () {
  41352. };
  41353. Action.prototype.getTriggerParameter = function () {
  41354. return this._triggerParameter;
  41355. };
  41356. Action.prototype._executeCurrent = function (evt) {
  41357. if (this._nextActiveAction._condition) {
  41358. var condition = this._nextActiveAction._condition;
  41359. var currentRenderId = this._actionManager.getScene().getRenderId();
  41360. // We cache the current evaluation for the current frame
  41361. if (condition._evaluationId === currentRenderId) {
  41362. if (!condition._currentResult) {
  41363. return;
  41364. }
  41365. }
  41366. else {
  41367. condition._evaluationId = currentRenderId;
  41368. if (!condition.isValid()) {
  41369. condition._currentResult = false;
  41370. return;
  41371. }
  41372. condition._currentResult = true;
  41373. }
  41374. }
  41375. this.onBeforeExecuteObservable.notifyObservers(this);
  41376. this._nextActiveAction.execute(evt);
  41377. this.skipToNextActiveAction();
  41378. };
  41379. Action.prototype.execute = function (evt) {
  41380. };
  41381. Action.prototype.skipToNextActiveAction = function () {
  41382. if (this._nextActiveAction._child) {
  41383. if (!this._nextActiveAction._child._actionManager) {
  41384. this._nextActiveAction._child._actionManager = this._actionManager;
  41385. }
  41386. this._nextActiveAction = this._nextActiveAction._child;
  41387. }
  41388. else {
  41389. this._nextActiveAction = this;
  41390. }
  41391. };
  41392. Action.prototype.then = function (action) {
  41393. this._child = action;
  41394. action._actionManager = this._actionManager;
  41395. action._prepare();
  41396. return action;
  41397. };
  41398. Action.prototype._getProperty = function (propertyPath) {
  41399. return this._actionManager._getProperty(propertyPath);
  41400. };
  41401. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41402. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41403. };
  41404. Action.prototype.serialize = function (parent) {
  41405. };
  41406. // Called by BABYLON.Action objects in serialize(...). Internal use
  41407. Action.prototype._serialize = function (serializedAction, parent) {
  41408. var serializationObject = {
  41409. type: 1,
  41410. children: [],
  41411. name: serializedAction.name,
  41412. properties: serializedAction.properties || []
  41413. };
  41414. // Serialize child
  41415. if (this._child) {
  41416. this._child.serialize(serializationObject);
  41417. }
  41418. // Check if "this" has a condition
  41419. if (this._condition) {
  41420. var serializedCondition = this._condition.serialize();
  41421. serializedCondition.children.push(serializationObject);
  41422. if (parent) {
  41423. parent.children.push(serializedCondition);
  41424. }
  41425. return serializedCondition;
  41426. }
  41427. if (parent) {
  41428. parent.children.push(serializationObject);
  41429. }
  41430. return serializationObject;
  41431. };
  41432. Action._SerializeValueAsString = function (value) {
  41433. if (typeof value === "number") {
  41434. return value.toString();
  41435. }
  41436. if (typeof value === "boolean") {
  41437. return value ? "true" : "false";
  41438. }
  41439. if (value instanceof BABYLON.Vector2) {
  41440. return value.x + ", " + value.y;
  41441. }
  41442. if (value instanceof BABYLON.Vector3) {
  41443. return value.x + ", " + value.y + ", " + value.z;
  41444. }
  41445. if (value instanceof BABYLON.Color3) {
  41446. return value.r + ", " + value.g + ", " + value.b;
  41447. }
  41448. if (value instanceof BABYLON.Color4) {
  41449. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41450. }
  41451. return value; // string
  41452. };
  41453. Action._GetTargetProperty = function (target) {
  41454. return {
  41455. name: "target",
  41456. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41457. : target instanceof BABYLON.Light ? "LightProperties"
  41458. : target instanceof BABYLON.Camera ? "CameraProperties"
  41459. : "SceneProperties",
  41460. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41461. };
  41462. };
  41463. return Action;
  41464. }());
  41465. BABYLON.Action = Action;
  41466. })(BABYLON || (BABYLON = {}));
  41467. //# sourceMappingURL=babylon.action.js.map
  41468. var BABYLON;
  41469. (function (BABYLON) {
  41470. /**
  41471. * ActionEvent is the event beint sent when an action is triggered.
  41472. */
  41473. var ActionEvent = /** @class */ (function () {
  41474. /**
  41475. * @param source The mesh or sprite that triggered the action.
  41476. * @param pointerX The X mouse cursor position at the time of the event
  41477. * @param pointerY The Y mouse cursor position at the time of the event
  41478. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41479. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41480. */
  41481. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41482. this.source = source;
  41483. this.pointerX = pointerX;
  41484. this.pointerY = pointerY;
  41485. this.meshUnderPointer = meshUnderPointer;
  41486. this.sourceEvent = sourceEvent;
  41487. this.additionalData = additionalData;
  41488. }
  41489. /**
  41490. * Helper function to auto-create an ActionEvent from a source mesh.
  41491. * @param source The source mesh that triggered the event
  41492. * @param evt {Event} The original (browser) event
  41493. */
  41494. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41495. var scene = source.getScene();
  41496. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41497. };
  41498. /**
  41499. * Helper function to auto-create an ActionEvent from a source mesh.
  41500. * @param source The source sprite that triggered the event
  41501. * @param scene Scene associated with the sprite
  41502. * @param evt {Event} The original (browser) event
  41503. */
  41504. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41505. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41506. };
  41507. /**
  41508. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41509. * @param scene the scene where the event occurred
  41510. * @param evt {Event} The original (browser) event
  41511. */
  41512. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41513. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41514. };
  41515. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41516. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41517. };
  41518. return ActionEvent;
  41519. }());
  41520. BABYLON.ActionEvent = ActionEvent;
  41521. /**
  41522. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41523. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41524. */
  41525. var ActionManager = /** @class */ (function () {
  41526. function ActionManager(scene) {
  41527. // Members
  41528. this.actions = new Array();
  41529. this.hoverCursor = '';
  41530. this._scene = scene;
  41531. scene._actionManagers.push(this);
  41532. }
  41533. Object.defineProperty(ActionManager, "NothingTrigger", {
  41534. get: function () {
  41535. return ActionManager._NothingTrigger;
  41536. },
  41537. enumerable: true,
  41538. configurable: true
  41539. });
  41540. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41541. get: function () {
  41542. return ActionManager._OnPickTrigger;
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41548. get: function () {
  41549. return ActionManager._OnLeftPickTrigger;
  41550. },
  41551. enumerable: true,
  41552. configurable: true
  41553. });
  41554. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41555. get: function () {
  41556. return ActionManager._OnRightPickTrigger;
  41557. },
  41558. enumerable: true,
  41559. configurable: true
  41560. });
  41561. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41562. get: function () {
  41563. return ActionManager._OnCenterPickTrigger;
  41564. },
  41565. enumerable: true,
  41566. configurable: true
  41567. });
  41568. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41569. get: function () {
  41570. return ActionManager._OnPickDownTrigger;
  41571. },
  41572. enumerable: true,
  41573. configurable: true
  41574. });
  41575. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41576. get: function () {
  41577. return ActionManager._OnDoublePickTrigger;
  41578. },
  41579. enumerable: true,
  41580. configurable: true
  41581. });
  41582. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41583. get: function () {
  41584. return ActionManager._OnPickUpTrigger;
  41585. },
  41586. enumerable: true,
  41587. configurable: true
  41588. });
  41589. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41590. /// This trigger will only be raised if you also declared a OnPickDown
  41591. get: function () {
  41592. return ActionManager._OnPickOutTrigger;
  41593. },
  41594. enumerable: true,
  41595. configurable: true
  41596. });
  41597. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41598. get: function () {
  41599. return ActionManager._OnLongPressTrigger;
  41600. },
  41601. enumerable: true,
  41602. configurable: true
  41603. });
  41604. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41605. get: function () {
  41606. return ActionManager._OnPointerOverTrigger;
  41607. },
  41608. enumerable: true,
  41609. configurable: true
  41610. });
  41611. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41612. get: function () {
  41613. return ActionManager._OnPointerOutTrigger;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41619. get: function () {
  41620. return ActionManager._OnEveryFrameTrigger;
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41626. get: function () {
  41627. return ActionManager._OnIntersectionEnterTrigger;
  41628. },
  41629. enumerable: true,
  41630. configurable: true
  41631. });
  41632. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41633. get: function () {
  41634. return ActionManager._OnIntersectionExitTrigger;
  41635. },
  41636. enumerable: true,
  41637. configurable: true
  41638. });
  41639. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41640. get: function () {
  41641. return ActionManager._OnKeyDownTrigger;
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41647. get: function () {
  41648. return ActionManager._OnKeyUpTrigger;
  41649. },
  41650. enumerable: true,
  41651. configurable: true
  41652. });
  41653. // Methods
  41654. ActionManager.prototype.dispose = function () {
  41655. var index = this._scene._actionManagers.indexOf(this);
  41656. for (var i = 0; i < this.actions.length; i++) {
  41657. var action = this.actions[i];
  41658. ActionManager.Triggers[action.trigger]--;
  41659. if (ActionManager.Triggers[action.trigger] === 0) {
  41660. delete ActionManager.Triggers[action.trigger];
  41661. }
  41662. }
  41663. if (index > -1) {
  41664. this._scene._actionManagers.splice(index, 1);
  41665. }
  41666. };
  41667. ActionManager.prototype.getScene = function () {
  41668. return this._scene;
  41669. };
  41670. /**
  41671. * Does this action manager handles actions of any of the given triggers
  41672. * @param {number[]} triggers - the triggers to be tested
  41673. * @return {boolean} whether one (or more) of the triggers is handeled
  41674. */
  41675. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41676. for (var index = 0; index < this.actions.length; index++) {
  41677. var action = this.actions[index];
  41678. if (triggers.indexOf(action.trigger) > -1) {
  41679. return true;
  41680. }
  41681. }
  41682. return false;
  41683. };
  41684. /**
  41685. * Does this action manager handles actions of a given trigger
  41686. * @param {number} trigger - the trigger to be tested
  41687. * @return {boolean} whether the trigger is handeled
  41688. */
  41689. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41690. for (var index = 0; index < this.actions.length; index++) {
  41691. var action = this.actions[index];
  41692. if (action.trigger === trigger) {
  41693. return true;
  41694. }
  41695. }
  41696. return false;
  41697. };
  41698. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41699. /**
  41700. * Does this action manager has pointer triggers
  41701. * @return {boolean} whether or not it has pointer triggers
  41702. */
  41703. get: function () {
  41704. for (var index = 0; index < this.actions.length; index++) {
  41705. var action = this.actions[index];
  41706. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41707. return true;
  41708. }
  41709. }
  41710. return false;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41716. /**
  41717. * Does this action manager has pick triggers
  41718. * @return {boolean} whether or not it has pick triggers
  41719. */
  41720. get: function () {
  41721. for (var index = 0; index < this.actions.length; index++) {
  41722. var action = this.actions[index];
  41723. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41724. return true;
  41725. }
  41726. }
  41727. return false;
  41728. },
  41729. enumerable: true,
  41730. configurable: true
  41731. });
  41732. Object.defineProperty(ActionManager, "HasTriggers", {
  41733. /**
  41734. * Does exist one action manager with at least one trigger
  41735. * @return {boolean} whether or not it exists one action manager with one trigger
  41736. **/
  41737. get: function () {
  41738. for (var t in ActionManager.Triggers) {
  41739. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41740. return true;
  41741. }
  41742. }
  41743. return false;
  41744. },
  41745. enumerable: true,
  41746. configurable: true
  41747. });
  41748. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41749. /**
  41750. * Does exist one action manager with at least one pick trigger
  41751. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41752. **/
  41753. get: function () {
  41754. for (var t in ActionManager.Triggers) {
  41755. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41756. var t_int = parseInt(t);
  41757. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41758. return true;
  41759. }
  41760. }
  41761. }
  41762. return false;
  41763. },
  41764. enumerable: true,
  41765. configurable: true
  41766. });
  41767. /**
  41768. * Does exist one action manager that handles actions of a given trigger
  41769. * @param {number} trigger - the trigger to be tested
  41770. * @return {boolean} whether the trigger is handeled by at least one action manager
  41771. **/
  41772. ActionManager.HasSpecificTrigger = function (trigger) {
  41773. for (var t in ActionManager.Triggers) {
  41774. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41775. var t_int = parseInt(t);
  41776. if (t_int === trigger) {
  41777. return true;
  41778. }
  41779. }
  41780. }
  41781. return false;
  41782. };
  41783. /**
  41784. * Registers an action to this action manager
  41785. * @param {BABYLON.Action} action - the action to be registered
  41786. * @return {BABYLON.Action} the action amended (prepared) after registration
  41787. */
  41788. ActionManager.prototype.registerAction = function (action) {
  41789. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41790. if (this.getScene().actionManager !== this) {
  41791. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41792. return null;
  41793. }
  41794. }
  41795. this.actions.push(action);
  41796. if (ActionManager.Triggers[action.trigger]) {
  41797. ActionManager.Triggers[action.trigger]++;
  41798. }
  41799. else {
  41800. ActionManager.Triggers[action.trigger] = 1;
  41801. }
  41802. action._actionManager = this;
  41803. action._prepare();
  41804. return action;
  41805. };
  41806. /**
  41807. * Process a specific trigger
  41808. * @param {number} trigger - the trigger to process
  41809. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41810. */
  41811. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41812. for (var index = 0; index < this.actions.length; index++) {
  41813. var action = this.actions[index];
  41814. if (action.trigger === trigger) {
  41815. if (evt) {
  41816. if (trigger === ActionManager.OnKeyUpTrigger
  41817. || trigger === ActionManager.OnKeyDownTrigger) {
  41818. var parameter = action.getTriggerParameter();
  41819. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41820. if (!parameter.toLowerCase) {
  41821. continue;
  41822. }
  41823. var lowerCase = parameter.toLowerCase();
  41824. if (lowerCase !== evt.sourceEvent.key) {
  41825. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41826. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41827. if (actualkey !== lowerCase) {
  41828. continue;
  41829. }
  41830. }
  41831. }
  41832. }
  41833. }
  41834. action._executeCurrent(evt);
  41835. }
  41836. }
  41837. };
  41838. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41839. var properties = propertyPath.split(".");
  41840. for (var index = 0; index < properties.length - 1; index++) {
  41841. target = target[properties[index]];
  41842. }
  41843. return target;
  41844. };
  41845. ActionManager.prototype._getProperty = function (propertyPath) {
  41846. var properties = propertyPath.split(".");
  41847. return properties[properties.length - 1];
  41848. };
  41849. ActionManager.prototype.serialize = function (name) {
  41850. var root = {
  41851. children: new Array(),
  41852. name: name,
  41853. type: 3,
  41854. properties: new Array() // Empty for root but required
  41855. };
  41856. for (var i = 0; i < this.actions.length; i++) {
  41857. var triggerObject = {
  41858. type: 0,
  41859. children: new Array(),
  41860. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41861. properties: new Array()
  41862. };
  41863. var triggerOptions = this.actions[i].triggerOptions;
  41864. if (triggerOptions && typeof triggerOptions !== "number") {
  41865. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41866. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41867. }
  41868. else {
  41869. var parameter = {};
  41870. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41871. if (triggerOptions.parameter.mesh) {
  41872. parameter._meshId = triggerOptions.parameter.mesh.id;
  41873. }
  41874. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41875. }
  41876. }
  41877. // Serialize child action, recursively
  41878. this.actions[i].serialize(triggerObject);
  41879. // Add serialized trigger
  41880. root.children.push(triggerObject);
  41881. }
  41882. return root;
  41883. };
  41884. ActionManager.Parse = function (parsedActions, object, scene) {
  41885. var actionManager = new BABYLON.ActionManager(scene);
  41886. if (object === null)
  41887. scene.actionManager = actionManager;
  41888. else
  41889. object.actionManager = actionManager;
  41890. // instanciate a new object
  41891. var instanciate = function (name, params) {
  41892. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41893. newInstance.constructor.apply(newInstance, params);
  41894. return newInstance;
  41895. };
  41896. var parseParameter = function (name, value, target, propertyPath) {
  41897. if (propertyPath === null) {
  41898. // String, boolean or float
  41899. var floatValue = parseFloat(value);
  41900. if (value === "true" || value === "false")
  41901. return value === "true";
  41902. else
  41903. return isNaN(floatValue) ? value : floatValue;
  41904. }
  41905. var effectiveTarget = propertyPath.split(".");
  41906. var values = value.split(",");
  41907. // Get effective Target
  41908. for (var i = 0; i < effectiveTarget.length; i++) {
  41909. target = target[effectiveTarget[i]];
  41910. }
  41911. // Return appropriate value with its type
  41912. if (typeof (target) === "boolean")
  41913. return values[0] === "true";
  41914. if (typeof (target) === "string")
  41915. return values[0];
  41916. // Parameters with multiple values such as Vector3 etc.
  41917. var split = new Array();
  41918. for (var i = 0; i < values.length; i++)
  41919. split.push(parseFloat(values[i]));
  41920. if (target instanceof BABYLON.Vector3)
  41921. return BABYLON.Vector3.FromArray(split);
  41922. if (target instanceof BABYLON.Vector4)
  41923. return BABYLON.Vector4.FromArray(split);
  41924. if (target instanceof BABYLON.Color3)
  41925. return BABYLON.Color3.FromArray(split);
  41926. if (target instanceof BABYLON.Color4)
  41927. return BABYLON.Color4.FromArray(split);
  41928. return parseFloat(values[0]);
  41929. };
  41930. // traverse graph per trigger
  41931. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41932. if (combineArray === void 0) { combineArray = null; }
  41933. if (parsedAction.detached)
  41934. return;
  41935. var parameters = new Array();
  41936. var target = null;
  41937. var propertyPath = null;
  41938. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41939. // Parameters
  41940. if (parsedAction.type === 2)
  41941. parameters.push(actionManager);
  41942. else
  41943. parameters.push(trigger);
  41944. if (combine) {
  41945. var actions = new Array();
  41946. for (var j = 0; j < parsedAction.combine.length; j++) {
  41947. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41948. }
  41949. parameters.push(actions);
  41950. }
  41951. else {
  41952. for (var i = 0; i < parsedAction.properties.length; i++) {
  41953. var value = parsedAction.properties[i].value;
  41954. var name = parsedAction.properties[i].name;
  41955. var targetType = parsedAction.properties[i].targetType;
  41956. if (name === "target")
  41957. if (targetType !== null && targetType === "SceneProperties")
  41958. value = target = scene;
  41959. else
  41960. value = target = scene.getNodeByName(value);
  41961. else if (name === "parent")
  41962. value = scene.getNodeByName(value);
  41963. else if (name === "sound")
  41964. value = scene.getSoundByName(value);
  41965. else if (name !== "propertyPath") {
  41966. if (parsedAction.type === 2 && name === "operator")
  41967. value = BABYLON.ValueCondition[value];
  41968. else
  41969. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41970. }
  41971. else {
  41972. propertyPath = value;
  41973. }
  41974. parameters.push(value);
  41975. }
  41976. }
  41977. if (combineArray === null) {
  41978. parameters.push(condition);
  41979. }
  41980. else {
  41981. parameters.push(null);
  41982. }
  41983. // If interpolate value action
  41984. if (parsedAction.name === "InterpolateValueAction") {
  41985. var param = parameters[parameters.length - 2];
  41986. parameters[parameters.length - 1] = param;
  41987. parameters[parameters.length - 2] = condition;
  41988. }
  41989. // Action or condition(s) and not CombineAction
  41990. var newAction = instanciate(parsedAction.name, parameters);
  41991. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41992. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41993. if (action)
  41994. action.then(nothing);
  41995. else
  41996. actionManager.registerAction(nothing);
  41997. action = nothing;
  41998. }
  41999. if (combineArray === null) {
  42000. if (newAction instanceof BABYLON.Condition) {
  42001. condition = newAction;
  42002. newAction = action;
  42003. }
  42004. else {
  42005. condition = null;
  42006. if (action)
  42007. action.then(newAction);
  42008. else
  42009. actionManager.registerAction(newAction);
  42010. }
  42011. }
  42012. else {
  42013. combineArray.push(newAction);
  42014. }
  42015. for (var i = 0; i < parsedAction.children.length; i++)
  42016. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42017. };
  42018. // triggers
  42019. for (var i = 0; i < parsedActions.children.length; i++) {
  42020. var triggerParams;
  42021. var trigger = parsedActions.children[i];
  42022. if (trigger.properties.length > 0) {
  42023. var param = trigger.properties[0].value;
  42024. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42025. if (value._meshId) {
  42026. value.mesh = scene.getMeshByID(value._meshId);
  42027. }
  42028. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42029. }
  42030. else
  42031. triggerParams = ActionManager[trigger.name];
  42032. for (var j = 0; j < trigger.children.length; j++) {
  42033. if (!trigger.detached)
  42034. traverse(trigger.children[j], triggerParams, null, null);
  42035. }
  42036. }
  42037. };
  42038. ActionManager.GetTriggerName = function (trigger) {
  42039. switch (trigger) {
  42040. case 0: return "NothingTrigger";
  42041. case 1: return "OnPickTrigger";
  42042. case 2: return "OnLeftPickTrigger";
  42043. case 3: return "OnRightPickTrigger";
  42044. case 4: return "OnCenterPickTrigger";
  42045. case 5: return "OnPickDownTrigger";
  42046. case 6: return "OnPickUpTrigger";
  42047. case 7: return "OnLongPressTrigger";
  42048. case 8: return "OnPointerOverTrigger";
  42049. case 9: return "OnPointerOutTrigger";
  42050. case 10: return "OnEveryFrameTrigger";
  42051. case 11: return "OnIntersectionEnterTrigger";
  42052. case 12: return "OnIntersectionExitTrigger";
  42053. case 13: return "OnKeyDownTrigger";
  42054. case 14: return "OnKeyUpTrigger";
  42055. case 15: return "OnPickOutTrigger";
  42056. default: return "";
  42057. }
  42058. };
  42059. // Statics
  42060. ActionManager._NothingTrigger = 0;
  42061. ActionManager._OnPickTrigger = 1;
  42062. ActionManager._OnLeftPickTrigger = 2;
  42063. ActionManager._OnRightPickTrigger = 3;
  42064. ActionManager._OnCenterPickTrigger = 4;
  42065. ActionManager._OnPickDownTrigger = 5;
  42066. ActionManager._OnDoublePickTrigger = 6;
  42067. ActionManager._OnPickUpTrigger = 7;
  42068. ActionManager._OnLongPressTrigger = 8;
  42069. ActionManager._OnPointerOverTrigger = 9;
  42070. ActionManager._OnPointerOutTrigger = 10;
  42071. ActionManager._OnEveryFrameTrigger = 11;
  42072. ActionManager._OnIntersectionEnterTrigger = 12;
  42073. ActionManager._OnIntersectionExitTrigger = 13;
  42074. ActionManager._OnKeyDownTrigger = 14;
  42075. ActionManager._OnKeyUpTrigger = 15;
  42076. ActionManager._OnPickOutTrigger = 16;
  42077. ActionManager.Triggers = {};
  42078. return ActionManager;
  42079. }());
  42080. BABYLON.ActionManager = ActionManager;
  42081. })(BABYLON || (BABYLON = {}));
  42082. //# sourceMappingURL=babylon.actionManager.js.map
  42083. var BABYLON;
  42084. (function (BABYLON) {
  42085. var InterpolateValueAction = /** @class */ (function (_super) {
  42086. __extends(InterpolateValueAction, _super);
  42087. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42088. if (duration === void 0) { duration = 1000; }
  42089. var _this = _super.call(this, triggerOptions, condition) || this;
  42090. _this.propertyPath = propertyPath;
  42091. _this.value = value;
  42092. _this.duration = duration;
  42093. _this.stopOtherAnimations = stopOtherAnimations;
  42094. _this.onInterpolationDone = onInterpolationDone;
  42095. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42096. _this._target = _this._effectiveTarget = target;
  42097. return _this;
  42098. }
  42099. InterpolateValueAction.prototype._prepare = function () {
  42100. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42101. this._property = this._getProperty(this.propertyPath);
  42102. };
  42103. InterpolateValueAction.prototype.execute = function () {
  42104. var _this = this;
  42105. var scene = this._actionManager.getScene();
  42106. var keys = [
  42107. {
  42108. frame: 0,
  42109. value: this._effectiveTarget[this._property]
  42110. }, {
  42111. frame: 100,
  42112. value: this.value
  42113. }
  42114. ];
  42115. var dataType;
  42116. if (typeof this.value === "number") {
  42117. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42118. }
  42119. else if (this.value instanceof BABYLON.Color3) {
  42120. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42121. }
  42122. else if (this.value instanceof BABYLON.Vector3) {
  42123. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42124. }
  42125. else if (this.value instanceof BABYLON.Matrix) {
  42126. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42127. }
  42128. else if (this.value instanceof BABYLON.Quaternion) {
  42129. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42130. }
  42131. else {
  42132. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42133. return;
  42134. }
  42135. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42136. animation.setKeys(keys);
  42137. if (this.stopOtherAnimations) {
  42138. scene.stopAnimation(this._effectiveTarget);
  42139. }
  42140. var wrapper = function () {
  42141. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42142. if (_this.onInterpolationDone) {
  42143. _this.onInterpolationDone();
  42144. }
  42145. };
  42146. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42147. };
  42148. InterpolateValueAction.prototype.serialize = function (parent) {
  42149. return _super.prototype._serialize.call(this, {
  42150. name: "InterpolateValueAction",
  42151. properties: [
  42152. BABYLON.Action._GetTargetProperty(this._target),
  42153. { name: "propertyPath", value: this.propertyPath },
  42154. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42155. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42156. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42157. ]
  42158. }, parent);
  42159. };
  42160. return InterpolateValueAction;
  42161. }(BABYLON.Action));
  42162. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42163. })(BABYLON || (BABYLON = {}));
  42164. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42165. var BABYLON;
  42166. (function (BABYLON) {
  42167. var SwitchBooleanAction = /** @class */ (function (_super) {
  42168. __extends(SwitchBooleanAction, _super);
  42169. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42170. var _this = _super.call(this, triggerOptions, condition) || this;
  42171. _this.propertyPath = propertyPath;
  42172. _this._target = _this._effectiveTarget = target;
  42173. return _this;
  42174. }
  42175. SwitchBooleanAction.prototype._prepare = function () {
  42176. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42177. this._property = this._getProperty(this.propertyPath);
  42178. };
  42179. SwitchBooleanAction.prototype.execute = function () {
  42180. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42181. };
  42182. SwitchBooleanAction.prototype.serialize = function (parent) {
  42183. return _super.prototype._serialize.call(this, {
  42184. name: "SwitchBooleanAction",
  42185. properties: [
  42186. BABYLON.Action._GetTargetProperty(this._target),
  42187. { name: "propertyPath", value: this.propertyPath }
  42188. ]
  42189. }, parent);
  42190. };
  42191. return SwitchBooleanAction;
  42192. }(BABYLON.Action));
  42193. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42194. var SetStateAction = /** @class */ (function (_super) {
  42195. __extends(SetStateAction, _super);
  42196. function SetStateAction(triggerOptions, target, value, condition) {
  42197. var _this = _super.call(this, triggerOptions, condition) || this;
  42198. _this.value = value;
  42199. _this._target = target;
  42200. return _this;
  42201. }
  42202. SetStateAction.prototype.execute = function () {
  42203. this._target.state = this.value;
  42204. };
  42205. SetStateAction.prototype.serialize = function (parent) {
  42206. return _super.prototype._serialize.call(this, {
  42207. name: "SetStateAction",
  42208. properties: [
  42209. BABYLON.Action._GetTargetProperty(this._target),
  42210. { name: "value", value: this.value }
  42211. ]
  42212. }, parent);
  42213. };
  42214. return SetStateAction;
  42215. }(BABYLON.Action));
  42216. BABYLON.SetStateAction = SetStateAction;
  42217. var SetValueAction = /** @class */ (function (_super) {
  42218. __extends(SetValueAction, _super);
  42219. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42220. var _this = _super.call(this, triggerOptions, condition) || this;
  42221. _this.propertyPath = propertyPath;
  42222. _this.value = value;
  42223. _this._target = _this._effectiveTarget = target;
  42224. return _this;
  42225. }
  42226. SetValueAction.prototype._prepare = function () {
  42227. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42228. this._property = this._getProperty(this.propertyPath);
  42229. };
  42230. SetValueAction.prototype.execute = function () {
  42231. this._effectiveTarget[this._property] = this.value;
  42232. if (this._target.markAsDirty) {
  42233. this._target.markAsDirty(this._property);
  42234. }
  42235. };
  42236. SetValueAction.prototype.serialize = function (parent) {
  42237. return _super.prototype._serialize.call(this, {
  42238. name: "SetValueAction",
  42239. properties: [
  42240. BABYLON.Action._GetTargetProperty(this._target),
  42241. { name: "propertyPath", value: this.propertyPath },
  42242. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42243. ]
  42244. }, parent);
  42245. };
  42246. return SetValueAction;
  42247. }(BABYLON.Action));
  42248. BABYLON.SetValueAction = SetValueAction;
  42249. var IncrementValueAction = /** @class */ (function (_super) {
  42250. __extends(IncrementValueAction, _super);
  42251. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42252. var _this = _super.call(this, triggerOptions, condition) || this;
  42253. _this.propertyPath = propertyPath;
  42254. _this.value = value;
  42255. _this._target = _this._effectiveTarget = target;
  42256. return _this;
  42257. }
  42258. IncrementValueAction.prototype._prepare = function () {
  42259. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42260. this._property = this._getProperty(this.propertyPath);
  42261. if (typeof this._effectiveTarget[this._property] !== "number") {
  42262. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42263. }
  42264. };
  42265. IncrementValueAction.prototype.execute = function () {
  42266. this._effectiveTarget[this._property] += this.value;
  42267. if (this._target.markAsDirty) {
  42268. this._target.markAsDirty(this._property);
  42269. }
  42270. };
  42271. IncrementValueAction.prototype.serialize = function (parent) {
  42272. return _super.prototype._serialize.call(this, {
  42273. name: "IncrementValueAction",
  42274. properties: [
  42275. BABYLON.Action._GetTargetProperty(this._target),
  42276. { name: "propertyPath", value: this.propertyPath },
  42277. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42278. ]
  42279. }, parent);
  42280. };
  42281. return IncrementValueAction;
  42282. }(BABYLON.Action));
  42283. BABYLON.IncrementValueAction = IncrementValueAction;
  42284. var PlayAnimationAction = /** @class */ (function (_super) {
  42285. __extends(PlayAnimationAction, _super);
  42286. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42287. var _this = _super.call(this, triggerOptions, condition) || this;
  42288. _this.from = from;
  42289. _this.to = to;
  42290. _this.loop = loop;
  42291. _this._target = target;
  42292. return _this;
  42293. }
  42294. PlayAnimationAction.prototype._prepare = function () {
  42295. };
  42296. PlayAnimationAction.prototype.execute = function () {
  42297. var scene = this._actionManager.getScene();
  42298. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42299. };
  42300. PlayAnimationAction.prototype.serialize = function (parent) {
  42301. return _super.prototype._serialize.call(this, {
  42302. name: "PlayAnimationAction",
  42303. properties: [
  42304. BABYLON.Action._GetTargetProperty(this._target),
  42305. { name: "from", value: String(this.from) },
  42306. { name: "to", value: String(this.to) },
  42307. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42308. ]
  42309. }, parent);
  42310. };
  42311. return PlayAnimationAction;
  42312. }(BABYLON.Action));
  42313. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42314. var StopAnimationAction = /** @class */ (function (_super) {
  42315. __extends(StopAnimationAction, _super);
  42316. function StopAnimationAction(triggerOptions, target, condition) {
  42317. var _this = _super.call(this, triggerOptions, condition) || this;
  42318. _this._target = target;
  42319. return _this;
  42320. }
  42321. StopAnimationAction.prototype._prepare = function () {
  42322. };
  42323. StopAnimationAction.prototype.execute = function () {
  42324. var scene = this._actionManager.getScene();
  42325. scene.stopAnimation(this._target);
  42326. };
  42327. StopAnimationAction.prototype.serialize = function (parent) {
  42328. return _super.prototype._serialize.call(this, {
  42329. name: "StopAnimationAction",
  42330. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42331. }, parent);
  42332. };
  42333. return StopAnimationAction;
  42334. }(BABYLON.Action));
  42335. BABYLON.StopAnimationAction = StopAnimationAction;
  42336. var DoNothingAction = /** @class */ (function (_super) {
  42337. __extends(DoNothingAction, _super);
  42338. function DoNothingAction(triggerOptions, condition) {
  42339. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42340. return _super.call(this, triggerOptions, condition) || this;
  42341. }
  42342. DoNothingAction.prototype.execute = function () {
  42343. };
  42344. DoNothingAction.prototype.serialize = function (parent) {
  42345. return _super.prototype._serialize.call(this, {
  42346. name: "DoNothingAction",
  42347. properties: []
  42348. }, parent);
  42349. };
  42350. return DoNothingAction;
  42351. }(BABYLON.Action));
  42352. BABYLON.DoNothingAction = DoNothingAction;
  42353. var CombineAction = /** @class */ (function (_super) {
  42354. __extends(CombineAction, _super);
  42355. function CombineAction(triggerOptions, children, condition) {
  42356. var _this = _super.call(this, triggerOptions, condition) || this;
  42357. _this.children = children;
  42358. return _this;
  42359. }
  42360. CombineAction.prototype._prepare = function () {
  42361. for (var index = 0; index < this.children.length; index++) {
  42362. this.children[index]._actionManager = this._actionManager;
  42363. this.children[index]._prepare();
  42364. }
  42365. };
  42366. CombineAction.prototype.execute = function (evt) {
  42367. for (var index = 0; index < this.children.length; index++) {
  42368. this.children[index].execute(evt);
  42369. }
  42370. };
  42371. CombineAction.prototype.serialize = function (parent) {
  42372. var serializationObject = _super.prototype._serialize.call(this, {
  42373. name: "CombineAction",
  42374. properties: [],
  42375. combine: []
  42376. }, parent);
  42377. for (var i = 0; i < this.children.length; i++) {
  42378. serializationObject.combine.push(this.children[i].serialize(null));
  42379. }
  42380. return serializationObject;
  42381. };
  42382. return CombineAction;
  42383. }(BABYLON.Action));
  42384. BABYLON.CombineAction = CombineAction;
  42385. var ExecuteCodeAction = /** @class */ (function (_super) {
  42386. __extends(ExecuteCodeAction, _super);
  42387. function ExecuteCodeAction(triggerOptions, func, condition) {
  42388. var _this = _super.call(this, triggerOptions, condition) || this;
  42389. _this.func = func;
  42390. return _this;
  42391. }
  42392. ExecuteCodeAction.prototype.execute = function (evt) {
  42393. this.func(evt);
  42394. };
  42395. return ExecuteCodeAction;
  42396. }(BABYLON.Action));
  42397. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42398. var SetParentAction = /** @class */ (function (_super) {
  42399. __extends(SetParentAction, _super);
  42400. function SetParentAction(triggerOptions, target, parent, condition) {
  42401. var _this = _super.call(this, triggerOptions, condition) || this;
  42402. _this._target = target;
  42403. _this._parent = parent;
  42404. return _this;
  42405. }
  42406. SetParentAction.prototype._prepare = function () {
  42407. };
  42408. SetParentAction.prototype.execute = function () {
  42409. if (this._target.parent === this._parent) {
  42410. return;
  42411. }
  42412. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42413. invertParentWorldMatrix.invert();
  42414. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42415. this._target.parent = this._parent;
  42416. };
  42417. SetParentAction.prototype.serialize = function (parent) {
  42418. return _super.prototype._serialize.call(this, {
  42419. name: "SetParentAction",
  42420. properties: [
  42421. BABYLON.Action._GetTargetProperty(this._target),
  42422. BABYLON.Action._GetTargetProperty(this._parent),
  42423. ]
  42424. }, parent);
  42425. };
  42426. return SetParentAction;
  42427. }(BABYLON.Action));
  42428. BABYLON.SetParentAction = SetParentAction;
  42429. var PlaySoundAction = /** @class */ (function (_super) {
  42430. __extends(PlaySoundAction, _super);
  42431. function PlaySoundAction(triggerOptions, sound, condition) {
  42432. var _this = _super.call(this, triggerOptions, condition) || this;
  42433. _this._sound = sound;
  42434. return _this;
  42435. }
  42436. PlaySoundAction.prototype._prepare = function () {
  42437. };
  42438. PlaySoundAction.prototype.execute = function () {
  42439. if (this._sound !== undefined)
  42440. this._sound.play();
  42441. };
  42442. PlaySoundAction.prototype.serialize = function (parent) {
  42443. return _super.prototype._serialize.call(this, {
  42444. name: "PlaySoundAction",
  42445. properties: [{ name: "sound", value: this._sound.name }]
  42446. }, parent);
  42447. };
  42448. return PlaySoundAction;
  42449. }(BABYLON.Action));
  42450. BABYLON.PlaySoundAction = PlaySoundAction;
  42451. var StopSoundAction = /** @class */ (function (_super) {
  42452. __extends(StopSoundAction, _super);
  42453. function StopSoundAction(triggerOptions, sound, condition) {
  42454. var _this = _super.call(this, triggerOptions, condition) || this;
  42455. _this._sound = sound;
  42456. return _this;
  42457. }
  42458. StopSoundAction.prototype._prepare = function () {
  42459. };
  42460. StopSoundAction.prototype.execute = function () {
  42461. if (this._sound !== undefined)
  42462. this._sound.stop();
  42463. };
  42464. StopSoundAction.prototype.serialize = function (parent) {
  42465. return _super.prototype._serialize.call(this, {
  42466. name: "StopSoundAction",
  42467. properties: [{ name: "sound", value: this._sound.name }]
  42468. }, parent);
  42469. };
  42470. return StopSoundAction;
  42471. }(BABYLON.Action));
  42472. BABYLON.StopSoundAction = StopSoundAction;
  42473. })(BABYLON || (BABYLON = {}));
  42474. //# sourceMappingURL=babylon.directActions.js.map
  42475. var BABYLON;
  42476. (function (BABYLON) {
  42477. var SpriteManager = /** @class */ (function () {
  42478. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42479. if (epsilon === void 0) { epsilon = 0.01; }
  42480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42481. this.name = name;
  42482. this.sprites = new Array();
  42483. this.renderingGroupId = 0;
  42484. this.layerMask = 0x0FFFFFFF;
  42485. this.fogEnabled = true;
  42486. this.isPickable = false;
  42487. /**
  42488. * An event triggered when the manager is disposed.
  42489. * @type {BABYLON.Observable}
  42490. */
  42491. this.onDisposeObservable = new BABYLON.Observable();
  42492. this._vertexBuffers = {};
  42493. this._capacity = capacity;
  42494. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42495. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42496. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42497. if (cellSize.width && cellSize.height) {
  42498. this.cellWidth = cellSize.width;
  42499. this.cellHeight = cellSize.height;
  42500. }
  42501. else if (cellSize !== undefined) {
  42502. this.cellWidth = cellSize;
  42503. this.cellHeight = cellSize;
  42504. }
  42505. else {
  42506. return;
  42507. }
  42508. this._epsilon = epsilon;
  42509. this._scene = scene;
  42510. this._scene.spriteManagers.push(this);
  42511. var indices = [];
  42512. var index = 0;
  42513. for (var count = 0; count < capacity; count++) {
  42514. indices.push(index);
  42515. indices.push(index + 1);
  42516. indices.push(index + 2);
  42517. indices.push(index);
  42518. indices.push(index + 2);
  42519. indices.push(index + 3);
  42520. index += 4;
  42521. }
  42522. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42523. // VBO
  42524. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42525. this._vertexData = new Float32Array(capacity * 16 * 4);
  42526. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42527. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42528. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42529. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42530. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42531. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42532. this._vertexBuffers["options"] = options;
  42533. this._vertexBuffers["cellInfo"] = cellInfo;
  42534. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42535. // Effects
  42536. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42537. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42538. }
  42539. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42540. set: function (callback) {
  42541. if (this._onDisposeObserver) {
  42542. this.onDisposeObservable.remove(this._onDisposeObserver);
  42543. }
  42544. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42545. },
  42546. enumerable: true,
  42547. configurable: true
  42548. });
  42549. Object.defineProperty(SpriteManager.prototype, "texture", {
  42550. get: function () {
  42551. return this._spriteTexture;
  42552. },
  42553. set: function (value) {
  42554. this._spriteTexture = value;
  42555. },
  42556. enumerable: true,
  42557. configurable: true
  42558. });
  42559. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42560. var arrayOffset = index * 16;
  42561. if (offsetX === 0)
  42562. offsetX = this._epsilon;
  42563. else if (offsetX === 1)
  42564. offsetX = 1 - this._epsilon;
  42565. if (offsetY === 0)
  42566. offsetY = this._epsilon;
  42567. else if (offsetY === 1)
  42568. offsetY = 1 - this._epsilon;
  42569. this._vertexData[arrayOffset] = sprite.position.x;
  42570. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42571. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42572. this._vertexData[arrayOffset + 3] = sprite.angle;
  42573. this._vertexData[arrayOffset + 4] = sprite.width;
  42574. this._vertexData[arrayOffset + 5] = sprite.height;
  42575. this._vertexData[arrayOffset + 6] = offsetX;
  42576. this._vertexData[arrayOffset + 7] = offsetY;
  42577. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42578. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42579. var offset = (sprite.cellIndex / rowSize) >> 0;
  42580. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42581. this._vertexData[arrayOffset + 11] = offset;
  42582. // Color
  42583. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42584. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42585. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42586. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42587. };
  42588. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42589. var count = Math.min(this._capacity, this.sprites.length);
  42590. var min = BABYLON.Vector3.Zero();
  42591. var max = BABYLON.Vector3.Zero();
  42592. var distance = Number.MAX_VALUE;
  42593. var currentSprite = null;
  42594. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42595. var cameraView = camera.getViewMatrix();
  42596. for (var index = 0; index < count; index++) {
  42597. var sprite = this.sprites[index];
  42598. if (!sprite) {
  42599. continue;
  42600. }
  42601. if (predicate) {
  42602. if (!predicate(sprite)) {
  42603. continue;
  42604. }
  42605. }
  42606. else if (!sprite.isPickable) {
  42607. continue;
  42608. }
  42609. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42610. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42611. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42612. if (ray.intersectsBoxMinMax(min, max)) {
  42613. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42614. if (distance > currentDistance) {
  42615. distance = currentDistance;
  42616. currentSprite = sprite;
  42617. if (fastCheck) {
  42618. break;
  42619. }
  42620. }
  42621. }
  42622. }
  42623. if (currentSprite) {
  42624. var result = new BABYLON.PickingInfo();
  42625. result.hit = true;
  42626. result.pickedSprite = currentSprite;
  42627. result.distance = distance;
  42628. return result;
  42629. }
  42630. return null;
  42631. };
  42632. SpriteManager.prototype.render = function () {
  42633. // Check
  42634. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42635. return;
  42636. var engine = this._scene.getEngine();
  42637. var baseSize = this._spriteTexture.getBaseSize();
  42638. // Sprites
  42639. var deltaTime = engine.getDeltaTime();
  42640. var max = Math.min(this._capacity, this.sprites.length);
  42641. var rowSize = baseSize.width / this.cellWidth;
  42642. var offset = 0;
  42643. for (var index = 0; index < max; index++) {
  42644. var sprite = this.sprites[index];
  42645. if (!sprite) {
  42646. continue;
  42647. }
  42648. sprite._animate(deltaTime);
  42649. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42650. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42651. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42652. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42653. }
  42654. this._buffer.update(this._vertexData);
  42655. // Render
  42656. var effect = this._effectBase;
  42657. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42658. effect = this._effectFog;
  42659. }
  42660. engine.enableEffect(effect);
  42661. var viewMatrix = this._scene.getViewMatrix();
  42662. effect.setTexture("diffuseSampler", this._spriteTexture);
  42663. effect.setMatrix("view", viewMatrix);
  42664. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42665. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42666. // Fog
  42667. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42668. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42669. effect.setColor3("vFogColor", this._scene.fogColor);
  42670. }
  42671. // VBOs
  42672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42673. // Draw order
  42674. engine.setDepthFunctionToLessOrEqual();
  42675. effect.setBool("alphaTest", true);
  42676. engine.setColorWrite(false);
  42677. engine.draw(true, 0, max * 6);
  42678. engine.setColorWrite(true);
  42679. effect.setBool("alphaTest", false);
  42680. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42681. engine.draw(true, 0, max * 6);
  42682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42683. };
  42684. SpriteManager.prototype.dispose = function () {
  42685. if (this._buffer) {
  42686. this._buffer.dispose();
  42687. this._buffer = null;
  42688. }
  42689. if (this._indexBuffer) {
  42690. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42691. this._indexBuffer = null;
  42692. }
  42693. if (this._spriteTexture) {
  42694. this._spriteTexture.dispose();
  42695. this._spriteTexture = null;
  42696. }
  42697. // Remove from scene
  42698. var index = this._scene.spriteManagers.indexOf(this);
  42699. this._scene.spriteManagers.splice(index, 1);
  42700. // Callback
  42701. this.onDisposeObservable.notifyObservers(this);
  42702. this.onDisposeObservable.clear();
  42703. };
  42704. return SpriteManager;
  42705. }());
  42706. BABYLON.SpriteManager = SpriteManager;
  42707. })(BABYLON || (BABYLON = {}));
  42708. //# sourceMappingURL=babylon.spriteManager.js.map
  42709. var BABYLON;
  42710. (function (BABYLON) {
  42711. var Sprite = /** @class */ (function () {
  42712. function Sprite(name, manager) {
  42713. this.name = name;
  42714. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42715. this.width = 1.0;
  42716. this.height = 1.0;
  42717. this.angle = 0;
  42718. this.cellIndex = 0;
  42719. this.invertU = 0;
  42720. this.invertV = 0;
  42721. this.animations = new Array();
  42722. this.isPickable = false;
  42723. this._animationStarted = false;
  42724. this._loopAnimation = false;
  42725. this._fromIndex = 0;
  42726. this._toIndex = 0;
  42727. this._delay = 0;
  42728. this._direction = 1;
  42729. this._time = 0;
  42730. this._manager = manager;
  42731. this._manager.sprites.push(this);
  42732. this.position = BABYLON.Vector3.Zero();
  42733. }
  42734. Object.defineProperty(Sprite.prototype, "size", {
  42735. get: function () {
  42736. return this.width;
  42737. },
  42738. set: function (value) {
  42739. this.width = value;
  42740. this.height = value;
  42741. },
  42742. enumerable: true,
  42743. configurable: true
  42744. });
  42745. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42746. this._fromIndex = from;
  42747. this._toIndex = to;
  42748. this._loopAnimation = loop;
  42749. this._delay = delay;
  42750. this._animationStarted = true;
  42751. this._direction = from < to ? 1 : -1;
  42752. this.cellIndex = from;
  42753. this._time = 0;
  42754. this._onAnimationEnd = onAnimationEnd;
  42755. };
  42756. Sprite.prototype.stopAnimation = function () {
  42757. this._animationStarted = false;
  42758. };
  42759. Sprite.prototype._animate = function (deltaTime) {
  42760. if (!this._animationStarted)
  42761. return;
  42762. this._time += deltaTime;
  42763. if (this._time > this._delay) {
  42764. this._time = this._time % this._delay;
  42765. this.cellIndex += this._direction;
  42766. if (this.cellIndex > this._toIndex) {
  42767. if (this._loopAnimation) {
  42768. this.cellIndex = this._fromIndex;
  42769. }
  42770. else {
  42771. this.cellIndex = this._toIndex;
  42772. this._animationStarted = false;
  42773. if (this._onAnimationEnd) {
  42774. this._onAnimationEnd();
  42775. }
  42776. if (this.disposeWhenFinishedAnimating) {
  42777. this.dispose();
  42778. }
  42779. }
  42780. }
  42781. }
  42782. };
  42783. Sprite.prototype.dispose = function () {
  42784. for (var i = 0; i < this._manager.sprites.length; i++) {
  42785. if (this._manager.sprites[i] == this) {
  42786. this._manager.sprites.splice(i, 1);
  42787. }
  42788. }
  42789. };
  42790. return Sprite;
  42791. }());
  42792. BABYLON.Sprite = Sprite;
  42793. })(BABYLON || (BABYLON = {}));
  42794. //# sourceMappingURL=babylon.sprite.js.map
  42795. var BABYLON;
  42796. (function (BABYLON) {
  42797. var IntersectionInfo = /** @class */ (function () {
  42798. function IntersectionInfo(bu, bv, distance) {
  42799. this.bu = bu;
  42800. this.bv = bv;
  42801. this.distance = distance;
  42802. this.faceId = 0;
  42803. this.subMeshId = 0;
  42804. }
  42805. return IntersectionInfo;
  42806. }());
  42807. BABYLON.IntersectionInfo = IntersectionInfo;
  42808. var PickingInfo = /** @class */ (function () {
  42809. function PickingInfo() {
  42810. this.hit = false;
  42811. this.distance = 0;
  42812. this.pickedPoint = null;
  42813. this.pickedMesh = null;
  42814. this.bu = 0;
  42815. this.bv = 0;
  42816. this.faceId = -1;
  42817. this.subMeshId = 0;
  42818. this.pickedSprite = null;
  42819. }
  42820. // Methods
  42821. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42822. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42823. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42824. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42825. return null;
  42826. }
  42827. var indices = this.pickedMesh.getIndices();
  42828. if (!indices) {
  42829. return null;
  42830. }
  42831. var result;
  42832. if (useVerticesNormals) {
  42833. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42834. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42835. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42836. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42837. normal0 = normal0.scale(this.bu);
  42838. normal1 = normal1.scale(this.bv);
  42839. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42840. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42841. }
  42842. else {
  42843. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42844. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42845. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42846. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42847. var p1p2 = vertex1.subtract(vertex2);
  42848. var p3p2 = vertex3.subtract(vertex2);
  42849. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42850. }
  42851. if (useWorldCoordinates) {
  42852. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42853. }
  42854. return BABYLON.Vector3.Normalize(result);
  42855. };
  42856. PickingInfo.prototype.getTextureCoordinates = function () {
  42857. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42858. return null;
  42859. }
  42860. var indices = this.pickedMesh.getIndices();
  42861. if (!indices) {
  42862. return null;
  42863. }
  42864. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42865. if (!uvs) {
  42866. return null;
  42867. }
  42868. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42869. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42870. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42871. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42872. uv1 = uv1.scale(this.bu);
  42873. uv2 = uv2.scale(this.bv);
  42874. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42875. };
  42876. return PickingInfo;
  42877. }());
  42878. BABYLON.PickingInfo = PickingInfo;
  42879. })(BABYLON || (BABYLON = {}));
  42880. //# sourceMappingURL=babylon.pickingInfo.js.map
  42881. var BABYLON;
  42882. (function (BABYLON) {
  42883. var Ray = /** @class */ (function () {
  42884. function Ray(origin, direction, length) {
  42885. if (length === void 0) { length = Number.MAX_VALUE; }
  42886. this.origin = origin;
  42887. this.direction = direction;
  42888. this.length = length;
  42889. }
  42890. // Methods
  42891. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42892. var d = 0.0;
  42893. var maxValue = Number.MAX_VALUE;
  42894. var inv;
  42895. var min;
  42896. var max;
  42897. var temp;
  42898. if (Math.abs(this.direction.x) < 0.0000001) {
  42899. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42900. return false;
  42901. }
  42902. }
  42903. else {
  42904. inv = 1.0 / this.direction.x;
  42905. min = (minimum.x - this.origin.x) * inv;
  42906. max = (maximum.x - this.origin.x) * inv;
  42907. if (max === -Infinity) {
  42908. max = Infinity;
  42909. }
  42910. if (min > max) {
  42911. temp = min;
  42912. min = max;
  42913. max = temp;
  42914. }
  42915. d = Math.max(min, d);
  42916. maxValue = Math.min(max, maxValue);
  42917. if (d > maxValue) {
  42918. return false;
  42919. }
  42920. }
  42921. if (Math.abs(this.direction.y) < 0.0000001) {
  42922. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42923. return false;
  42924. }
  42925. }
  42926. else {
  42927. inv = 1.0 / this.direction.y;
  42928. min = (minimum.y - this.origin.y) * inv;
  42929. max = (maximum.y - this.origin.y) * inv;
  42930. if (max === -Infinity) {
  42931. max = Infinity;
  42932. }
  42933. if (min > max) {
  42934. temp = min;
  42935. min = max;
  42936. max = temp;
  42937. }
  42938. d = Math.max(min, d);
  42939. maxValue = Math.min(max, maxValue);
  42940. if (d > maxValue) {
  42941. return false;
  42942. }
  42943. }
  42944. if (Math.abs(this.direction.z) < 0.0000001) {
  42945. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42946. return false;
  42947. }
  42948. }
  42949. else {
  42950. inv = 1.0 / this.direction.z;
  42951. min = (minimum.z - this.origin.z) * inv;
  42952. max = (maximum.z - this.origin.z) * inv;
  42953. if (max === -Infinity) {
  42954. max = Infinity;
  42955. }
  42956. if (min > max) {
  42957. temp = min;
  42958. min = max;
  42959. max = temp;
  42960. }
  42961. d = Math.max(min, d);
  42962. maxValue = Math.min(max, maxValue);
  42963. if (d > maxValue) {
  42964. return false;
  42965. }
  42966. }
  42967. return true;
  42968. };
  42969. Ray.prototype.intersectsBox = function (box) {
  42970. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42971. };
  42972. Ray.prototype.intersectsSphere = function (sphere) {
  42973. var x = sphere.center.x - this.origin.x;
  42974. var y = sphere.center.y - this.origin.y;
  42975. var z = sphere.center.z - this.origin.z;
  42976. var pyth = (x * x) + (y * y) + (z * z);
  42977. var rr = sphere.radius * sphere.radius;
  42978. if (pyth <= rr) {
  42979. return true;
  42980. }
  42981. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42982. if (dot < 0.0) {
  42983. return false;
  42984. }
  42985. var temp = pyth - (dot * dot);
  42986. return temp <= rr;
  42987. };
  42988. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42989. if (!this._edge1) {
  42990. this._edge1 = BABYLON.Vector3.Zero();
  42991. this._edge2 = BABYLON.Vector3.Zero();
  42992. this._pvec = BABYLON.Vector3.Zero();
  42993. this._tvec = BABYLON.Vector3.Zero();
  42994. this._qvec = BABYLON.Vector3.Zero();
  42995. }
  42996. vertex1.subtractToRef(vertex0, this._edge1);
  42997. vertex2.subtractToRef(vertex0, this._edge2);
  42998. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42999. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43000. if (det === 0) {
  43001. return null;
  43002. }
  43003. var invdet = 1 / det;
  43004. this.origin.subtractToRef(vertex0, this._tvec);
  43005. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43006. if (bu < 0 || bu > 1.0) {
  43007. return null;
  43008. }
  43009. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43010. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43011. if (bv < 0 || bu + bv > 1.0) {
  43012. return null;
  43013. }
  43014. //check if the distance is longer than the predefined length.
  43015. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43016. if (distance > this.length) {
  43017. return null;
  43018. }
  43019. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43020. };
  43021. Ray.prototype.intersectsPlane = function (plane) {
  43022. var distance;
  43023. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43024. if (Math.abs(result1) < 9.99999997475243E-07) {
  43025. return null;
  43026. }
  43027. else {
  43028. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43029. distance = (-plane.d - result2) / result1;
  43030. if (distance < 0.0) {
  43031. if (distance < -9.99999997475243E-07) {
  43032. return null;
  43033. }
  43034. else {
  43035. return 0;
  43036. }
  43037. }
  43038. return distance;
  43039. }
  43040. };
  43041. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43042. var tm = BABYLON.Tmp.Matrix[0];
  43043. mesh.getWorldMatrix().invertToRef(tm);
  43044. if (this._tmpRay) {
  43045. Ray.TransformToRef(this, tm, this._tmpRay);
  43046. }
  43047. else {
  43048. this._tmpRay = Ray.Transform(this, tm);
  43049. }
  43050. return mesh.intersects(this._tmpRay, fastCheck);
  43051. };
  43052. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43053. if (results) {
  43054. results.length = 0;
  43055. }
  43056. else {
  43057. results = [];
  43058. }
  43059. for (var i = 0; i < meshes.length; i++) {
  43060. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43061. if (pickInfo.hit) {
  43062. results.push(pickInfo);
  43063. }
  43064. }
  43065. results.sort(this._comparePickingInfo);
  43066. return results;
  43067. };
  43068. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43069. if (pickingInfoA.distance < pickingInfoB.distance) {
  43070. return -1;
  43071. }
  43072. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43073. return 1;
  43074. }
  43075. else {
  43076. return 0;
  43077. }
  43078. };
  43079. /**
  43080. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43081. * @param sega the first point of the segment to test the intersection against
  43082. * @param segb the second point of the segment to test the intersection against
  43083. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43084. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43085. */
  43086. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43087. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43088. var u = segb.subtract(sega);
  43089. var v = rsegb.subtract(this.origin);
  43090. var w = sega.subtract(this.origin);
  43091. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43092. var b = BABYLON.Vector3.Dot(u, v);
  43093. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43094. var d = BABYLON.Vector3.Dot(u, w);
  43095. var e = BABYLON.Vector3.Dot(v, w);
  43096. var D = a * c - b * b; // always >= 0
  43097. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43098. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43099. // compute the line parameters of the two closest points
  43100. if (D < Ray.smallnum) {
  43101. sN = 0.0; // force using point P0 on segment S1
  43102. sD = 1.0; // to prevent possible division by 0.0 later
  43103. tN = e;
  43104. tD = c;
  43105. }
  43106. else {
  43107. sN = (b * e - c * d);
  43108. tN = (a * e - b * d);
  43109. if (sN < 0.0) {
  43110. sN = 0.0;
  43111. tN = e;
  43112. tD = c;
  43113. }
  43114. else if (sN > sD) {
  43115. sN = sD;
  43116. tN = e + b;
  43117. tD = c;
  43118. }
  43119. }
  43120. if (tN < 0.0) {
  43121. tN = 0.0;
  43122. // recompute sc for this edge
  43123. if (-d < 0.0) {
  43124. sN = 0.0;
  43125. }
  43126. else if (-d > a)
  43127. sN = sD;
  43128. else {
  43129. sN = -d;
  43130. sD = a;
  43131. }
  43132. }
  43133. else if (tN > tD) {
  43134. tN = tD;
  43135. // recompute sc for this edge
  43136. if ((-d + b) < 0.0) {
  43137. sN = 0;
  43138. }
  43139. else if ((-d + b) > a) {
  43140. sN = sD;
  43141. }
  43142. else {
  43143. sN = (-d + b);
  43144. sD = a;
  43145. }
  43146. }
  43147. // finally do the division to get sc and tc
  43148. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43149. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43150. // get the difference of the two closest points
  43151. var qtc = v.multiplyByFloats(tc, tc, tc);
  43152. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43153. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43154. if (isIntersected) {
  43155. return qtc.length();
  43156. }
  43157. return -1;
  43158. };
  43159. // Statics
  43160. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43161. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43162. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43163. var direction = end.subtract(start);
  43164. direction.normalize();
  43165. return new Ray(start, direction);
  43166. };
  43167. /**
  43168. * 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
  43169. * transformed to the given world matrix.
  43170. * @param origin The origin point
  43171. * @param end The end point
  43172. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43173. */
  43174. Ray.CreateNewFromTo = function (origin, end, world) {
  43175. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43176. var direction = end.subtract(origin);
  43177. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43178. direction.normalize();
  43179. return Ray.Transform(new Ray(origin, direction, length), world);
  43180. };
  43181. Ray.Transform = function (ray, matrix) {
  43182. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43183. Ray.TransformToRef(ray, matrix, result);
  43184. return result;
  43185. };
  43186. Ray.TransformToRef = function (ray, matrix, result) {
  43187. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43188. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43189. result.length = ray.length;
  43190. var dir = result.direction;
  43191. var len = dir.length();
  43192. if (!(len === 0 || len === 1)) {
  43193. var num = 1.0 / len;
  43194. dir.x *= num;
  43195. dir.y *= num;
  43196. dir.z *= num;
  43197. result.length *= len;
  43198. }
  43199. };
  43200. Ray.smallnum = 0.00000001;
  43201. Ray.rayl = 10e8;
  43202. return Ray;
  43203. }());
  43204. BABYLON.Ray = Ray;
  43205. })(BABYLON || (BABYLON = {}));
  43206. //# sourceMappingURL=babylon.ray.js.map
  43207. var BABYLON;
  43208. (function (BABYLON) {
  43209. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43210. if (boxMin.x > sphereCenter.x + sphereRadius)
  43211. return false;
  43212. if (sphereCenter.x - sphereRadius > boxMax.x)
  43213. return false;
  43214. if (boxMin.y > sphereCenter.y + sphereRadius)
  43215. return false;
  43216. if (sphereCenter.y - sphereRadius > boxMax.y)
  43217. return false;
  43218. if (boxMin.z > sphereCenter.z + sphereRadius)
  43219. return false;
  43220. if (sphereCenter.z - sphereRadius > boxMax.z)
  43221. return false;
  43222. return true;
  43223. };
  43224. var getLowestRoot = (function () {
  43225. var result = { root: 0, found: false };
  43226. return function (a, b, c, maxR) {
  43227. result.root = 0;
  43228. result.found = false;
  43229. var determinant = b * b - 4.0 * a * c;
  43230. if (determinant < 0)
  43231. return result;
  43232. var sqrtD = Math.sqrt(determinant);
  43233. var r1 = (-b - sqrtD) / (2.0 * a);
  43234. var r2 = (-b + sqrtD) / (2.0 * a);
  43235. if (r1 > r2) {
  43236. var temp = r2;
  43237. r2 = r1;
  43238. r1 = temp;
  43239. }
  43240. if (r1 > 0 && r1 < maxR) {
  43241. result.root = r1;
  43242. result.found = true;
  43243. return result;
  43244. }
  43245. if (r2 > 0 && r2 < maxR) {
  43246. result.root = r2;
  43247. result.found = true;
  43248. return result;
  43249. }
  43250. return result;
  43251. };
  43252. })();
  43253. var Collider = /** @class */ (function () {
  43254. function Collider() {
  43255. this.radius = BABYLON.Vector3.One();
  43256. this.retry = 0;
  43257. this.basePointWorld = BABYLON.Vector3.Zero();
  43258. this.velocityWorld = BABYLON.Vector3.Zero();
  43259. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43260. this._collisionPoint = BABYLON.Vector3.Zero();
  43261. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43262. this._tempVector = BABYLON.Vector3.Zero();
  43263. this._tempVector2 = BABYLON.Vector3.Zero();
  43264. this._tempVector3 = BABYLON.Vector3.Zero();
  43265. this._tempVector4 = BABYLON.Vector3.Zero();
  43266. this._edge = BABYLON.Vector3.Zero();
  43267. this._baseToVertex = BABYLON.Vector3.Zero();
  43268. this._destinationPoint = BABYLON.Vector3.Zero();
  43269. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43270. this._displacementVector = BABYLON.Vector3.Zero();
  43271. this._collisionMask = -1;
  43272. }
  43273. Object.defineProperty(Collider.prototype, "collisionMask", {
  43274. get: function () {
  43275. return this._collisionMask;
  43276. },
  43277. set: function (mask) {
  43278. this._collisionMask = !isNaN(mask) ? mask : -1;
  43279. },
  43280. enumerable: true,
  43281. configurable: true
  43282. });
  43283. // Methods
  43284. Collider.prototype._initialize = function (source, dir, e) {
  43285. this.velocity = dir;
  43286. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43287. this.basePoint = source;
  43288. source.multiplyToRef(this.radius, this.basePointWorld);
  43289. dir.multiplyToRef(this.radius, this.velocityWorld);
  43290. this.velocityWorldLength = this.velocityWorld.length();
  43291. this.epsilon = e;
  43292. this.collisionFound = false;
  43293. };
  43294. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43295. pa.subtractToRef(point, this._tempVector);
  43296. pb.subtractToRef(point, this._tempVector2);
  43297. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43298. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43299. if (d < 0)
  43300. return false;
  43301. pc.subtractToRef(point, this._tempVector3);
  43302. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43303. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43304. if (d < 0)
  43305. return false;
  43306. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43307. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43308. return d >= 0;
  43309. };
  43310. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43311. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43312. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43313. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43314. return false;
  43315. }
  43316. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43317. return false;
  43318. return true;
  43319. };
  43320. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43321. var t0;
  43322. var embeddedInPlane = false;
  43323. //defensive programming, actually not needed.
  43324. if (!trianglePlaneArray) {
  43325. trianglePlaneArray = [];
  43326. }
  43327. if (!trianglePlaneArray[faceIndex]) {
  43328. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43329. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43330. }
  43331. var trianglePlane = trianglePlaneArray[faceIndex];
  43332. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43333. return;
  43334. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43335. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43336. if (normalDotVelocity == 0) {
  43337. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43338. return;
  43339. embeddedInPlane = true;
  43340. t0 = 0;
  43341. }
  43342. else {
  43343. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43344. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43345. if (t0 > t1) {
  43346. var temp = t1;
  43347. t1 = t0;
  43348. t0 = temp;
  43349. }
  43350. if (t0 > 1.0 || t1 < 0.0)
  43351. return;
  43352. if (t0 < 0)
  43353. t0 = 0;
  43354. if (t0 > 1.0)
  43355. t0 = 1.0;
  43356. }
  43357. this._collisionPoint.copyFromFloats(0, 0, 0);
  43358. var found = false;
  43359. var t = 1.0;
  43360. if (!embeddedInPlane) {
  43361. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43362. this.velocity.scaleToRef(t0, this._tempVector);
  43363. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43364. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43365. found = true;
  43366. t = t0;
  43367. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43368. }
  43369. }
  43370. if (!found) {
  43371. var velocitySquaredLength = this.velocity.lengthSquared();
  43372. var a = velocitySquaredLength;
  43373. this.basePoint.subtractToRef(p1, this._tempVector);
  43374. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43375. var c = this._tempVector.lengthSquared() - 1.0;
  43376. var lowestRoot = getLowestRoot(a, b, c, t);
  43377. if (lowestRoot.found) {
  43378. t = lowestRoot.root;
  43379. found = true;
  43380. this._collisionPoint.copyFrom(p1);
  43381. }
  43382. this.basePoint.subtractToRef(p2, this._tempVector);
  43383. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43384. c = this._tempVector.lengthSquared() - 1.0;
  43385. lowestRoot = getLowestRoot(a, b, c, t);
  43386. if (lowestRoot.found) {
  43387. t = lowestRoot.root;
  43388. found = true;
  43389. this._collisionPoint.copyFrom(p2);
  43390. }
  43391. this.basePoint.subtractToRef(p3, this._tempVector);
  43392. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43393. c = this._tempVector.lengthSquared() - 1.0;
  43394. lowestRoot = getLowestRoot(a, b, c, t);
  43395. if (lowestRoot.found) {
  43396. t = lowestRoot.root;
  43397. found = true;
  43398. this._collisionPoint.copyFrom(p3);
  43399. }
  43400. p2.subtractToRef(p1, this._edge);
  43401. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43402. var edgeSquaredLength = this._edge.lengthSquared();
  43403. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43404. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43405. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43406. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43407. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43408. lowestRoot = getLowestRoot(a, b, c, t);
  43409. if (lowestRoot.found) {
  43410. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43411. if (f >= 0.0 && f <= 1.0) {
  43412. t = lowestRoot.root;
  43413. found = true;
  43414. this._edge.scaleInPlace(f);
  43415. p1.addToRef(this._edge, this._collisionPoint);
  43416. }
  43417. }
  43418. p3.subtractToRef(p2, this._edge);
  43419. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43420. edgeSquaredLength = this._edge.lengthSquared();
  43421. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43422. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43423. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43424. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43425. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43426. lowestRoot = getLowestRoot(a, b, c, t);
  43427. if (lowestRoot.found) {
  43428. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43429. if (f >= 0.0 && f <= 1.0) {
  43430. t = lowestRoot.root;
  43431. found = true;
  43432. this._edge.scaleInPlace(f);
  43433. p2.addToRef(this._edge, this._collisionPoint);
  43434. }
  43435. }
  43436. p1.subtractToRef(p3, this._edge);
  43437. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43438. edgeSquaredLength = this._edge.lengthSquared();
  43439. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43440. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43441. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43442. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43443. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43444. lowestRoot = getLowestRoot(a, b, c, t);
  43445. if (lowestRoot.found) {
  43446. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43447. if (f >= 0.0 && f <= 1.0) {
  43448. t = lowestRoot.root;
  43449. found = true;
  43450. this._edge.scaleInPlace(f);
  43451. p3.addToRef(this._edge, this._collisionPoint);
  43452. }
  43453. }
  43454. }
  43455. if (found) {
  43456. var distToCollision = t * this.velocity.length();
  43457. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43458. if (!this.intersectionPoint) {
  43459. this.intersectionPoint = this._collisionPoint.clone();
  43460. }
  43461. else {
  43462. this.intersectionPoint.copyFrom(this._collisionPoint);
  43463. }
  43464. this.nearestDistance = distToCollision;
  43465. this.collisionFound = true;
  43466. }
  43467. }
  43468. };
  43469. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43470. for (var i = indexStart; i < indexEnd; i += 3) {
  43471. var p1 = pts[indices[i] - decal];
  43472. var p2 = pts[indices[i + 1] - decal];
  43473. var p3 = pts[indices[i + 2] - decal];
  43474. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43475. }
  43476. };
  43477. Collider.prototype._getResponse = function (pos, vel) {
  43478. pos.addToRef(vel, this._destinationPoint);
  43479. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43480. this.basePoint.addToRef(vel, pos);
  43481. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43482. this._slidePlaneNormal.normalize();
  43483. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43484. pos.addInPlace(this._displacementVector);
  43485. this.intersectionPoint.addInPlace(this._displacementVector);
  43486. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43487. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43488. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43489. };
  43490. return Collider;
  43491. }());
  43492. BABYLON.Collider = Collider;
  43493. })(BABYLON || (BABYLON = {}));
  43494. //# sourceMappingURL=babylon.collider.js.map
  43495. var BABYLON;
  43496. (function (BABYLON) {
  43497. //WebWorker code will be inserted to this variable.
  43498. BABYLON.CollisionWorker = "";
  43499. var WorkerTaskType;
  43500. (function (WorkerTaskType) {
  43501. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43502. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43503. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43504. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43505. var WorkerReplyType;
  43506. (function (WorkerReplyType) {
  43507. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43508. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43509. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43510. var CollisionCoordinatorWorker = /** @class */ (function () {
  43511. function CollisionCoordinatorWorker() {
  43512. var _this = this;
  43513. this._scaledPosition = BABYLON.Vector3.Zero();
  43514. this._scaledVelocity = BABYLON.Vector3.Zero();
  43515. this.onMeshUpdated = function (mesh) {
  43516. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43517. };
  43518. this.onGeometryUpdated = function (geometry) {
  43519. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43520. };
  43521. this._afterRender = function () {
  43522. if (!_this._init)
  43523. return;
  43524. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43525. return;
  43526. }
  43527. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43528. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43529. if (_this._runningUpdated > 4) {
  43530. return;
  43531. }
  43532. ++_this._runningUpdated;
  43533. var payload = {
  43534. updatedMeshes: _this._addUpdateMeshesList,
  43535. updatedGeometries: _this._addUpdateGeometriesList,
  43536. removedGeometries: _this._toRemoveGeometryArray,
  43537. removedMeshes: _this._toRemoveMeshesArray
  43538. };
  43539. var message = {
  43540. payload: payload,
  43541. taskType: WorkerTaskType.UPDATE
  43542. };
  43543. var serializable = [];
  43544. for (var id in payload.updatedGeometries) {
  43545. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43546. //prepare transferables
  43547. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43548. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43549. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43550. }
  43551. }
  43552. _this._worker.postMessage(message, serializable);
  43553. _this._addUpdateMeshesList = {};
  43554. _this._addUpdateGeometriesList = {};
  43555. _this._toRemoveGeometryArray = [];
  43556. _this._toRemoveMeshesArray = [];
  43557. };
  43558. this._onMessageFromWorker = function (e) {
  43559. var returnData = e.data;
  43560. if (returnData.error != WorkerReplyType.SUCCESS) {
  43561. //TODO what errors can be returned from the worker?
  43562. BABYLON.Tools.Warn("error returned from worker!");
  43563. return;
  43564. }
  43565. switch (returnData.taskType) {
  43566. case WorkerTaskType.INIT:
  43567. _this._init = true;
  43568. //Update the worked with ALL of the scene's current state
  43569. _this._scene.meshes.forEach(function (mesh) {
  43570. _this.onMeshAdded(mesh);
  43571. });
  43572. _this._scene.getGeometries().forEach(function (geometry) {
  43573. _this.onGeometryAdded(geometry);
  43574. });
  43575. break;
  43576. case WorkerTaskType.UPDATE:
  43577. _this._runningUpdated--;
  43578. break;
  43579. case WorkerTaskType.COLLIDE:
  43580. _this._runningCollisionTask = false;
  43581. var returnPayload = returnData.payload;
  43582. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43583. return;
  43584. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43585. if (callback) {
  43586. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43587. if (mesh) {
  43588. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43589. }
  43590. }
  43591. //cleanup
  43592. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43593. break;
  43594. }
  43595. };
  43596. this._collisionsCallbackArray = [];
  43597. this._init = false;
  43598. this._runningUpdated = 0;
  43599. this._runningCollisionTask = false;
  43600. this._addUpdateMeshesList = {};
  43601. this._addUpdateGeometriesList = {};
  43602. this._toRemoveGeometryArray = [];
  43603. this._toRemoveMeshesArray = [];
  43604. }
  43605. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43606. if (!this._init)
  43607. return;
  43608. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43609. return;
  43610. position.divideToRef(collider.radius, this._scaledPosition);
  43611. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43612. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43613. var payload = {
  43614. collider: {
  43615. position: this._scaledPosition.asArray(),
  43616. velocity: this._scaledVelocity.asArray(),
  43617. radius: collider.radius.asArray()
  43618. },
  43619. collisionId: collisionIndex,
  43620. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43621. maximumRetry: maximumRetry
  43622. };
  43623. var message = {
  43624. payload: payload,
  43625. taskType: WorkerTaskType.COLLIDE
  43626. };
  43627. this._worker.postMessage(message);
  43628. };
  43629. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43630. this._scene = scene;
  43631. this._scene.registerAfterRender(this._afterRender);
  43632. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43633. this._worker = new Worker(workerUrl);
  43634. this._worker.onmessage = this._onMessageFromWorker;
  43635. var message = {
  43636. payload: {},
  43637. taskType: WorkerTaskType.INIT
  43638. };
  43639. this._worker.postMessage(message);
  43640. };
  43641. CollisionCoordinatorWorker.prototype.destroy = function () {
  43642. this._scene.unregisterAfterRender(this._afterRender);
  43643. this._worker.terminate();
  43644. };
  43645. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43646. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43647. this.onMeshUpdated(mesh);
  43648. };
  43649. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43650. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43651. };
  43652. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43653. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43654. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43655. this.onGeometryUpdated(geometry);
  43656. };
  43657. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43658. this._toRemoveGeometryArray.push(geometry.id);
  43659. };
  43660. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43661. var submeshes = [];
  43662. if (mesh.subMeshes) {
  43663. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43664. var boundingInfo = sm.getBoundingInfo();
  43665. return {
  43666. position: idx,
  43667. verticesStart: sm.verticesStart,
  43668. verticesCount: sm.verticesCount,
  43669. indexStart: sm.indexStart,
  43670. indexCount: sm.indexCount,
  43671. hasMaterial: !!sm.getMaterial(),
  43672. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43673. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43674. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43675. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43676. };
  43677. });
  43678. }
  43679. var geometryId = null;
  43680. if (mesh instanceof BABYLON.Mesh) {
  43681. var geometry = mesh.geometry;
  43682. geometryId = geometry ? geometry.id : null;
  43683. }
  43684. else if (mesh instanceof BABYLON.InstancedMesh) {
  43685. var geometry = mesh.sourceMesh.geometry;
  43686. geometryId = geometry ? geometry.id : null;
  43687. }
  43688. var boundingInfo = mesh.getBoundingInfo();
  43689. return {
  43690. uniqueId: mesh.uniqueId,
  43691. id: mesh.id,
  43692. name: mesh.name,
  43693. geometryId: geometryId,
  43694. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43695. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43696. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43697. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43698. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43699. subMeshes: submeshes,
  43700. checkCollisions: mesh.checkCollisions
  43701. };
  43702. };
  43703. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43704. return {
  43705. id: geometry.id,
  43706. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43707. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43708. indices: new Uint32Array(geometry.getIndices() || []),
  43709. };
  43710. };
  43711. return CollisionCoordinatorWorker;
  43712. }());
  43713. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43714. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43715. function CollisionCoordinatorLegacy() {
  43716. this._scaledPosition = BABYLON.Vector3.Zero();
  43717. this._scaledVelocity = BABYLON.Vector3.Zero();
  43718. this._finalPosition = BABYLON.Vector3.Zero();
  43719. }
  43720. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43721. position.divideToRef(collider.radius, this._scaledPosition);
  43722. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43723. collider.collidedMesh = null;
  43724. collider.retry = 0;
  43725. collider.initialVelocity = this._scaledVelocity;
  43726. collider.initialPosition = this._scaledPosition;
  43727. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43728. this._finalPosition.multiplyInPlace(collider.radius);
  43729. //run the callback
  43730. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43731. };
  43732. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43733. this._scene = scene;
  43734. };
  43735. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43736. //Legacy need no destruction method.
  43737. };
  43738. //No update in legacy mode
  43739. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43740. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43741. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43742. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43743. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43744. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43745. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43746. if (excludedMesh === void 0) { excludedMesh = null; }
  43747. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43748. if (collider.retry >= maximumRetry) {
  43749. finalPosition.copyFrom(position);
  43750. return;
  43751. }
  43752. // Check if this is a mesh else camera or -1
  43753. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43754. collider._initialize(position, velocity, closeDistance);
  43755. // Check all meshes
  43756. for (var index = 0; index < this._scene.meshes.length; index++) {
  43757. var mesh = this._scene.meshes[index];
  43758. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43759. mesh._checkCollision(collider);
  43760. }
  43761. }
  43762. if (!collider.collisionFound) {
  43763. position.addToRef(velocity, finalPosition);
  43764. return;
  43765. }
  43766. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43767. collider._getResponse(position, velocity);
  43768. }
  43769. if (velocity.length() <= closeDistance) {
  43770. finalPosition.copyFrom(position);
  43771. return;
  43772. }
  43773. collider.retry++;
  43774. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43775. };
  43776. return CollisionCoordinatorLegacy;
  43777. }());
  43778. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43779. })(BABYLON || (BABYLON = {}));
  43780. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43781. var BABYLON;
  43782. (function (BABYLON) {
  43783. var Particle = /** @class */ (function () {
  43784. function Particle(particleSystem) {
  43785. this.particleSystem = particleSystem;
  43786. this.position = BABYLON.Vector3.Zero();
  43787. this.direction = BABYLON.Vector3.Zero();
  43788. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43789. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43790. this.lifeTime = 1.0;
  43791. this.age = 0;
  43792. this.size = 0;
  43793. this.angle = 0;
  43794. this.angularSpeed = 0;
  43795. this._currentFrameCounter = 0;
  43796. this.cellIndex = 0;
  43797. if (!this.particleSystem.isAnimationSheetEnabled) {
  43798. return;
  43799. }
  43800. this.cellIndex = this.particleSystem.startSpriteCellID;
  43801. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43802. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43803. }
  43804. else {
  43805. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43806. }
  43807. }
  43808. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43809. // (ageOffset / scaledUpdateSpeed) / available cells
  43810. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43811. this._currentFrameCounter += scaledUpdateSpeed;
  43812. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43813. this._currentFrameCounter = 0;
  43814. this.cellIndex++;
  43815. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43816. this.cellIndex = this.particleSystem.endSpriteCellID;
  43817. }
  43818. }
  43819. };
  43820. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43821. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43822. this.cellIndex++;
  43823. this._currentFrameCounter = 0;
  43824. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43825. if (this.particleSystem.spriteCellLoop) {
  43826. this.cellIndex = this.particleSystem.startSpriteCellID;
  43827. }
  43828. else {
  43829. this.cellIndex = this.particleSystem.endSpriteCellID;
  43830. }
  43831. }
  43832. }
  43833. else {
  43834. this._currentFrameCounter++;
  43835. }
  43836. };
  43837. Particle.prototype.copyTo = function (other) {
  43838. other.position.copyFrom(this.position);
  43839. other.direction.copyFrom(this.direction);
  43840. other.color.copyFrom(this.color);
  43841. other.colorStep.copyFrom(this.colorStep);
  43842. other.lifeTime = this.lifeTime;
  43843. other.age = this.age;
  43844. other.size = this.size;
  43845. other.angle = this.angle;
  43846. other.angularSpeed = this.angularSpeed;
  43847. other.particleSystem = this.particleSystem;
  43848. other.cellIndex = this.cellIndex;
  43849. };
  43850. return Particle;
  43851. }());
  43852. BABYLON.Particle = Particle;
  43853. })(BABYLON || (BABYLON = {}));
  43854. //# sourceMappingURL=babylon.particle.js.map
  43855. var BABYLON;
  43856. (function (BABYLON) {
  43857. var randomNumber = function (min, max) {
  43858. if (min === max) {
  43859. return (min);
  43860. }
  43861. var random = Math.random();
  43862. return ((random * (max - min)) + min);
  43863. };
  43864. var ParticleSystem = /** @class */ (function () {
  43865. // end of sheet animation
  43866. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43867. if (customEffect === void 0) { customEffect = null; }
  43868. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43869. if (epsilon === void 0) { epsilon = 0.01; }
  43870. var _this = this;
  43871. this.name = name;
  43872. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43873. // Members
  43874. this.animations = [];
  43875. this.renderingGroupId = 0;
  43876. this.emitter = null;
  43877. this.emitRate = 10;
  43878. this.manualEmitCount = -1;
  43879. this.updateSpeed = 0.01;
  43880. this.targetStopDuration = 0;
  43881. this.disposeOnStop = false;
  43882. this.minEmitPower = 1;
  43883. this.maxEmitPower = 1;
  43884. this.minLifeTime = 1;
  43885. this.maxLifeTime = 1;
  43886. this.minSize = 1;
  43887. this.maxSize = 1;
  43888. this.minAngularSpeed = 0;
  43889. this.maxAngularSpeed = 0;
  43890. this.layerMask = 0x0FFFFFFF;
  43891. this.customShader = null;
  43892. this.preventAutoStart = false;
  43893. /**
  43894. * An event triggered when the system is disposed.
  43895. * @type {BABYLON.Observable}
  43896. */
  43897. this.onDisposeObservable = new BABYLON.Observable();
  43898. this.onAnimationEnd = null;
  43899. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43900. this.forceDepthWrite = false;
  43901. this.gravity = BABYLON.Vector3.Zero();
  43902. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43903. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43904. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43905. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43906. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43907. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43908. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43909. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43910. this.particles = new Array();
  43911. this._stockParticles = new Array();
  43912. this._newPartsExcess = 0;
  43913. this._vertexBuffers = {};
  43914. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43915. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43916. this._scaledDirection = BABYLON.Vector3.Zero();
  43917. this._scaledGravity = BABYLON.Vector3.Zero();
  43918. this._currentRenderId = -1;
  43919. this._started = false;
  43920. this._stopped = false;
  43921. this._actualFrame = 0;
  43922. // sheet animation
  43923. this.startSpriteCellID = 0;
  43924. this.endSpriteCellID = 0;
  43925. this.spriteCellLoop = true;
  43926. this.spriteCellChangeSpeed = 0;
  43927. this.spriteCellWidth = 0;
  43928. this.spriteCellHeight = 0;
  43929. this._vertexBufferSize = 11;
  43930. this.appendParticleVertexes = null;
  43931. this.id = name;
  43932. this._capacity = capacity;
  43933. this._epsilon = epsilon;
  43934. if (_isAnimationSheetEnabled) {
  43935. this._vertexBufferSize = 12;
  43936. }
  43937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43938. this._customEffect = customEffect;
  43939. scene.particleSystems.push(this);
  43940. this._createIndexBuffer();
  43941. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43942. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43943. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43944. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43945. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43946. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43947. if (this._isAnimationSheetEnabled) {
  43948. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43949. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43950. }
  43951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43952. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43953. this._vertexBuffers["options"] = options;
  43954. // Default behaviors
  43955. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43956. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43957. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43958. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43959. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43960. };
  43961. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43962. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43963. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43964. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43966. };
  43967. this.updateFunction = function (particles) {
  43968. for (var index = 0; index < particles.length; index++) {
  43969. var particle = particles[index];
  43970. particle.age += _this._scaledUpdateSpeed;
  43971. if (particle.age >= particle.lifeTime) {
  43972. _this.recycleParticle(particle);
  43973. index--;
  43974. continue;
  43975. }
  43976. else {
  43977. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43978. particle.color.addInPlace(_this._scaledColorStep);
  43979. if (particle.color.a < 0)
  43980. particle.color.a = 0;
  43981. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43982. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43983. particle.position.addInPlace(_this._scaledDirection);
  43984. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43985. particle.direction.addInPlace(_this._scaledGravity);
  43986. if (_this._isAnimationSheetEnabled) {
  43987. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43988. }
  43989. }
  43990. }
  43991. };
  43992. }
  43993. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43994. set: function (callback) {
  43995. if (this._onDisposeObserver) {
  43996. this.onDisposeObservable.remove(this._onDisposeObserver);
  43997. }
  43998. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44004. get: function () {
  44005. return this._isAnimationSheetEnabled;
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. ParticleSystem.prototype._createIndexBuffer = function () {
  44011. var indices = [];
  44012. var index = 0;
  44013. for (var count = 0; count < this._capacity; count++) {
  44014. indices.push(index);
  44015. indices.push(index + 1);
  44016. indices.push(index + 2);
  44017. indices.push(index);
  44018. indices.push(index + 2);
  44019. indices.push(index + 3);
  44020. index += 4;
  44021. }
  44022. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44023. };
  44024. ParticleSystem.prototype.recycleParticle = function (particle) {
  44025. var lastParticle = this.particles.pop();
  44026. if (lastParticle !== particle) {
  44027. lastParticle.copyTo(particle);
  44028. this._stockParticles.push(lastParticle);
  44029. }
  44030. };
  44031. ParticleSystem.prototype.getCapacity = function () {
  44032. return this._capacity;
  44033. };
  44034. ParticleSystem.prototype.isAlive = function () {
  44035. return this._alive;
  44036. };
  44037. ParticleSystem.prototype.isStarted = function () {
  44038. return this._started;
  44039. };
  44040. ParticleSystem.prototype.start = function () {
  44041. this._started = true;
  44042. this._stopped = false;
  44043. this._actualFrame = 0;
  44044. };
  44045. ParticleSystem.prototype.stop = function () {
  44046. this._stopped = true;
  44047. };
  44048. // animation sheet
  44049. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44050. var offset = index * this._vertexBufferSize;
  44051. this._vertexData[offset] = particle.position.x;
  44052. this._vertexData[offset + 1] = particle.position.y;
  44053. this._vertexData[offset + 2] = particle.position.z;
  44054. this._vertexData[offset + 3] = particle.color.r;
  44055. this._vertexData[offset + 4] = particle.color.g;
  44056. this._vertexData[offset + 5] = particle.color.b;
  44057. this._vertexData[offset + 6] = particle.color.a;
  44058. this._vertexData[offset + 7] = particle.angle;
  44059. this._vertexData[offset + 8] = particle.size;
  44060. this._vertexData[offset + 9] = offsetX;
  44061. this._vertexData[offset + 10] = offsetY;
  44062. };
  44063. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44064. if (offsetX === 0)
  44065. offsetX = this._epsilon;
  44066. else if (offsetX === 1)
  44067. offsetX = 1 - this._epsilon;
  44068. if (offsetY === 0)
  44069. offsetY = this._epsilon;
  44070. else if (offsetY === 1)
  44071. offsetY = 1 - this._epsilon;
  44072. var offset = index * this._vertexBufferSize;
  44073. this._vertexData[offset] = particle.position.x;
  44074. this._vertexData[offset + 1] = particle.position.y;
  44075. this._vertexData[offset + 2] = particle.position.z;
  44076. this._vertexData[offset + 3] = particle.color.r;
  44077. this._vertexData[offset + 4] = particle.color.g;
  44078. this._vertexData[offset + 5] = particle.color.b;
  44079. this._vertexData[offset + 6] = particle.color.a;
  44080. this._vertexData[offset + 7] = particle.angle;
  44081. this._vertexData[offset + 8] = particle.size;
  44082. this._vertexData[offset + 9] = offsetX;
  44083. this._vertexData[offset + 10] = offsetY;
  44084. this._vertexData[offset + 11] = particle.cellIndex;
  44085. };
  44086. ParticleSystem.prototype._update = function (newParticles) {
  44087. // Update current
  44088. this._alive = this.particles.length > 0;
  44089. this.updateFunction(this.particles);
  44090. // Add new ones
  44091. var worldMatrix;
  44092. if (this.emitter.position) {
  44093. var emitterMesh = this.emitter;
  44094. worldMatrix = emitterMesh.getWorldMatrix();
  44095. }
  44096. else {
  44097. var emitterPosition = this.emitter;
  44098. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44099. }
  44100. var particle;
  44101. for (var index = 0; index < newParticles; index++) {
  44102. if (this.particles.length === this._capacity) {
  44103. break;
  44104. }
  44105. if (this._stockParticles.length !== 0) {
  44106. particle = this._stockParticles.pop();
  44107. particle.age = 0;
  44108. particle.cellIndex = this.startSpriteCellID;
  44109. }
  44110. else {
  44111. particle = new BABYLON.Particle(this);
  44112. }
  44113. this.particles.push(particle);
  44114. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44115. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44116. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44117. particle.size = randomNumber(this.minSize, this.maxSize);
  44118. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44119. this.startPositionFunction(worldMatrix, particle.position, particle);
  44120. var step = randomNumber(0, 1.0);
  44121. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44122. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44123. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44124. }
  44125. };
  44126. ParticleSystem.prototype._getEffect = function () {
  44127. if (this._customEffect) {
  44128. return this._customEffect;
  44129. }
  44130. ;
  44131. var defines = [];
  44132. if (this._scene.clipPlane) {
  44133. defines.push("#define CLIPPLANE");
  44134. }
  44135. if (this._isAnimationSheetEnabled) {
  44136. defines.push("#define ANIMATESHEET");
  44137. }
  44138. // Effect
  44139. var join = defines.join("\n");
  44140. if (this._cachedDefines !== join) {
  44141. this._cachedDefines = join;
  44142. var attributesNamesOrOptions;
  44143. var effectCreationOption;
  44144. if (this._isAnimationSheetEnabled) {
  44145. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44146. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44147. }
  44148. else {
  44149. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44150. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44151. }
  44152. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44153. }
  44154. return this._effect;
  44155. };
  44156. ParticleSystem.prototype.animate = function () {
  44157. if (!this._started)
  44158. return;
  44159. var effect = this._getEffect();
  44160. // Check
  44161. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44162. return;
  44163. if (this._currentRenderId === this._scene.getRenderId()) {
  44164. return;
  44165. }
  44166. this._currentRenderId = this._scene.getRenderId();
  44167. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44168. // determine the number of particles we need to create
  44169. var newParticles;
  44170. if (this.manualEmitCount > -1) {
  44171. newParticles = this.manualEmitCount;
  44172. this._newPartsExcess = 0;
  44173. this.manualEmitCount = 0;
  44174. }
  44175. else {
  44176. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44177. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44178. }
  44179. if (this._newPartsExcess > 1.0) {
  44180. newParticles += this._newPartsExcess >> 0;
  44181. this._newPartsExcess -= this._newPartsExcess >> 0;
  44182. }
  44183. this._alive = false;
  44184. if (!this._stopped) {
  44185. this._actualFrame += this._scaledUpdateSpeed;
  44186. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44187. this.stop();
  44188. }
  44189. else {
  44190. newParticles = 0;
  44191. }
  44192. this._update(newParticles);
  44193. // Stopped?
  44194. if (this._stopped) {
  44195. if (!this._alive) {
  44196. this._started = false;
  44197. if (this.onAnimationEnd) {
  44198. this.onAnimationEnd();
  44199. }
  44200. if (this.disposeOnStop) {
  44201. this._scene._toBeDisposed.push(this);
  44202. }
  44203. }
  44204. }
  44205. // Animation sheet
  44206. if (this._isAnimationSheetEnabled) {
  44207. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44208. }
  44209. else {
  44210. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44211. }
  44212. // Update VBO
  44213. var offset = 0;
  44214. for (var index = 0; index < this.particles.length; index++) {
  44215. var particle = this.particles[index];
  44216. this.appendParticleVertexes(offset, particle);
  44217. offset += 4;
  44218. }
  44219. if (this._vertexBuffer) {
  44220. this._vertexBuffer.update(this._vertexData);
  44221. }
  44222. };
  44223. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44224. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44225. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44226. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44227. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44228. };
  44229. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44230. this._appendParticleVertex(offset++, particle, 0, 0);
  44231. this._appendParticleVertex(offset++, particle, 1, 0);
  44232. this._appendParticleVertex(offset++, particle, 1, 1);
  44233. this._appendParticleVertex(offset++, particle, 0, 1);
  44234. };
  44235. ParticleSystem.prototype.rebuild = function () {
  44236. this._createIndexBuffer();
  44237. if (this._vertexBuffer) {
  44238. this._vertexBuffer._rebuild();
  44239. }
  44240. };
  44241. ParticleSystem.prototype.render = function () {
  44242. var effect = this._getEffect();
  44243. // Check
  44244. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44245. return 0;
  44246. var engine = this._scene.getEngine();
  44247. // Render
  44248. engine.enableEffect(effect);
  44249. engine.setState(false);
  44250. var viewMatrix = this._scene.getViewMatrix();
  44251. effect.setTexture("diffuseSampler", this.particleTexture);
  44252. effect.setMatrix("view", viewMatrix);
  44253. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44254. if (this._isAnimationSheetEnabled) {
  44255. var baseSize = this.particleTexture.getBaseSize();
  44256. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44257. }
  44258. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44259. if (this._scene.clipPlane) {
  44260. var clipPlane = this._scene.clipPlane;
  44261. var invView = viewMatrix.clone();
  44262. invView.invert();
  44263. effect.setMatrix("invView", invView);
  44264. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44265. }
  44266. // VBOs
  44267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44268. // Draw order
  44269. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44270. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44271. }
  44272. else {
  44273. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44274. }
  44275. if (this.forceDepthWrite) {
  44276. engine.setDepthWrite(true);
  44277. }
  44278. engine.draw(true, 0, this.particles.length * 6);
  44279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44280. return this.particles.length;
  44281. };
  44282. ParticleSystem.prototype.dispose = function () {
  44283. if (this._vertexBuffer) {
  44284. this._vertexBuffer.dispose();
  44285. this._vertexBuffer = null;
  44286. }
  44287. if (this._indexBuffer) {
  44288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44289. this._indexBuffer = null;
  44290. }
  44291. if (this.particleTexture) {
  44292. this.particleTexture.dispose();
  44293. this.particleTexture = null;
  44294. }
  44295. // Remove from scene
  44296. var index = this._scene.particleSystems.indexOf(this);
  44297. if (index > -1) {
  44298. this._scene.particleSystems.splice(index, 1);
  44299. }
  44300. // Callback
  44301. this.onDisposeObservable.notifyObservers(this);
  44302. this.onDisposeObservable.clear();
  44303. };
  44304. // Clone
  44305. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44306. var custom = null;
  44307. var program = null;
  44308. if (this.customShader != null) {
  44309. program = this.customShader;
  44310. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44311. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44312. }
  44313. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44314. result.customShader = program;
  44315. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44316. if (newEmitter === undefined) {
  44317. newEmitter = this.emitter;
  44318. }
  44319. result.emitter = newEmitter;
  44320. if (this.particleTexture) {
  44321. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44322. }
  44323. if (!this.preventAutoStart) {
  44324. result.start();
  44325. }
  44326. return result;
  44327. };
  44328. ParticleSystem.prototype.serialize = function () {
  44329. var serializationObject = {};
  44330. serializationObject.name = this.name;
  44331. serializationObject.id = this.id;
  44332. // Emitter
  44333. if (this.emitter.position) {
  44334. var emitterMesh = this.emitter;
  44335. serializationObject.emitterId = emitterMesh.id;
  44336. }
  44337. else {
  44338. var emitterPosition = this.emitter;
  44339. serializationObject.emitter = emitterPosition.asArray();
  44340. }
  44341. serializationObject.capacity = this.getCapacity();
  44342. if (this.particleTexture) {
  44343. serializationObject.textureName = this.particleTexture.name;
  44344. }
  44345. // Animations
  44346. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44347. // Particle system
  44348. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44349. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44350. serializationObject.minSize = this.minSize;
  44351. serializationObject.maxSize = this.maxSize;
  44352. serializationObject.minEmitPower = this.minEmitPower;
  44353. serializationObject.maxEmitPower = this.maxEmitPower;
  44354. serializationObject.minLifeTime = this.minLifeTime;
  44355. serializationObject.maxLifeTime = this.maxLifeTime;
  44356. serializationObject.emitRate = this.emitRate;
  44357. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44358. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44359. serializationObject.gravity = this.gravity.asArray();
  44360. serializationObject.direction1 = this.direction1.asArray();
  44361. serializationObject.direction2 = this.direction2.asArray();
  44362. serializationObject.color1 = this.color1.asArray();
  44363. serializationObject.color2 = this.color2.asArray();
  44364. serializationObject.colorDead = this.colorDead.asArray();
  44365. serializationObject.updateSpeed = this.updateSpeed;
  44366. serializationObject.targetStopDuration = this.targetStopDuration;
  44367. serializationObject.textureMask = this.textureMask.asArray();
  44368. serializationObject.blendMode = this.blendMode;
  44369. serializationObject.customShader = this.customShader;
  44370. serializationObject.preventAutoStart = this.preventAutoStart;
  44371. return serializationObject;
  44372. };
  44373. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44374. var name = parsedParticleSystem.name;
  44375. var custom = null;
  44376. var program = null;
  44377. if (parsedParticleSystem.customShader) {
  44378. program = parsedParticleSystem.customShader;
  44379. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44380. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44381. }
  44382. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44383. particleSystem.customShader = program;
  44384. if (parsedParticleSystem.id) {
  44385. particleSystem.id = parsedParticleSystem.id;
  44386. }
  44387. // Auto start
  44388. if (parsedParticleSystem.preventAutoStart) {
  44389. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44390. }
  44391. // Texture
  44392. if (parsedParticleSystem.textureName) {
  44393. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44394. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44395. }
  44396. // Emitter
  44397. if (parsedParticleSystem.emitterId) {
  44398. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44399. }
  44400. else {
  44401. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44402. }
  44403. // Animations
  44404. if (parsedParticleSystem.animations) {
  44405. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44406. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44407. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44408. }
  44409. }
  44410. if (parsedParticleSystem.autoAnimate) {
  44411. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44412. }
  44413. // Particle system
  44414. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44415. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44416. particleSystem.minSize = parsedParticleSystem.minSize;
  44417. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44418. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44419. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44420. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44421. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44422. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44423. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44424. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44425. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44426. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44427. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44428. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44429. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44430. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44431. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44432. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44433. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44434. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44435. if (!particleSystem.preventAutoStart) {
  44436. particleSystem.start();
  44437. }
  44438. return particleSystem;
  44439. };
  44440. // Statics
  44441. ParticleSystem.BLENDMODE_ONEONE = 0;
  44442. ParticleSystem.BLENDMODE_STANDARD = 1;
  44443. return ParticleSystem;
  44444. }());
  44445. BABYLON.ParticleSystem = ParticleSystem;
  44446. })(BABYLON || (BABYLON = {}));
  44447. //# sourceMappingURL=babylon.particleSystem.js.map
  44448. var BABYLON;
  44449. (function (BABYLON) {
  44450. var SolidParticle = /** @class */ (function () {
  44451. /**
  44452. * Creates a Solid Particle object.
  44453. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44454. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44455. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44456. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44457. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44458. * `shapeId` (integer) is the model shape identifier in the SPS.
  44459. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44460. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44461. */
  44462. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44463. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44464. this.idx = 0; // particle global index
  44465. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44466. this.position = BABYLON.Vector3.Zero(); // position
  44467. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44468. this.scaling = BABYLON.Vector3.One(); // scaling
  44469. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44470. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44471. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44472. this.alive = true; // alive
  44473. this.isVisible = true; // visibility
  44474. this._pos = 0; // index of this particle in the global "positions" array
  44475. this._ind = 0; // index of this particle in the global "indices" array
  44476. this.shapeId = 0; // model shape id
  44477. this.idxInShape = 0; // index of the particle in its shape id
  44478. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44479. this.idx = particleIndex;
  44480. this._pos = positionIndex;
  44481. this._ind = indiceIndex;
  44482. this._model = model;
  44483. this.shapeId = shapeId;
  44484. this.idxInShape = idxInShape;
  44485. this._sps = sps;
  44486. if (modelBoundingInfo) {
  44487. this._modelBoundingInfo = modelBoundingInfo;
  44488. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44489. }
  44490. }
  44491. Object.defineProperty(SolidParticle.prototype, "scale", {
  44492. /**
  44493. * legacy support, changed scale to scaling
  44494. */
  44495. get: function () {
  44496. return this.scaling;
  44497. },
  44498. set: function (scale) {
  44499. this.scaling = scale;
  44500. },
  44501. enumerable: true,
  44502. configurable: true
  44503. });
  44504. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44505. /**
  44506. * legacy support, changed quaternion to rotationQuaternion
  44507. */
  44508. get: function () {
  44509. return this.rotationQuaternion;
  44510. },
  44511. set: function (q) {
  44512. this.rotationQuaternion = q;
  44513. },
  44514. enumerable: true,
  44515. configurable: true
  44516. });
  44517. /**
  44518. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44519. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44520. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44521. */
  44522. SolidParticle.prototype.intersectsMesh = function (target) {
  44523. if (!this._boundingInfo || !target._boundingInfo) {
  44524. return false;
  44525. }
  44526. if (this._sps._bSphereOnly) {
  44527. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44528. }
  44529. return this._boundingInfo.intersects(target._boundingInfo, false);
  44530. };
  44531. return SolidParticle;
  44532. }());
  44533. BABYLON.SolidParticle = SolidParticle;
  44534. var ModelShape = /** @class */ (function () {
  44535. /**
  44536. * 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.
  44537. * SPS internal tool, don't use it manually.
  44538. */
  44539. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44540. this._indicesLength = 0; // length of the shape in the model indices array
  44541. this.shapeID = id;
  44542. this._shape = shape;
  44543. this._indicesLength = indicesLength;
  44544. this._shapeUV = shapeUV;
  44545. this._positionFunction = posFunction;
  44546. this._vertexFunction = vtxFunction;
  44547. }
  44548. return ModelShape;
  44549. }());
  44550. BABYLON.ModelShape = ModelShape;
  44551. var DepthSortedParticle = /** @class */ (function () {
  44552. function DepthSortedParticle() {
  44553. this.ind = 0; // index of the particle in the "indices" array
  44554. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44555. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44556. }
  44557. return DepthSortedParticle;
  44558. }());
  44559. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44560. })(BABYLON || (BABYLON = {}));
  44561. //# sourceMappingURL=babylon.solidParticle.js.map
  44562. var BABYLON;
  44563. (function (BABYLON) {
  44564. /**
  44565. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44566. */
  44567. var SolidParticleSystem = /** @class */ (function () {
  44568. /**
  44569. * Creates a SPS (Solid Particle System) object.
  44570. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44571. * `scene` (Scene) is the scene in which the SPS is added.
  44572. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44573. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44574. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44575. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44576. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44577. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44578. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44579. */
  44580. function SolidParticleSystem(name, scene, options) {
  44581. // public members
  44582. /**
  44583. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44584. * Example : var p = SPS.particles[i];
  44585. */
  44586. this.particles = new Array();
  44587. /**
  44588. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44589. */
  44590. this.nbParticles = 0;
  44591. /**
  44592. * If the particles must ever face the camera (default false). Useful for planar particles.
  44593. */
  44594. this.billboard = false;
  44595. /**
  44596. * Recompute normals when adding a shape
  44597. */
  44598. this.recomputeNormals = true;
  44599. /**
  44600. * This a counter ofr your own usage. It's not set by any SPS functions.
  44601. */
  44602. this.counter = 0;
  44603. /**
  44604. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44605. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44606. */
  44607. this.vars = {};
  44608. this._positions = new Array();
  44609. this._indices = new Array();
  44610. this._normals = new Array();
  44611. this._colors = new Array();
  44612. this._uvs = new Array();
  44613. this._index = 0; // indices index
  44614. this._updatable = true;
  44615. this._pickable = false;
  44616. this._isVisibilityBoxLocked = false;
  44617. this._alwaysVisible = false;
  44618. this._depthSort = false;
  44619. this._shapeCounter = 0;
  44620. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44621. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44622. this._computeParticleColor = true;
  44623. this._computeParticleTexture = true;
  44624. this._computeParticleRotation = true;
  44625. this._computeParticleVertex = false;
  44626. this._computeBoundingBox = false;
  44627. this._depthSortParticles = true;
  44628. this._cam_axisZ = BABYLON.Vector3.Zero();
  44629. this._cam_axisY = BABYLON.Vector3.Zero();
  44630. this._cam_axisX = BABYLON.Vector3.Zero();
  44631. this._axisZ = BABYLON.Axis.Z;
  44632. this._camDir = BABYLON.Vector3.Zero();
  44633. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44634. this._rotMatrix = new BABYLON.Matrix();
  44635. this._invertMatrix = new BABYLON.Matrix();
  44636. this._rotated = BABYLON.Vector3.Zero();
  44637. this._quaternion = new BABYLON.Quaternion();
  44638. this._vertex = BABYLON.Vector3.Zero();
  44639. this._normal = BABYLON.Vector3.Zero();
  44640. this._yaw = 0.0;
  44641. this._pitch = 0.0;
  44642. this._roll = 0.0;
  44643. this._halfroll = 0.0;
  44644. this._halfpitch = 0.0;
  44645. this._halfyaw = 0.0;
  44646. this._sinRoll = 0.0;
  44647. this._cosRoll = 0.0;
  44648. this._sinPitch = 0.0;
  44649. this._cosPitch = 0.0;
  44650. this._sinYaw = 0.0;
  44651. this._cosYaw = 0.0;
  44652. this._mustUnrotateFixedNormals = false;
  44653. this._minimum = BABYLON.Tmp.Vector3[0];
  44654. this._maximum = BABYLON.Tmp.Vector3[1];
  44655. this._minBbox = BABYLON.Tmp.Vector3[4];
  44656. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44657. this._particlesIntersect = false;
  44658. this._depthSortFunction = function (p1, p2) {
  44659. return (p2.sqDistance - p1.sqDistance);
  44660. };
  44661. this._needs32Bits = false;
  44662. this._bSphereOnly = false;
  44663. this._bSphereRadiusFactor = 1.0;
  44664. this.name = name;
  44665. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44666. this._camera = scene.activeCamera;
  44667. this._pickable = options ? options.isPickable : false;
  44668. this._depthSort = options ? options.enableDepthSort : false;
  44669. this._particlesIntersect = options ? options.particleIntersection : false;
  44670. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44671. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44672. if (options && options.updatable) {
  44673. this._updatable = options.updatable;
  44674. }
  44675. else {
  44676. this._updatable = true;
  44677. }
  44678. if (this._pickable) {
  44679. this.pickedParticles = [];
  44680. }
  44681. if (this._depthSort) {
  44682. this.depthSortedParticles = [];
  44683. }
  44684. }
  44685. /**
  44686. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44687. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44688. */
  44689. SolidParticleSystem.prototype.buildMesh = function () {
  44690. if (this.nbParticles === 0) {
  44691. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44692. this.addShape(triangle, 1);
  44693. triangle.dispose();
  44694. }
  44695. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44696. this._positions32 = new Float32Array(this._positions);
  44697. this._uvs32 = new Float32Array(this._uvs);
  44698. this._colors32 = new Float32Array(this._colors);
  44699. if (this.recomputeNormals) {
  44700. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44701. }
  44702. this._normals32 = new Float32Array(this._normals);
  44703. this._fixedNormal32 = new Float32Array(this._normals);
  44704. if (this._mustUnrotateFixedNormals) {
  44705. this._unrotateFixedNormals();
  44706. }
  44707. var vertexData = new BABYLON.VertexData();
  44708. vertexData.indices = this._indices32;
  44709. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44710. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44711. if (this._uvs32) {
  44712. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44713. ;
  44714. }
  44715. if (this._colors32) {
  44716. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44717. }
  44718. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44719. vertexData.applyToMesh(mesh, this._updatable);
  44720. this.mesh = mesh;
  44721. this.mesh.isPickable = this._pickable;
  44722. // free memory
  44723. if (!this._depthSort) {
  44724. this._indices = null;
  44725. }
  44726. this._positions = null;
  44727. this._normals = null;
  44728. this._uvs = null;
  44729. this._colors = null;
  44730. if (!this._updatable) {
  44731. this.particles.length = 0;
  44732. }
  44733. return mesh;
  44734. };
  44735. /**
  44736. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44737. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44738. * Thus the particles generated from `digest()` have their property `position` set yet.
  44739. * `mesh` ( Mesh ) is the mesh to be digested
  44740. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44741. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44742. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44743. */
  44744. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44745. var size = (options && options.facetNb) || 1;
  44746. var number = (options && options.number) || 0;
  44747. var delta = (options && options.delta) || 0;
  44748. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44749. var meshInd = mesh.getIndices();
  44750. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44751. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44752. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44753. var f = 0; // facet counter
  44754. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44755. // compute size from number
  44756. if (number) {
  44757. number = (number > totalFacets) ? totalFacets : number;
  44758. size = Math.round(totalFacets / number);
  44759. delta = 0;
  44760. }
  44761. else {
  44762. size = (size > totalFacets) ? totalFacets : size;
  44763. }
  44764. var facetPos = []; // submesh positions
  44765. var facetInd = []; // submesh indices
  44766. var facetUV = []; // submesh UV
  44767. var facetCol = []; // submesh colors
  44768. var barycenter = BABYLON.Tmp.Vector3[0];
  44769. var sizeO = size;
  44770. while (f < totalFacets) {
  44771. size = sizeO + Math.floor((1 + delta) * Math.random());
  44772. if (f > totalFacets - size) {
  44773. size = totalFacets - f;
  44774. }
  44775. // reset temp arrays
  44776. facetPos.length = 0;
  44777. facetInd.length = 0;
  44778. facetUV.length = 0;
  44779. facetCol.length = 0;
  44780. // iterate over "size" facets
  44781. var fi = 0;
  44782. for (var j = f * 3; j < (f + size) * 3; j++) {
  44783. facetInd.push(fi);
  44784. var i = meshInd[j];
  44785. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44786. if (meshUV) {
  44787. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44788. }
  44789. if (meshCol) {
  44790. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44791. }
  44792. fi++;
  44793. }
  44794. // create a model shape for each single particle
  44795. var idx = this.nbParticles;
  44796. var shape = this._posToShape(facetPos);
  44797. var shapeUV = this._uvsToShapeUV(facetUV);
  44798. // compute the barycenter of the shape
  44799. var v;
  44800. for (v = 0; v < shape.length; v++) {
  44801. barycenter.addInPlace(shape[v]);
  44802. }
  44803. barycenter.scaleInPlace(1 / shape.length);
  44804. // shift the shape from its barycenter to the origin
  44805. for (v = 0; v < shape.length; v++) {
  44806. shape[v].subtractInPlace(barycenter);
  44807. }
  44808. var bInfo;
  44809. if (this._particlesIntersect) {
  44810. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44811. }
  44812. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44813. // add the particle in the SPS
  44814. var currentPos = this._positions.length;
  44815. var currentInd = this._indices.length;
  44816. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44817. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44818. // initialize the particle position
  44819. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44820. this._index += shape.length;
  44821. idx++;
  44822. this.nbParticles++;
  44823. this._shapeCounter++;
  44824. f += size;
  44825. }
  44826. return this;
  44827. };
  44828. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44829. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44830. var index = 0;
  44831. var idx = 0;
  44832. for (var p = 0; p < this.particles.length; p++) {
  44833. this._particle = this.particles[p];
  44834. this._shape = this._particle._model._shape;
  44835. if (this._particle.rotationQuaternion) {
  44836. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44837. }
  44838. else {
  44839. this._yaw = this._particle.rotation.y;
  44840. this._pitch = this._particle.rotation.x;
  44841. this._roll = this._particle.rotation.z;
  44842. this._quaternionRotationYPR();
  44843. }
  44844. this._quaternionToRotationMatrix();
  44845. this._rotMatrix.invertToRef(this._invertMatrix);
  44846. for (var pt = 0; pt < this._shape.length; pt++) {
  44847. idx = index + pt * 3;
  44848. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44849. this._fixedNormal32[idx] = this._normal.x;
  44850. this._fixedNormal32[idx + 1] = this._normal.y;
  44851. this._fixedNormal32[idx + 2] = this._normal.z;
  44852. }
  44853. index = idx + 3;
  44854. }
  44855. };
  44856. //reset copy
  44857. SolidParticleSystem.prototype._resetCopy = function () {
  44858. this._copy.position.x = 0;
  44859. this._copy.position.y = 0;
  44860. this._copy.position.z = 0;
  44861. this._copy.rotation.x = 0;
  44862. this._copy.rotation.y = 0;
  44863. this._copy.rotation.z = 0;
  44864. this._copy.rotationQuaternion = null;
  44865. this._copy.scaling.x = 1.0;
  44866. this._copy.scaling.y = 1.0;
  44867. this._copy.scaling.z = 1.0;
  44868. this._copy.uvs.x = 0;
  44869. this._copy.uvs.y = 0;
  44870. this._copy.uvs.z = 1.0;
  44871. this._copy.uvs.w = 1.0;
  44872. this._copy.color = null;
  44873. };
  44874. // _meshBuilder : inserts the shape model in the global SPS mesh
  44875. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44876. var i;
  44877. var u = 0;
  44878. var c = 0;
  44879. var n = 0;
  44880. this._resetCopy();
  44881. if (options && options.positionFunction) {
  44882. options.positionFunction(this._copy, idx, idxInShape);
  44883. this._mustUnrotateFixedNormals = true;
  44884. }
  44885. if (this._copy.rotationQuaternion) {
  44886. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44887. }
  44888. else {
  44889. this._yaw = this._copy.rotation.y;
  44890. this._pitch = this._copy.rotation.x;
  44891. this._roll = this._copy.rotation.z;
  44892. this._quaternionRotationYPR();
  44893. }
  44894. this._quaternionToRotationMatrix();
  44895. for (i = 0; i < shape.length; i++) {
  44896. this._vertex.x = shape[i].x;
  44897. this._vertex.y = shape[i].y;
  44898. this._vertex.z = shape[i].z;
  44899. if (options && options.vertexFunction) {
  44900. options.vertexFunction(this._copy, this._vertex, i);
  44901. }
  44902. this._vertex.x *= this._copy.scaling.x;
  44903. this._vertex.y *= this._copy.scaling.y;
  44904. this._vertex.z *= this._copy.scaling.z;
  44905. this._vertex.x += this._copy.pivot.x;
  44906. this._vertex.y += this._copy.pivot.y;
  44907. this._vertex.z += this._copy.pivot.z;
  44908. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44909. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44910. if (meshUV) {
  44911. 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);
  44912. u += 2;
  44913. }
  44914. if (this._copy.color) {
  44915. this._color = this._copy.color;
  44916. }
  44917. else if (meshCol && meshCol[c] !== undefined) {
  44918. this._color.r = meshCol[c];
  44919. this._color.g = meshCol[c + 1];
  44920. this._color.b = meshCol[c + 2];
  44921. this._color.a = meshCol[c + 3];
  44922. }
  44923. else {
  44924. this._color.r = 1.0;
  44925. this._color.g = 1.0;
  44926. this._color.b = 1.0;
  44927. this._color.a = 1.0;
  44928. }
  44929. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44930. c += 4;
  44931. if (!this.recomputeNormals && meshNor) {
  44932. this._normal.x = meshNor[n];
  44933. this._normal.y = meshNor[n + 1];
  44934. this._normal.z = meshNor[n + 2];
  44935. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44936. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44937. n += 3;
  44938. }
  44939. }
  44940. for (i = 0; i < meshInd.length; i++) {
  44941. var current_ind = p + meshInd[i];
  44942. indices.push(current_ind);
  44943. if (current_ind > 65535) {
  44944. this._needs32Bits = true;
  44945. }
  44946. }
  44947. if (this._pickable) {
  44948. var nbfaces = meshInd.length / 3;
  44949. for (i = 0; i < nbfaces; i++) {
  44950. this.pickedParticles.push({ idx: idx, faceId: i });
  44951. }
  44952. }
  44953. if (this._depthSort) {
  44954. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44955. }
  44956. return this._copy;
  44957. };
  44958. // returns a shape array from positions array
  44959. SolidParticleSystem.prototype._posToShape = function (positions) {
  44960. var shape = [];
  44961. for (var i = 0; i < positions.length; i += 3) {
  44962. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44963. }
  44964. return shape;
  44965. };
  44966. // returns a shapeUV array from a Vector4 uvs
  44967. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44968. var shapeUV = [];
  44969. if (uvs) {
  44970. for (var i = 0; i < uvs.length; i++)
  44971. shapeUV.push(uvs[i]);
  44972. }
  44973. return shapeUV;
  44974. };
  44975. // adds a new particle object in the particles array
  44976. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44977. if (bInfo === void 0) { bInfo = null; }
  44978. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44979. this.particles.push(sp);
  44980. return sp;
  44981. };
  44982. /**
  44983. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44984. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44985. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44986. * `nb` (positive integer) the number of particles to be created from this model
  44987. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44988. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44989. */
  44990. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44991. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44992. var meshInd = mesh.getIndices();
  44993. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44994. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44995. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44996. var bbInfo;
  44997. if (this._particlesIntersect) {
  44998. bbInfo = mesh.getBoundingInfo();
  44999. }
  45000. var shape = this._posToShape(meshPos);
  45001. var shapeUV = this._uvsToShapeUV(meshUV);
  45002. var posfunc = options ? options.positionFunction : null;
  45003. var vtxfunc = options ? options.vertexFunction : null;
  45004. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45005. // particles
  45006. var sp;
  45007. var currentCopy;
  45008. var idx = this.nbParticles;
  45009. for (var i = 0; i < nb; i++) {
  45010. var currentPos = this._positions.length;
  45011. var currentInd = this._indices.length;
  45012. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45013. if (this._updatable) {
  45014. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45015. sp.position.copyFrom(currentCopy.position);
  45016. sp.rotation.copyFrom(currentCopy.rotation);
  45017. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45018. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45019. }
  45020. if (currentCopy.color && sp.color) {
  45021. sp.color.copyFrom(currentCopy.color);
  45022. }
  45023. sp.scaling.copyFrom(currentCopy.scaling);
  45024. sp.uvs.copyFrom(currentCopy.uvs);
  45025. }
  45026. this._index += shape.length;
  45027. idx++;
  45028. }
  45029. this.nbParticles += nb;
  45030. this._shapeCounter++;
  45031. return this._shapeCounter - 1;
  45032. };
  45033. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45034. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45035. this._resetCopy();
  45036. if (particle._model._positionFunction) {
  45037. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45038. }
  45039. if (this._copy.rotationQuaternion) {
  45040. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45041. }
  45042. else {
  45043. this._yaw = this._copy.rotation.y;
  45044. this._pitch = this._copy.rotation.x;
  45045. this._roll = this._copy.rotation.z;
  45046. this._quaternionRotationYPR();
  45047. }
  45048. this._quaternionToRotationMatrix();
  45049. this._shape = particle._model._shape;
  45050. for (var pt = 0; pt < this._shape.length; pt++) {
  45051. this._vertex.x = this._shape[pt].x;
  45052. this._vertex.y = this._shape[pt].y;
  45053. this._vertex.z = this._shape[pt].z;
  45054. if (particle._model._vertexFunction) {
  45055. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45056. }
  45057. this._vertex.x *= this._copy.scaling.x;
  45058. this._vertex.y *= this._copy.scaling.y;
  45059. this._vertex.z *= this._copy.scaling.z;
  45060. this._vertex.x += this._copy.pivot.x;
  45061. this._vertex.y += this._copy.pivot.y;
  45062. this._vertex.z += this._copy.pivot.z;
  45063. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45064. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45065. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45066. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45067. }
  45068. particle.position.x = 0.0;
  45069. particle.position.y = 0.0;
  45070. particle.position.z = 0.0;
  45071. particle.rotation.x = 0.0;
  45072. particle.rotation.y = 0.0;
  45073. particle.rotation.z = 0.0;
  45074. particle.rotationQuaternion = null;
  45075. particle.scaling.x = 1.0;
  45076. particle.scaling.y = 1.0;
  45077. particle.scaling.z = 1.0;
  45078. };
  45079. /**
  45080. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45081. * Returns the SPS.
  45082. */
  45083. SolidParticleSystem.prototype.rebuildMesh = function () {
  45084. for (var p = 0; p < this.particles.length; p++) {
  45085. this._rebuildParticle(this.particles[p]);
  45086. }
  45087. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45088. return this;
  45089. };
  45090. /**
  45091. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45092. * This method calls `updateParticle()` for each particle of the SPS.
  45093. * For an animated SPS, it is usually called within the render loop.
  45094. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45095. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45096. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45097. * Returns the SPS.
  45098. */
  45099. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45100. if (start === void 0) { start = 0; }
  45101. if (end === void 0) { end = this.nbParticles - 1; }
  45102. if (update === void 0) { update = true; }
  45103. if (!this._updatable) {
  45104. return this;
  45105. }
  45106. // custom beforeUpdate
  45107. this.beforeUpdateParticles(start, end, update);
  45108. this._cam_axisX.x = 1.0;
  45109. this._cam_axisX.y = 0.0;
  45110. this._cam_axisX.z = 0.0;
  45111. this._cam_axisY.x = 0.0;
  45112. this._cam_axisY.y = 1.0;
  45113. this._cam_axisY.z = 0.0;
  45114. this._cam_axisZ.x = 0.0;
  45115. this._cam_axisZ.y = 0.0;
  45116. this._cam_axisZ.z = 1.0;
  45117. // cases when the World Matrix is to be computed first
  45118. if (this.billboard || this._depthSort) {
  45119. this.mesh.computeWorldMatrix(true);
  45120. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45121. }
  45122. // if the particles will always face the camera
  45123. if (this.billboard) {
  45124. // compute the camera position and un-rotate it by the current mesh rotation
  45125. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45126. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45127. this._cam_axisZ.normalize();
  45128. // same for camera up vector extracted from the cam view matrix
  45129. var view = this._camera.getViewMatrix(true);
  45130. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45131. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45132. this._cam_axisY.normalize();
  45133. this._cam_axisX.normalize();
  45134. }
  45135. // if depthSort, compute the camera global position in the mesh local system
  45136. if (this._depthSort) {
  45137. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45138. }
  45139. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45140. var idx = 0; // current position index in the global array positions32
  45141. var index = 0; // position start index in the global array positions32 of the current particle
  45142. var colidx = 0; // current color index in the global array colors32
  45143. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45144. var uvidx = 0; // current uv index in the global array uvs32
  45145. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45146. var pt = 0; // current index in the particle model shape
  45147. if (this.mesh.isFacetDataEnabled) {
  45148. this._computeBoundingBox = true;
  45149. }
  45150. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45151. if (this._computeBoundingBox) {
  45152. if (start == 0 && end == this.nbParticles - 1) {
  45153. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45154. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45155. }
  45156. else {
  45157. if (this.mesh._boundingInfo) {
  45158. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45159. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45160. }
  45161. }
  45162. }
  45163. // particle loop
  45164. index = this.particles[start]._pos;
  45165. var vpos = (index / 3) | 0;
  45166. colorIndex = vpos * 4;
  45167. uvIndex = vpos * 2;
  45168. for (var p = start; p <= end; p++) {
  45169. this._particle = this.particles[p];
  45170. this._shape = this._particle._model._shape;
  45171. this._shapeUV = this._particle._model._shapeUV;
  45172. // call to custom user function to update the particle properties
  45173. this.updateParticle(this._particle);
  45174. // camera-particle distance for depth sorting
  45175. if (this._depthSort && this._depthSortParticles) {
  45176. var dsp = this.depthSortedParticles[p];
  45177. dsp.ind = this._particle._ind;
  45178. dsp.indicesLength = this._particle._model._indicesLength;
  45179. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45180. }
  45181. // skip the computations for inactive or already invisible particles
  45182. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45183. // increment indexes for the next particle
  45184. pt = this._shape.length;
  45185. index += pt * 3;
  45186. colorIndex += pt * 4;
  45187. uvIndex += pt * 2;
  45188. continue;
  45189. }
  45190. if (this._particle.isVisible) {
  45191. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45192. // particle rotation matrix
  45193. if (this.billboard) {
  45194. this._particle.rotation.x = 0.0;
  45195. this._particle.rotation.y = 0.0;
  45196. }
  45197. if (this._computeParticleRotation || this.billboard) {
  45198. if (this._particle.rotationQuaternion) {
  45199. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45200. }
  45201. else {
  45202. this._yaw = this._particle.rotation.y;
  45203. this._pitch = this._particle.rotation.x;
  45204. this._roll = this._particle.rotation.z;
  45205. this._quaternionRotationYPR();
  45206. }
  45207. this._quaternionToRotationMatrix();
  45208. }
  45209. // particle vertex loop
  45210. for (pt = 0; pt < this._shape.length; pt++) {
  45211. idx = index + pt * 3;
  45212. colidx = colorIndex + pt * 4;
  45213. uvidx = uvIndex + pt * 2;
  45214. this._vertex.x = this._shape[pt].x;
  45215. this._vertex.y = this._shape[pt].y;
  45216. this._vertex.z = this._shape[pt].z;
  45217. if (this._computeParticleVertex) {
  45218. this.updateParticleVertex(this._particle, this._vertex, pt);
  45219. }
  45220. // positions
  45221. this._vertex.x *= this._particle.scaling.x;
  45222. this._vertex.y *= this._particle.scaling.y;
  45223. this._vertex.z *= this._particle.scaling.z;
  45224. this._vertex.x += this._particle.pivot.x;
  45225. this._vertex.y += this._particle.pivot.y;
  45226. this._vertex.z += this._particle.pivot.z;
  45227. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45228. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45229. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45230. 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;
  45231. 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;
  45232. 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;
  45233. if (this._computeBoundingBox) {
  45234. if (this._positions32[idx] < this._minimum.x) {
  45235. this._minimum.x = this._positions32[idx];
  45236. }
  45237. if (this._positions32[idx] > this._maximum.x) {
  45238. this._maximum.x = this._positions32[idx];
  45239. }
  45240. if (this._positions32[idx + 1] < this._minimum.y) {
  45241. this._minimum.y = this._positions32[idx + 1];
  45242. }
  45243. if (this._positions32[idx + 1] > this._maximum.y) {
  45244. this._maximum.y = this._positions32[idx + 1];
  45245. }
  45246. if (this._positions32[idx + 2] < this._minimum.z) {
  45247. this._minimum.z = this._positions32[idx + 2];
  45248. }
  45249. if (this._positions32[idx + 2] > this._maximum.z) {
  45250. this._maximum.z = this._positions32[idx + 2];
  45251. }
  45252. }
  45253. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45254. if (!this._computeParticleVertex) {
  45255. this._normal.x = this._fixedNormal32[idx];
  45256. this._normal.y = this._fixedNormal32[idx + 1];
  45257. this._normal.z = this._fixedNormal32[idx + 2];
  45258. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45259. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45260. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45261. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45262. 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;
  45263. 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;
  45264. }
  45265. if (this._computeParticleColor && this._particle.color) {
  45266. this._colors32[colidx] = this._particle.color.r;
  45267. this._colors32[colidx + 1] = this._particle.color.g;
  45268. this._colors32[colidx + 2] = this._particle.color.b;
  45269. this._colors32[colidx + 3] = this._particle.color.a;
  45270. }
  45271. if (this._computeParticleTexture) {
  45272. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45273. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45274. }
  45275. }
  45276. }
  45277. else {
  45278. this._particle._stillInvisible = true; // mark the particle as invisible
  45279. for (pt = 0; pt < this._shape.length; pt++) {
  45280. idx = index + pt * 3;
  45281. colidx = colorIndex + pt * 4;
  45282. uvidx = uvIndex + pt * 2;
  45283. this._positions32[idx] = 0.0;
  45284. this._positions32[idx + 1] = 0.0;
  45285. this._positions32[idx + 2] = 0.0;
  45286. this._normals32[idx] = 0.0;
  45287. this._normals32[idx + 1] = 0.0;
  45288. this._normals32[idx + 2] = 0.0;
  45289. if (this._computeParticleColor && this._particle.color) {
  45290. this._colors32[colidx] = this._particle.color.r;
  45291. this._colors32[colidx + 1] = this._particle.color.g;
  45292. this._colors32[colidx + 2] = this._particle.color.b;
  45293. this._colors32[colidx + 3] = this._particle.color.a;
  45294. }
  45295. if (this._computeParticleTexture) {
  45296. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45297. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45298. }
  45299. }
  45300. }
  45301. // if the particle intersections must be computed : update the bbInfo
  45302. if (this._particlesIntersect) {
  45303. var bInfo = this._particle._boundingInfo;
  45304. var bBox = bInfo.boundingBox;
  45305. var bSphere = bInfo.boundingSphere;
  45306. if (!this._bSphereOnly) {
  45307. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45308. for (var b = 0; b < bBox.vectors.length; b++) {
  45309. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45310. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45311. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45312. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45313. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45314. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45315. 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;
  45316. 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;
  45317. 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;
  45318. }
  45319. bBox._update(this.mesh._worldMatrix);
  45320. }
  45321. // place and scale the particle bouding sphere in the SPS local system, then update it
  45322. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45323. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45324. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45325. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45326. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45327. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45328. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45329. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45330. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45331. 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));
  45332. bSphere._update(this.mesh._worldMatrix);
  45333. }
  45334. // increment indexes for the next particle
  45335. index = idx + 3;
  45336. colorIndex = colidx + 4;
  45337. uvIndex = uvidx + 2;
  45338. }
  45339. // if the VBO must be updated
  45340. if (update) {
  45341. if (this._computeParticleColor) {
  45342. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45343. }
  45344. if (this._computeParticleTexture) {
  45345. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45346. }
  45347. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45348. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45349. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45350. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45351. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45352. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45353. for (var i = 0; i < this._normals32.length; i++) {
  45354. this._fixedNormal32[i] = this._normals32[i];
  45355. }
  45356. }
  45357. if (!this.mesh.areNormalsFrozen) {
  45358. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45359. }
  45360. }
  45361. if (this._depthSort && this._depthSortParticles) {
  45362. this.depthSortedParticles.sort(this._depthSortFunction);
  45363. var dspl = this.depthSortedParticles.length;
  45364. var sorted = 0;
  45365. var lind = 0;
  45366. var sind = 0;
  45367. var sid = 0;
  45368. for (sorted = 0; sorted < dspl; sorted++) {
  45369. lind = this.depthSortedParticles[sorted].indicesLength;
  45370. sind = this.depthSortedParticles[sorted].ind;
  45371. for (var i = 0; i < lind; i++) {
  45372. this._indices32[sid] = this._indices[sind + i];
  45373. sid++;
  45374. }
  45375. }
  45376. this.mesh.updateIndices(this._indices32);
  45377. }
  45378. }
  45379. if (this._computeBoundingBox) {
  45380. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45381. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45382. }
  45383. this.afterUpdateParticles(start, end, update);
  45384. return this;
  45385. };
  45386. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45387. this._halfroll = this._roll * 0.5;
  45388. this._halfpitch = this._pitch * 0.5;
  45389. this._halfyaw = this._yaw * 0.5;
  45390. this._sinRoll = Math.sin(this._halfroll);
  45391. this._cosRoll = Math.cos(this._halfroll);
  45392. this._sinPitch = Math.sin(this._halfpitch);
  45393. this._cosPitch = Math.cos(this._halfpitch);
  45394. this._sinYaw = Math.sin(this._halfyaw);
  45395. this._cosYaw = Math.cos(this._halfyaw);
  45396. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45397. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45398. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45399. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45400. };
  45401. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45402. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45403. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45404. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45405. this._rotMatrix.m[3] = 0;
  45406. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45407. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45408. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45409. this._rotMatrix.m[7] = 0;
  45410. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45411. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45412. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45413. this._rotMatrix.m[11] = 0;
  45414. this._rotMatrix.m[12] = 0;
  45415. this._rotMatrix.m[13] = 0;
  45416. this._rotMatrix.m[14] = 0;
  45417. this._rotMatrix.m[15] = 1.0;
  45418. };
  45419. /**
  45420. * Disposes the SPS.
  45421. * Returns nothing.
  45422. */
  45423. SolidParticleSystem.prototype.dispose = function () {
  45424. this.mesh.dispose();
  45425. this.vars = null;
  45426. // drop references to internal big arrays for the GC
  45427. this._positions = null;
  45428. this._indices = null;
  45429. this._normals = null;
  45430. this._uvs = null;
  45431. this._colors = null;
  45432. this._indices32 = null;
  45433. this._positions32 = null;
  45434. this._normals32 = null;
  45435. this._fixedNormal32 = null;
  45436. this._uvs32 = null;
  45437. this._colors32 = null;
  45438. this.pickedParticles = null;
  45439. };
  45440. /**
  45441. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45442. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45443. * Returns the SPS.
  45444. */
  45445. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45446. if (!this._isVisibilityBoxLocked) {
  45447. this.mesh.refreshBoundingInfo();
  45448. }
  45449. return this;
  45450. };
  45451. /**
  45452. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45453. * @param size the size (float) of the visibility box
  45454. * note : this doesn't lock the SPS mesh bounding box.
  45455. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45456. */
  45457. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45458. var vis = size / 2;
  45459. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45460. };
  45461. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45462. // getter and setter
  45463. get: function () {
  45464. return this._alwaysVisible;
  45465. },
  45466. /**
  45467. * Sets the SPS as always visible or not
  45468. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45469. */
  45470. set: function (val) {
  45471. this._alwaysVisible = val;
  45472. this.mesh.alwaysSelectAsActiveMesh = val;
  45473. },
  45474. enumerable: true,
  45475. configurable: true
  45476. });
  45477. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45478. get: function () {
  45479. return this._isVisibilityBoxLocked;
  45480. },
  45481. /**
  45482. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45483. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45484. */
  45485. set: function (val) {
  45486. this._isVisibilityBoxLocked = val;
  45487. var boundingInfo = this.mesh.getBoundingInfo();
  45488. if (boundingInfo) {
  45489. boundingInfo.isLocked = val;
  45490. }
  45491. },
  45492. enumerable: true,
  45493. configurable: true
  45494. });
  45495. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45496. // getters
  45497. get: function () {
  45498. return this._computeParticleRotation;
  45499. },
  45500. // Optimizer setters
  45501. /**
  45502. * Tells to `setParticles()` to compute the particle rotations or not.
  45503. * Default value : true. The SPS is faster when it's set to false.
  45504. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45505. */
  45506. set: function (val) {
  45507. this._computeParticleRotation = val;
  45508. },
  45509. enumerable: true,
  45510. configurable: true
  45511. });
  45512. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45513. get: function () {
  45514. return this._computeParticleColor;
  45515. },
  45516. /**
  45517. * Tells to `setParticles()` to compute the particle colors or not.
  45518. * Default value : true. The SPS is faster when it's set to false.
  45519. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45520. */
  45521. set: function (val) {
  45522. this._computeParticleColor = val;
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45528. get: function () {
  45529. return this._computeParticleTexture;
  45530. },
  45531. /**
  45532. * Tells to `setParticles()` to compute the particle textures or not.
  45533. * Default value : true. The SPS is faster when it's set to false.
  45534. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45535. */
  45536. set: function (val) {
  45537. this._computeParticleTexture = val;
  45538. },
  45539. enumerable: true,
  45540. configurable: true
  45541. });
  45542. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45543. get: function () {
  45544. return this._computeParticleVertex;
  45545. },
  45546. /**
  45547. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45548. * Default value : false. The SPS is faster when it's set to false.
  45549. * Note : the particle custom vertex positions aren't stored values.
  45550. */
  45551. set: function (val) {
  45552. this._computeParticleVertex = val;
  45553. },
  45554. enumerable: true,
  45555. configurable: true
  45556. });
  45557. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45558. get: function () {
  45559. return this._computeBoundingBox;
  45560. },
  45561. /**
  45562. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45563. */
  45564. set: function (val) {
  45565. this._computeBoundingBox = val;
  45566. },
  45567. enumerable: true,
  45568. configurable: true
  45569. });
  45570. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45571. get: function () {
  45572. return this._depthSortParticles;
  45573. },
  45574. /**
  45575. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45576. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45577. * Default : `true`
  45578. */
  45579. set: function (val) {
  45580. this._depthSortParticles = val;
  45581. },
  45582. enumerable: true,
  45583. configurable: true
  45584. });
  45585. // =======================================================================
  45586. // Particle behavior logic
  45587. // these following methods may be overwritten by the user to fit his needs
  45588. /**
  45589. * This function does nothing. It may be overwritten to set all the particle first values.
  45590. * The SPS doesn't call this function, you may have to call it by your own.
  45591. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45592. */
  45593. SolidParticleSystem.prototype.initParticles = function () {
  45594. };
  45595. /**
  45596. * This function does nothing. It may be overwritten to recycle a particle.
  45597. * The SPS doesn't call this function, you may have to call it by your own.
  45598. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45599. */
  45600. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45601. return particle;
  45602. };
  45603. /**
  45604. * Updates a particle : this function should be overwritten by the user.
  45605. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45606. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45607. * ex : just set a particle position or velocity and recycle conditions
  45608. */
  45609. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45610. return particle;
  45611. };
  45612. /**
  45613. * Updates a vertex of a particle : it can be overwritten by the user.
  45614. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45615. * @param particle the current particle
  45616. * @param vertex the current index of the current particle
  45617. * @param pt the index of the current vertex in the particle shape
  45618. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45619. * ex : just set a vertex particle position
  45620. */
  45621. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45622. return vertex;
  45623. };
  45624. /**
  45625. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45626. * This does nothing and may be overwritten by the user.
  45627. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45628. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45629. * @param update the boolean update value actually passed to setParticles()
  45630. */
  45631. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45632. };
  45633. /**
  45634. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45635. * This will be passed three parameters.
  45636. * This does nothing and may be overwritten by the user.
  45637. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45638. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45639. * @param update the boolean update value actually passed to setParticles()
  45640. */
  45641. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45642. };
  45643. return SolidParticleSystem;
  45644. }());
  45645. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45646. })(BABYLON || (BABYLON = {}));
  45647. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45648. var BABYLON;
  45649. (function (BABYLON) {
  45650. var GroundMesh = /** @class */ (function (_super) {
  45651. __extends(GroundMesh, _super);
  45652. function GroundMesh(name, scene) {
  45653. var _this = _super.call(this, name, scene) || this;
  45654. _this.generateOctree = false;
  45655. return _this;
  45656. }
  45657. GroundMesh.prototype.getClassName = function () {
  45658. return "GroundMesh";
  45659. };
  45660. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45661. get: function () {
  45662. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45663. },
  45664. enumerable: true,
  45665. configurable: true
  45666. });
  45667. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45668. get: function () {
  45669. return this._subdivisionsX;
  45670. },
  45671. enumerable: true,
  45672. configurable: true
  45673. });
  45674. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45675. get: function () {
  45676. return this._subdivisionsY;
  45677. },
  45678. enumerable: true,
  45679. configurable: true
  45680. });
  45681. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45682. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45683. this._subdivisionsX = chunksCount;
  45684. this._subdivisionsY = chunksCount;
  45685. this.subdivide(chunksCount);
  45686. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45687. };
  45688. /**
  45689. * Returns a height (y) value in the Worl system :
  45690. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45691. * Returns the ground y position if (x, z) are outside the ground surface.
  45692. */
  45693. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45694. var world = this.getWorldMatrix();
  45695. var invMat = BABYLON.Tmp.Matrix[5];
  45696. world.invertToRef(invMat);
  45697. var tmpVect = BABYLON.Tmp.Vector3[8];
  45698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45699. x = tmpVect.x;
  45700. z = tmpVect.z;
  45701. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45702. return this.position.y;
  45703. }
  45704. if (!this._heightQuads || this._heightQuads.length == 0) {
  45705. this._initHeightQuads();
  45706. this._computeHeightQuads();
  45707. }
  45708. var facet = this._getFacetAt(x, z);
  45709. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45710. // return y in the World system
  45711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45712. return tmpVect.y;
  45713. };
  45714. /**
  45715. * Returns a normalized vector (Vector3) orthogonal to the ground
  45716. * at the ground coordinates (x, z) expressed in the World system.
  45717. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45718. */
  45719. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45720. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45721. this.getNormalAtCoordinatesToRef(x, z, normal);
  45722. return normal;
  45723. };
  45724. /**
  45725. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45726. * at the ground coordinates (x, z) expressed in the World system.
  45727. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45728. * Returns the GroundMesh.
  45729. */
  45730. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45731. var world = this.getWorldMatrix();
  45732. var tmpMat = BABYLON.Tmp.Matrix[5];
  45733. world.invertToRef(tmpMat);
  45734. var tmpVect = BABYLON.Tmp.Vector3[8];
  45735. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45736. x = tmpVect.x;
  45737. z = tmpVect.z;
  45738. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45739. return this;
  45740. }
  45741. if (!this._heightQuads || this._heightQuads.length == 0) {
  45742. this._initHeightQuads();
  45743. this._computeHeightQuads();
  45744. }
  45745. var facet = this._getFacetAt(x, z);
  45746. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45747. return this;
  45748. };
  45749. /**
  45750. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45751. * if the ground has been updated.
  45752. * This can be used in the render loop.
  45753. * Returns the GroundMesh.
  45754. */
  45755. GroundMesh.prototype.updateCoordinateHeights = function () {
  45756. if (!this._heightQuads || this._heightQuads.length == 0) {
  45757. this._initHeightQuads();
  45758. }
  45759. this._computeHeightQuads();
  45760. return this;
  45761. };
  45762. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45763. GroundMesh.prototype._getFacetAt = function (x, z) {
  45764. // retrieve col and row from x, z coordinates in the ground local system
  45765. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45766. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45767. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45768. var facet;
  45769. if (z < quad.slope.x * x + quad.slope.y) {
  45770. facet = quad.facet1;
  45771. }
  45772. else {
  45773. facet = quad.facet2;
  45774. }
  45775. return facet;
  45776. };
  45777. // Creates and populates the heightMap array with "facet" elements :
  45778. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45779. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45780. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45781. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45782. // Returns the GroundMesh.
  45783. GroundMesh.prototype._initHeightQuads = function () {
  45784. var subdivisionsX = this._subdivisionsX;
  45785. var subdivisionsY = this._subdivisionsY;
  45786. this._heightQuads = new Array();
  45787. for (var row = 0; row < subdivisionsY; row++) {
  45788. for (var col = 0; col < subdivisionsX; col++) {
  45789. 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) };
  45790. this._heightQuads[row * subdivisionsX + col] = quad;
  45791. }
  45792. }
  45793. return this;
  45794. };
  45795. // Compute each quad element values and update the the heightMap array :
  45796. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45797. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45798. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45799. // Returns the GroundMesh.
  45800. GroundMesh.prototype._computeHeightQuads = function () {
  45801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45802. if (!positions) {
  45803. return this;
  45804. }
  45805. var v1 = BABYLON.Tmp.Vector3[3];
  45806. var v2 = BABYLON.Tmp.Vector3[2];
  45807. var v3 = BABYLON.Tmp.Vector3[1];
  45808. var v4 = BABYLON.Tmp.Vector3[0];
  45809. var v1v2 = BABYLON.Tmp.Vector3[4];
  45810. var v1v3 = BABYLON.Tmp.Vector3[5];
  45811. var v1v4 = BABYLON.Tmp.Vector3[6];
  45812. var norm1 = BABYLON.Tmp.Vector3[7];
  45813. var norm2 = BABYLON.Tmp.Vector3[8];
  45814. var i = 0;
  45815. var j = 0;
  45816. var k = 0;
  45817. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45818. var h = 0;
  45819. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45820. var d2 = 0;
  45821. var subdivisionsX = this._subdivisionsX;
  45822. var subdivisionsY = this._subdivisionsY;
  45823. for (var row = 0; row < subdivisionsY; row++) {
  45824. for (var col = 0; col < subdivisionsX; col++) {
  45825. i = col * 3;
  45826. j = row * (subdivisionsX + 1) * 3;
  45827. k = (row + 1) * (subdivisionsX + 1) * 3;
  45828. v1.x = positions[j + i];
  45829. v1.y = positions[j + i + 1];
  45830. v1.z = positions[j + i + 2];
  45831. v2.x = positions[j + i + 3];
  45832. v2.y = positions[j + i + 4];
  45833. v2.z = positions[j + i + 5];
  45834. v3.x = positions[k + i];
  45835. v3.y = positions[k + i + 1];
  45836. v3.z = positions[k + i + 2];
  45837. v4.x = positions[k + i + 3];
  45838. v4.y = positions[k + i + 4];
  45839. v4.z = positions[k + i + 5];
  45840. // 2D slope V1V4
  45841. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45842. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45843. // facet equations :
  45844. // we compute each facet normal vector
  45845. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45846. // we compute the value d by applying the equation to v1 which belongs to the plane
  45847. // then we store the facet equation in a Vector4
  45848. v2.subtractToRef(v1, v1v2);
  45849. v3.subtractToRef(v1, v1v3);
  45850. v4.subtractToRef(v1, v1v4);
  45851. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45852. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45853. norm1.normalize();
  45854. norm2.normalize();
  45855. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45856. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45857. var quad = this._heightQuads[row * subdivisionsX + col];
  45858. quad.slope.copyFromFloats(cd, h);
  45859. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45860. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45861. }
  45862. }
  45863. return this;
  45864. };
  45865. GroundMesh.prototype.serialize = function (serializationObject) {
  45866. _super.prototype.serialize.call(this, serializationObject);
  45867. serializationObject.subdivisionsX = this._subdivisionsX;
  45868. serializationObject.subdivisionsY = this._subdivisionsY;
  45869. serializationObject.minX = this._minX;
  45870. serializationObject.maxX = this._maxX;
  45871. serializationObject.minZ = this._minZ;
  45872. serializationObject.maxZ = this._maxZ;
  45873. serializationObject.width = this._width;
  45874. serializationObject.height = this._height;
  45875. };
  45876. GroundMesh.Parse = function (parsedMesh, scene) {
  45877. var result = new GroundMesh(parsedMesh.name, scene);
  45878. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45879. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45880. result._minX = parsedMesh.minX;
  45881. result._maxX = parsedMesh.maxX;
  45882. result._minZ = parsedMesh.minZ;
  45883. result._maxZ = parsedMesh.maxZ;
  45884. result._width = parsedMesh.width;
  45885. result._height = parsedMesh.height;
  45886. return result;
  45887. };
  45888. return GroundMesh;
  45889. }(BABYLON.Mesh));
  45890. BABYLON.GroundMesh = GroundMesh;
  45891. })(BABYLON || (BABYLON = {}));
  45892. //# sourceMappingURL=babylon.groundMesh.js.map
  45893. var BABYLON;
  45894. (function (BABYLON) {
  45895. /**
  45896. * Creates an instance based on a source mesh.
  45897. */
  45898. var InstancedMesh = /** @class */ (function (_super) {
  45899. __extends(InstancedMesh, _super);
  45900. function InstancedMesh(name, source) {
  45901. var _this = _super.call(this, name, source.getScene()) || this;
  45902. source.instances.push(_this);
  45903. _this._sourceMesh = source;
  45904. _this.position.copyFrom(source.position);
  45905. _this.rotation.copyFrom(source.rotation);
  45906. _this.scaling.copyFrom(source.scaling);
  45907. if (source.rotationQuaternion) {
  45908. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45909. }
  45910. _this.infiniteDistance = source.infiniteDistance;
  45911. _this.setPivotMatrix(source.getPivotMatrix());
  45912. _this.refreshBoundingInfo();
  45913. _this._syncSubMeshes();
  45914. return _this;
  45915. }
  45916. /**
  45917. * Returns the string "InstancedMesh".
  45918. */
  45919. InstancedMesh.prototype.getClassName = function () {
  45920. return "InstancedMesh";
  45921. };
  45922. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45923. // Methods
  45924. get: function () {
  45925. return this._sourceMesh.receiveShadows;
  45926. },
  45927. enumerable: true,
  45928. configurable: true
  45929. });
  45930. Object.defineProperty(InstancedMesh.prototype, "material", {
  45931. get: function () {
  45932. return this._sourceMesh.material;
  45933. },
  45934. enumerable: true,
  45935. configurable: true
  45936. });
  45937. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45938. get: function () {
  45939. return this._sourceMesh.visibility;
  45940. },
  45941. enumerable: true,
  45942. configurable: true
  45943. });
  45944. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45945. get: function () {
  45946. return this._sourceMesh.skeleton;
  45947. },
  45948. enumerable: true,
  45949. configurable: true
  45950. });
  45951. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45952. get: function () {
  45953. return this._sourceMesh.renderingGroupId;
  45954. },
  45955. enumerable: true,
  45956. configurable: true
  45957. });
  45958. /**
  45959. * Returns the total number of vertices (integer).
  45960. */
  45961. InstancedMesh.prototype.getTotalVertices = function () {
  45962. return this._sourceMesh.getTotalVertices();
  45963. };
  45964. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45965. get: function () {
  45966. return this._sourceMesh;
  45967. },
  45968. enumerable: true,
  45969. configurable: true
  45970. });
  45971. /**
  45972. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45973. */
  45974. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45975. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45976. };
  45977. /**
  45978. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45979. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45980. * The `data` are either a numeric array either a Float32Array.
  45981. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45982. * 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).
  45983. * Note that a new underlying VertexBuffer object is created each call.
  45984. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45985. *
  45986. * Possible `kind` values :
  45987. * - BABYLON.VertexBuffer.PositionKind
  45988. * - BABYLON.VertexBuffer.UVKind
  45989. * - BABYLON.VertexBuffer.UV2Kind
  45990. * - BABYLON.VertexBuffer.UV3Kind
  45991. * - BABYLON.VertexBuffer.UV4Kind
  45992. * - BABYLON.VertexBuffer.UV5Kind
  45993. * - BABYLON.VertexBuffer.UV6Kind
  45994. * - BABYLON.VertexBuffer.ColorKind
  45995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45999. *
  46000. * Returns the Mesh.
  46001. */
  46002. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46003. if (this.sourceMesh) {
  46004. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46005. }
  46006. return this.sourceMesh;
  46007. };
  46008. /**
  46009. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46010. * If the mesh has no geometry, it is simply returned as it is.
  46011. * The `data` are either a numeric array either a Float32Array.
  46012. * No new underlying VertexBuffer object is created.
  46013. * 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.
  46014. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46015. *
  46016. * Possible `kind` values :
  46017. * - BABYLON.VertexBuffer.PositionKind
  46018. * - BABYLON.VertexBuffer.UVKind
  46019. * - BABYLON.VertexBuffer.UV2Kind
  46020. * - BABYLON.VertexBuffer.UV3Kind
  46021. * - BABYLON.VertexBuffer.UV4Kind
  46022. * - BABYLON.VertexBuffer.UV5Kind
  46023. * - BABYLON.VertexBuffer.UV6Kind
  46024. * - BABYLON.VertexBuffer.ColorKind
  46025. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46026. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46027. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46028. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46029. *
  46030. * Returns the Mesh.
  46031. */
  46032. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46033. if (this.sourceMesh) {
  46034. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46035. }
  46036. return this.sourceMesh;
  46037. };
  46038. /**
  46039. * Sets the mesh indices.
  46040. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46041. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46042. * This method creates a new index buffer each call.
  46043. * Returns the Mesh.
  46044. */
  46045. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46046. if (totalVertices === void 0) { totalVertices = null; }
  46047. if (this.sourceMesh) {
  46048. this.sourceMesh.setIndices(indices, totalVertices);
  46049. }
  46050. return this.sourceMesh;
  46051. };
  46052. /**
  46053. * Boolean : True if the mesh owns the requested kind of data.
  46054. */
  46055. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46056. return this._sourceMesh.isVerticesDataPresent(kind);
  46057. };
  46058. /**
  46059. * Returns an array of indices (IndicesArray).
  46060. */
  46061. InstancedMesh.prototype.getIndices = function () {
  46062. return this._sourceMesh.getIndices();
  46063. };
  46064. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46065. get: function () {
  46066. return this._sourceMesh._positions;
  46067. },
  46068. enumerable: true,
  46069. configurable: true
  46070. });
  46071. /**
  46072. * Sets a new updated BoundingInfo to the mesh.
  46073. * Returns the mesh.
  46074. */
  46075. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46076. var meshBB = this._sourceMesh.getBoundingInfo();
  46077. if (meshBB) {
  46078. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46079. }
  46080. this._updateBoundingInfo();
  46081. return this;
  46082. };
  46083. InstancedMesh.prototype._preActivate = function () {
  46084. if (this._currentLOD) {
  46085. this._currentLOD._preActivate();
  46086. }
  46087. return this;
  46088. };
  46089. InstancedMesh.prototype._activate = function (renderId) {
  46090. if (this._currentLOD) {
  46091. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46092. }
  46093. return this;
  46094. };
  46095. /**
  46096. * Returns the current associated LOD AbstractMesh.
  46097. */
  46098. InstancedMesh.prototype.getLOD = function (camera) {
  46099. if (!camera) {
  46100. return this;
  46101. }
  46102. var boundingInfo = this.getBoundingInfo();
  46103. if (!boundingInfo) {
  46104. return this;
  46105. }
  46106. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46107. if (this._currentLOD === this.sourceMesh) {
  46108. return this;
  46109. }
  46110. return this._currentLOD;
  46111. };
  46112. InstancedMesh.prototype._syncSubMeshes = function () {
  46113. this.releaseSubMeshes();
  46114. if (this._sourceMesh.subMeshes) {
  46115. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46116. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46117. }
  46118. }
  46119. return this;
  46120. };
  46121. InstancedMesh.prototype._generatePointsArray = function () {
  46122. return this._sourceMesh._generatePointsArray();
  46123. };
  46124. /**
  46125. * Creates a new InstancedMesh from the current mesh.
  46126. * - name (string) : the cloned mesh name
  46127. * - newParent (optional Node) : the optional Node to parent the clone to.
  46128. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46129. *
  46130. * Returns the clone.
  46131. */
  46132. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46133. var result = this._sourceMesh.createInstance(name);
  46134. // Deep copy
  46135. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46136. // Bounding info
  46137. this.refreshBoundingInfo();
  46138. // Parent
  46139. if (newParent) {
  46140. result.parent = newParent;
  46141. }
  46142. if (!doNotCloneChildren) {
  46143. // Children
  46144. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46145. var mesh = this.getScene().meshes[index];
  46146. if (mesh.parent === this) {
  46147. mesh.clone(mesh.name, result);
  46148. }
  46149. }
  46150. }
  46151. result.computeWorldMatrix(true);
  46152. return result;
  46153. };
  46154. /**
  46155. * Disposes the InstancedMesh.
  46156. * Returns nothing.
  46157. */
  46158. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46159. // Remove from mesh
  46160. var index = this._sourceMesh.instances.indexOf(this);
  46161. this._sourceMesh.instances.splice(index, 1);
  46162. _super.prototype.dispose.call(this, doNotRecurse);
  46163. };
  46164. return InstancedMesh;
  46165. }(BABYLON.AbstractMesh));
  46166. BABYLON.InstancedMesh = InstancedMesh;
  46167. })(BABYLON || (BABYLON = {}));
  46168. //# sourceMappingURL=babylon.instancedMesh.js.map
  46169. var BABYLON;
  46170. (function (BABYLON) {
  46171. var LinesMesh = /** @class */ (function (_super) {
  46172. __extends(LinesMesh, _super);
  46173. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46174. if (scene === void 0) { scene = null; }
  46175. if (parent === void 0) { parent = null; }
  46176. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46177. _this.useVertexColor = useVertexColor;
  46178. _this.color = new BABYLON.Color3(1, 1, 1);
  46179. _this.alpha = 1;
  46180. if (source) {
  46181. _this.color = source.color.clone();
  46182. _this.alpha = source.alpha;
  46183. _this.useVertexColor = source.useVertexColor;
  46184. }
  46185. _this._intersectionThreshold = 0.1;
  46186. var options = {
  46187. attributes: [BABYLON.VertexBuffer.PositionKind],
  46188. uniforms: ["world", "viewProjection"],
  46189. needAlphaBlending: false,
  46190. };
  46191. if (!useVertexColor) {
  46192. options.uniforms.push("color");
  46193. options.needAlphaBlending = true;
  46194. }
  46195. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46196. return _this;
  46197. }
  46198. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46199. /**
  46200. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46201. * This margin is expressed in world space coordinates, so its value may vary.
  46202. * Default value is 0.1
  46203. * @returns the intersection Threshold value.
  46204. */
  46205. get: function () {
  46206. return this._intersectionThreshold;
  46207. },
  46208. /**
  46209. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46210. * This margin is expressed in world space coordinates, so its value may vary.
  46211. * @param value the new threshold to apply
  46212. */
  46213. set: function (value) {
  46214. if (this._intersectionThreshold === value) {
  46215. return;
  46216. }
  46217. this._intersectionThreshold = value;
  46218. if (this.geometry) {
  46219. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46220. }
  46221. },
  46222. enumerable: true,
  46223. configurable: true
  46224. });
  46225. /**
  46226. * Returns the string "LineMesh"
  46227. */
  46228. LinesMesh.prototype.getClassName = function () {
  46229. return "LinesMesh";
  46230. };
  46231. Object.defineProperty(LinesMesh.prototype, "material", {
  46232. get: function () {
  46233. return this._colorShader;
  46234. },
  46235. enumerable: true,
  46236. configurable: true
  46237. });
  46238. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46239. get: function () {
  46240. return false;
  46241. },
  46242. enumerable: true,
  46243. configurable: true
  46244. });
  46245. LinesMesh.prototype.createInstance = function (name) {
  46246. throw new Error("LinesMeshes do not support createInstance.");
  46247. };
  46248. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46249. if (!this._geometry) {
  46250. return this;
  46251. }
  46252. // VBOs
  46253. this._geometry._bind(this._colorShader.getEffect());
  46254. // Color
  46255. if (!this.useVertexColor) {
  46256. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46257. }
  46258. return this;
  46259. };
  46260. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46261. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46262. return this;
  46263. }
  46264. var engine = this.getScene().getEngine();
  46265. // Draw order
  46266. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46267. return this;
  46268. };
  46269. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46270. this._colorShader.dispose();
  46271. _super.prototype.dispose.call(this, doNotRecurse);
  46272. };
  46273. /**
  46274. * Returns a new LineMesh object cloned from the current one.
  46275. */
  46276. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46277. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46278. };
  46279. return LinesMesh;
  46280. }(BABYLON.Mesh));
  46281. BABYLON.LinesMesh = LinesMesh;
  46282. })(BABYLON || (BABYLON = {}));
  46283. //# sourceMappingURL=babylon.linesMesh.js.map
  46284. var BABYLON;
  46285. (function (BABYLON) {
  46286. var ShaderMaterial = /** @class */ (function (_super) {
  46287. __extends(ShaderMaterial, _super);
  46288. function ShaderMaterial(name, scene, shaderPath, options) {
  46289. var _this = _super.call(this, name, scene) || this;
  46290. _this._textures = {};
  46291. _this._textureArrays = {};
  46292. _this._floats = {};
  46293. _this._floatsArrays = {};
  46294. _this._colors3 = {};
  46295. _this._colors3Arrays = {};
  46296. _this._colors4 = {};
  46297. _this._vectors2 = {};
  46298. _this._vectors3 = {};
  46299. _this._vectors4 = {};
  46300. _this._matrices = {};
  46301. _this._matrices3x3 = {};
  46302. _this._matrices2x2 = {};
  46303. _this._vectors3Arrays = {};
  46304. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46305. _this._shaderPath = shaderPath;
  46306. options.needAlphaBlending = options.needAlphaBlending || false;
  46307. options.needAlphaTesting = options.needAlphaTesting || false;
  46308. options.attributes = options.attributes || ["position", "normal", "uv"];
  46309. options.uniforms = options.uniforms || ["worldViewProjection"];
  46310. options.uniformBuffers = options.uniformBuffers || [];
  46311. options.samplers = options.samplers || [];
  46312. options.defines = options.defines || [];
  46313. _this._options = options;
  46314. return _this;
  46315. }
  46316. ShaderMaterial.prototype.getClassName = function () {
  46317. return "ShaderMaterial";
  46318. };
  46319. ShaderMaterial.prototype.needAlphaBlending = function () {
  46320. return this._options.needAlphaBlending;
  46321. };
  46322. ShaderMaterial.prototype.needAlphaTesting = function () {
  46323. return this._options.needAlphaTesting;
  46324. };
  46325. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46326. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46327. this._options.uniforms.push(uniformName);
  46328. }
  46329. };
  46330. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46331. if (this._options.samplers.indexOf(name) === -1) {
  46332. this._options.samplers.push(name);
  46333. }
  46334. this._textures[name] = texture;
  46335. return this;
  46336. };
  46337. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46338. if (this._options.samplers.indexOf(name) === -1) {
  46339. this._options.samplers.push(name);
  46340. }
  46341. this._checkUniform(name);
  46342. this._textureArrays[name] = textures;
  46343. return this;
  46344. };
  46345. ShaderMaterial.prototype.setFloat = function (name, value) {
  46346. this._checkUniform(name);
  46347. this._floats[name] = value;
  46348. return this;
  46349. };
  46350. ShaderMaterial.prototype.setFloats = function (name, value) {
  46351. this._checkUniform(name);
  46352. this._floatsArrays[name] = value;
  46353. return this;
  46354. };
  46355. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46356. this._checkUniform(name);
  46357. this._colors3[name] = value;
  46358. return this;
  46359. };
  46360. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46361. this._checkUniform(name);
  46362. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46363. color.toArray(arr, arr.length);
  46364. return arr;
  46365. }, []);
  46366. return this;
  46367. };
  46368. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46369. this._checkUniform(name);
  46370. this._colors4[name] = value;
  46371. return this;
  46372. };
  46373. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46374. this._checkUniform(name);
  46375. this._vectors2[name] = value;
  46376. return this;
  46377. };
  46378. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46379. this._checkUniform(name);
  46380. this._vectors3[name] = value;
  46381. return this;
  46382. };
  46383. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46384. this._checkUniform(name);
  46385. this._vectors4[name] = value;
  46386. return this;
  46387. };
  46388. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46389. this._checkUniform(name);
  46390. this._matrices[name] = value;
  46391. return this;
  46392. };
  46393. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46394. this._checkUniform(name);
  46395. this._matrices3x3[name] = value;
  46396. return this;
  46397. };
  46398. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46399. this._checkUniform(name);
  46400. this._matrices2x2[name] = value;
  46401. return this;
  46402. };
  46403. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46404. this._checkUniform(name);
  46405. this._vectors3Arrays[name] = value;
  46406. return this;
  46407. };
  46408. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46409. if (!mesh) {
  46410. return true;
  46411. }
  46412. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46413. return false;
  46414. }
  46415. return false;
  46416. };
  46417. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46418. var scene = this.getScene();
  46419. var engine = scene.getEngine();
  46420. if (!this.checkReadyOnEveryCall) {
  46421. if (this._renderId === scene.getRenderId()) {
  46422. if (this._checkCache(scene, mesh, useInstances)) {
  46423. return true;
  46424. }
  46425. }
  46426. }
  46427. // Instances
  46428. var defines = [];
  46429. var attribs = [];
  46430. var fallbacks = new BABYLON.EffectFallbacks();
  46431. if (useInstances) {
  46432. defines.push("#define INSTANCES");
  46433. }
  46434. for (var index = 0; index < this._options.defines.length; index++) {
  46435. defines.push(this._options.defines[index]);
  46436. }
  46437. for (var index = 0; index < this._options.attributes.length; index++) {
  46438. attribs.push(this._options.attributes[index]);
  46439. }
  46440. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46441. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46442. defines.push("#define VERTEXCOLOR");
  46443. }
  46444. // Bones
  46445. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46446. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46447. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46448. if (mesh.numBoneInfluencers > 4) {
  46449. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46450. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46451. }
  46452. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46453. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46454. fallbacks.addCPUSkinningFallback(0, mesh);
  46455. if (this._options.uniforms.indexOf("mBones") === -1) {
  46456. this._options.uniforms.push("mBones");
  46457. }
  46458. }
  46459. else {
  46460. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46461. }
  46462. // Textures
  46463. for (var name in this._textures) {
  46464. if (!this._textures[name].isReady()) {
  46465. return false;
  46466. }
  46467. }
  46468. // Alpha test
  46469. if (engine.getAlphaTesting()) {
  46470. defines.push("#define ALPHATEST");
  46471. }
  46472. var previousEffect = this._effect;
  46473. var join = defines.join("\n");
  46474. this._effect = engine.createEffect(this._shaderPath, {
  46475. attributes: attribs,
  46476. uniformsNames: this._options.uniforms,
  46477. uniformBuffersNames: this._options.uniformBuffers,
  46478. samplers: this._options.samplers,
  46479. defines: join,
  46480. fallbacks: fallbacks,
  46481. onCompiled: this.onCompiled,
  46482. onError: this.onError
  46483. }, engine);
  46484. if (!this._effect.isReady()) {
  46485. return false;
  46486. }
  46487. if (previousEffect !== this._effect) {
  46488. scene.resetCachedMaterial();
  46489. }
  46490. this._renderId = scene.getRenderId();
  46491. return true;
  46492. };
  46493. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46494. var scene = this.getScene();
  46495. if (!this._effect) {
  46496. return;
  46497. }
  46498. if (this._options.uniforms.indexOf("world") !== -1) {
  46499. this._effect.setMatrix("world", world);
  46500. }
  46501. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46502. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46503. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46504. }
  46505. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46506. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46507. }
  46508. };
  46509. ShaderMaterial.prototype.bind = function (world, mesh) {
  46510. // Std values
  46511. this.bindOnlyWorldMatrix(world);
  46512. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46513. if (this._options.uniforms.indexOf("view") !== -1) {
  46514. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46515. }
  46516. if (this._options.uniforms.indexOf("projection") !== -1) {
  46517. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46518. }
  46519. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46520. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46521. }
  46522. // Bones
  46523. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46524. var name;
  46525. // Texture
  46526. for (name in this._textures) {
  46527. this._effect.setTexture(name, this._textures[name]);
  46528. }
  46529. // Texture arrays
  46530. for (name in this._textureArrays) {
  46531. this._effect.setTextureArray(name, this._textureArrays[name]);
  46532. }
  46533. // Float
  46534. for (name in this._floats) {
  46535. this._effect.setFloat(name, this._floats[name]);
  46536. }
  46537. // Float s
  46538. for (name in this._floatsArrays) {
  46539. this._effect.setArray(name, this._floatsArrays[name]);
  46540. }
  46541. // Color3
  46542. for (name in this._colors3) {
  46543. this._effect.setColor3(name, this._colors3[name]);
  46544. }
  46545. for (name in this._colors3Arrays) {
  46546. this._effect.setArray3(name, this._colors3Arrays[name]);
  46547. }
  46548. // Color4
  46549. for (name in this._colors4) {
  46550. var color = this._colors4[name];
  46551. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46552. }
  46553. // Vector2
  46554. for (name in this._vectors2) {
  46555. this._effect.setVector2(name, this._vectors2[name]);
  46556. }
  46557. // Vector3
  46558. for (name in this._vectors3) {
  46559. this._effect.setVector3(name, this._vectors3[name]);
  46560. }
  46561. // Vector4
  46562. for (name in this._vectors4) {
  46563. this._effect.setVector4(name, this._vectors4[name]);
  46564. }
  46565. // Matrix
  46566. for (name in this._matrices) {
  46567. this._effect.setMatrix(name, this._matrices[name]);
  46568. }
  46569. // Matrix 3x3
  46570. for (name in this._matrices3x3) {
  46571. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46572. }
  46573. // Matrix 2x2
  46574. for (name in this._matrices2x2) {
  46575. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46576. }
  46577. // Vector3Array
  46578. for (name in this._vectors3Arrays) {
  46579. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46580. }
  46581. }
  46582. this._afterBind(mesh);
  46583. };
  46584. ShaderMaterial.prototype.getActiveTextures = function () {
  46585. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46586. for (var name in this._textures) {
  46587. activeTextures.push(this._textures[name]);
  46588. }
  46589. for (var name in this._textureArrays) {
  46590. var array = this._textureArrays[name];
  46591. for (var index = 0; index < array.length; index++) {
  46592. activeTextures.push(array[index]);
  46593. }
  46594. }
  46595. return activeTextures;
  46596. };
  46597. ShaderMaterial.prototype.hasTexture = function (texture) {
  46598. if (_super.prototype.hasTexture.call(this, texture)) {
  46599. return true;
  46600. }
  46601. for (var name in this._textures) {
  46602. if (this._textures[name] === texture) {
  46603. return true;
  46604. }
  46605. }
  46606. for (var name in this._textureArrays) {
  46607. var array = this._textureArrays[name];
  46608. for (var index = 0; index < array.length; index++) {
  46609. if (array[index] === texture) {
  46610. return true;
  46611. }
  46612. }
  46613. }
  46614. return false;
  46615. };
  46616. ShaderMaterial.prototype.clone = function (name) {
  46617. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46618. return newShaderMaterial;
  46619. };
  46620. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46621. if (forceDisposeTextures) {
  46622. var name;
  46623. for (name in this._textures) {
  46624. this._textures[name].dispose();
  46625. }
  46626. for (name in this._textureArrays) {
  46627. var array = this._textureArrays[name];
  46628. for (var index = 0; index < array.length; index++) {
  46629. array[index].dispose();
  46630. }
  46631. }
  46632. }
  46633. this._textures = {};
  46634. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46635. };
  46636. ShaderMaterial.prototype.serialize = function () {
  46637. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46638. serializationObject.customType = "BABYLON.ShaderMaterial";
  46639. serializationObject.options = this._options;
  46640. serializationObject.shaderPath = this._shaderPath;
  46641. var name;
  46642. // Texture
  46643. serializationObject.textures = {};
  46644. for (name in this._textures) {
  46645. serializationObject.textures[name] = this._textures[name].serialize();
  46646. }
  46647. // Texture arrays
  46648. serializationObject.textureArrays = {};
  46649. for (name in this._textureArrays) {
  46650. serializationObject.textureArrays[name] = [];
  46651. var array = this._textureArrays[name];
  46652. for (var index = 0; index < array.length; index++) {
  46653. serializationObject.textureArrays[name].push(array[index].serialize());
  46654. }
  46655. }
  46656. // Float
  46657. serializationObject.floats = {};
  46658. for (name in this._floats) {
  46659. serializationObject.floats[name] = this._floats[name];
  46660. }
  46661. // Float s
  46662. serializationObject.FloatArrays = {};
  46663. for (name in this._floatsArrays) {
  46664. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46665. }
  46666. // Color3
  46667. serializationObject.colors3 = {};
  46668. for (name in this._colors3) {
  46669. serializationObject.colors3[name] = this._colors3[name].asArray();
  46670. }
  46671. // Color3 array
  46672. serializationObject.colors3Arrays = {};
  46673. for (name in this._colors3Arrays) {
  46674. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46675. }
  46676. // Color4
  46677. serializationObject.colors4 = {};
  46678. for (name in this._colors4) {
  46679. serializationObject.colors4[name] = this._colors4[name].asArray();
  46680. }
  46681. // Vector2
  46682. serializationObject.vectors2 = {};
  46683. for (name in this._vectors2) {
  46684. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46685. }
  46686. // Vector3
  46687. serializationObject.vectors3 = {};
  46688. for (name in this._vectors3) {
  46689. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46690. }
  46691. // Vector4
  46692. serializationObject.vectors4 = {};
  46693. for (name in this._vectors4) {
  46694. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46695. }
  46696. // Matrix
  46697. serializationObject.matrices = {};
  46698. for (name in this._matrices) {
  46699. serializationObject.matrices[name] = this._matrices[name].asArray();
  46700. }
  46701. // Matrix 3x3
  46702. serializationObject.matrices3x3 = {};
  46703. for (name in this._matrices3x3) {
  46704. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46705. }
  46706. // Matrix 2x2
  46707. serializationObject.matrices2x2 = {};
  46708. for (name in this._matrices2x2) {
  46709. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46710. }
  46711. // Vector3Array
  46712. serializationObject.vectors3Arrays = {};
  46713. for (name in this._vectors3Arrays) {
  46714. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46715. }
  46716. return serializationObject;
  46717. };
  46718. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46719. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46720. var name;
  46721. // Texture
  46722. for (name in source.textures) {
  46723. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46724. }
  46725. // Texture arrays
  46726. for (name in source.textureArrays) {
  46727. var array = source.textureArrays[name];
  46728. var textureArray = new Array();
  46729. for (var index = 0; index < array.length; index++) {
  46730. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46731. }
  46732. material.setTextureArray(name, textureArray);
  46733. }
  46734. // Float
  46735. for (name in source.floats) {
  46736. material.setFloat(name, source.floats[name]);
  46737. }
  46738. // Float s
  46739. for (name in source.floatsArrays) {
  46740. material.setFloats(name, source.floatsArrays[name]);
  46741. }
  46742. // Color3
  46743. for (name in source.colors3) {
  46744. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46745. }
  46746. // Color3 arrays
  46747. for (name in source.colors3Arrays) {
  46748. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46749. if (i % 3 === 0) {
  46750. arr.push([num]);
  46751. }
  46752. else {
  46753. arr[arr.length - 1].push(num);
  46754. }
  46755. return arr;
  46756. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46757. material.setColor3Array(name, colors);
  46758. }
  46759. // Color4
  46760. for (name in source.colors4) {
  46761. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46762. }
  46763. // Vector2
  46764. for (name in source.vectors2) {
  46765. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46766. }
  46767. // Vector3
  46768. for (name in source.vectors3) {
  46769. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46770. }
  46771. // Vector4
  46772. for (name in source.vectors4) {
  46773. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46774. }
  46775. // Matrix
  46776. for (name in source.matrices) {
  46777. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46778. }
  46779. // Matrix 3x3
  46780. for (name in source.matrices3x3) {
  46781. material.setMatrix3x3(name, source.matrices3x3[name]);
  46782. }
  46783. // Matrix 2x2
  46784. for (name in source.matrices2x2) {
  46785. material.setMatrix2x2(name, source.matrices2x2[name]);
  46786. }
  46787. // Vector3Array
  46788. for (name in source.vectors3Arrays) {
  46789. material.setArray3(name, source.vectors3Arrays[name]);
  46790. }
  46791. return material;
  46792. };
  46793. return ShaderMaterial;
  46794. }(BABYLON.Material));
  46795. BABYLON.ShaderMaterial = ShaderMaterial;
  46796. })(BABYLON || (BABYLON = {}));
  46797. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46798. var BABYLON;
  46799. (function (BABYLON) {
  46800. var MeshBuilder = /** @class */ (function () {
  46801. function MeshBuilder() {
  46802. }
  46803. MeshBuilder.updateSideOrientation = function (orientation) {
  46804. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46805. return BABYLON.Mesh.DOUBLESIDE;
  46806. }
  46807. if (orientation === undefined || orientation === null) {
  46808. return BABYLON.Mesh.FRONTSIDE;
  46809. }
  46810. return orientation;
  46811. };
  46812. /**
  46813. * Creates a box mesh.
  46814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46815. * The parameter `size` sets the size (float) of each box side (default 1).
  46816. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46817. * 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).
  46818. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46819. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46820. * 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).
  46821. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46823. */
  46824. MeshBuilder.CreateBox = function (name, options, scene) {
  46825. if (scene === void 0) { scene = null; }
  46826. var box = new BABYLON.Mesh(name, scene);
  46827. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46828. box._originalBuilderSideOrientation = options.sideOrientation;
  46829. var vertexData = BABYLON.VertexData.CreateBox(options);
  46830. vertexData.applyToMesh(box, options.updatable);
  46831. return box;
  46832. };
  46833. /**
  46834. * Creates a sphere mesh.
  46835. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46836. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46837. * 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`).
  46838. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46839. * 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
  46840. * 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).
  46841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46842. * 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).
  46843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46845. */
  46846. MeshBuilder.CreateSphere = function (name, options, scene) {
  46847. var sphere = new BABYLON.Mesh(name, scene);
  46848. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46849. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46850. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46851. vertexData.applyToMesh(sphere, options.updatable);
  46852. return sphere;
  46853. };
  46854. /**
  46855. * Creates a plane polygonal mesh. By default, this is a disc.
  46856. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46857. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46858. * 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.
  46859. * 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
  46860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46861. * 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).
  46862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46864. */
  46865. MeshBuilder.CreateDisc = function (name, options, scene) {
  46866. if (scene === void 0) { scene = null; }
  46867. var disc = new BABYLON.Mesh(name, scene);
  46868. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46869. disc._originalBuilderSideOrientation = options.sideOrientation;
  46870. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46871. vertexData.applyToMesh(disc, options.updatable);
  46872. return disc;
  46873. };
  46874. /**
  46875. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46877. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46878. * 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`).
  46879. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46880. * 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.
  46881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46882. * 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).
  46883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46885. */
  46886. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46887. var sphere = new BABYLON.Mesh(name, scene);
  46888. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46889. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46890. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46891. vertexData.applyToMesh(sphere, options.updatable);
  46892. return sphere;
  46893. };
  46894. ;
  46895. /**
  46896. * Creates a ribbon mesh.
  46897. * 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.
  46898. *
  46899. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46900. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46901. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46902. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46903. * 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.
  46904. * 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.
  46905. * 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
  46906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46907. * 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).
  46908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46909. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46910. * 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.
  46911. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46912. * 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
  46913. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46914. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46916. */
  46917. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46918. if (scene === void 0) { scene = null; }
  46919. var pathArray = options.pathArray;
  46920. var closeArray = options.closeArray;
  46921. var closePath = options.closePath;
  46922. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46923. var instance = options.instance;
  46924. var updatable = options.updatable;
  46925. if (instance) {
  46926. // positionFunction : ribbon case
  46927. // only pathArray and sideOrientation parameters are taken into account for positions update
  46928. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46929. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46930. var positionFunction = function (positions) {
  46931. var minlg = pathArray[0].length;
  46932. var i = 0;
  46933. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46934. for (var si = 1; si <= ns; si++) {
  46935. for (var p = 0; p < pathArray.length; p++) {
  46936. var path = pathArray[p];
  46937. var l = path.length;
  46938. minlg = (minlg < l) ? minlg : l;
  46939. var j = 0;
  46940. while (j < minlg) {
  46941. positions[i] = path[j].x;
  46942. positions[i + 1] = path[j].y;
  46943. positions[i + 2] = path[j].z;
  46944. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46945. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46946. }
  46947. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46948. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46949. }
  46950. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46951. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46952. }
  46953. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46954. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46955. }
  46956. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46957. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46958. }
  46959. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46960. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46961. }
  46962. j++;
  46963. i += 3;
  46964. }
  46965. if (instance._closePath) {
  46966. positions[i] = path[0].x;
  46967. positions[i + 1] = path[0].y;
  46968. positions[i + 2] = path[0].z;
  46969. i += 3;
  46970. }
  46971. }
  46972. }
  46973. };
  46974. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46975. positionFunction(positions);
  46976. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46977. instance._boundingInfo.update(instance._worldMatrix);
  46978. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46979. if (options.colors) {
  46980. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46981. for (var c = 0; c < options.colors.length; c++) {
  46982. colors[c * 4] = options.colors[c].r;
  46983. colors[c * 4 + 1] = options.colors[c].g;
  46984. colors[c * 4 + 2] = options.colors[c].b;
  46985. colors[c * 4 + 3] = options.colors[c].a;
  46986. }
  46987. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46988. }
  46989. if (options.uvs) {
  46990. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46991. for (var i = 0; i < options.uvs.length; i++) {
  46992. uvs[i * 2] = options.uvs[i].x;
  46993. uvs[i * 2 + 1] = options.uvs[i].y;
  46994. }
  46995. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46996. }
  46997. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46998. var indices = instance.getIndices();
  46999. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47000. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47001. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47002. if (instance._closePath) {
  47003. var indexFirst = 0;
  47004. var indexLast = 0;
  47005. for (var p = 0; p < pathArray.length; p++) {
  47006. indexFirst = instance._idx[p] * 3;
  47007. if (p + 1 < pathArray.length) {
  47008. indexLast = (instance._idx[p + 1] - 1) * 3;
  47009. }
  47010. else {
  47011. indexLast = normals.length - 3;
  47012. }
  47013. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47014. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47015. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47016. normals[indexLast] = normals[indexFirst];
  47017. normals[indexLast + 1] = normals[indexFirst + 1];
  47018. normals[indexLast + 2] = normals[indexFirst + 2];
  47019. }
  47020. }
  47021. if (!(instance.areNormalsFrozen)) {
  47022. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47023. }
  47024. }
  47025. return instance;
  47026. }
  47027. else {
  47028. var ribbon = new BABYLON.Mesh(name, scene);
  47029. ribbon._originalBuilderSideOrientation = sideOrientation;
  47030. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47031. if (closePath) {
  47032. ribbon._idx = vertexData._idx;
  47033. }
  47034. ribbon._closePath = closePath;
  47035. ribbon._closeArray = closeArray;
  47036. vertexData.applyToMesh(ribbon, updatable);
  47037. return ribbon;
  47038. }
  47039. };
  47040. /**
  47041. * Creates a cylinder or a cone mesh.
  47042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47043. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47044. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47045. * 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.
  47046. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47047. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47048. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47049. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47050. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47051. * 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).
  47052. * 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
  47053. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47054. * 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
  47055. * 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.
  47056. * If `enclose` is false, a ring surface is one element.
  47057. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47058. * 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
  47059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47060. * 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).
  47061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47063. */
  47064. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47065. var cylinder = new BABYLON.Mesh(name, scene);
  47066. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47067. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47068. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47069. vertexData.applyToMesh(cylinder, options.updatable);
  47070. return cylinder;
  47071. };
  47072. /**
  47073. * Creates a torus mesh.
  47074. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47075. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47076. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47077. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47079. * 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).
  47080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47082. */
  47083. MeshBuilder.CreateTorus = function (name, options, scene) {
  47084. var torus = new BABYLON.Mesh(name, scene);
  47085. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47086. torus._originalBuilderSideOrientation = options.sideOrientation;
  47087. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47088. vertexData.applyToMesh(torus, options.updatable);
  47089. return torus;
  47090. };
  47091. /**
  47092. * Creates a torus knot mesh.
  47093. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47094. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47095. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47096. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47097. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47099. * 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).
  47100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47102. */
  47103. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47104. var torusKnot = new BABYLON.Mesh(name, scene);
  47105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47106. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47107. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47108. vertexData.applyToMesh(torusKnot, options.updatable);
  47109. return torusKnot;
  47110. };
  47111. /**
  47112. * Creates a line system mesh.
  47113. * A line system is a pool of many lines gathered in a single mesh.
  47114. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47115. * 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.
  47116. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47117. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47118. * 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
  47119. * 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
  47120. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47122. */
  47123. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47124. var instance = options.instance;
  47125. var lines = options.lines;
  47126. if (instance) {
  47127. var positionFunction = function (positions) {
  47128. var i = 0;
  47129. for (var l = 0; l < lines.length; l++) {
  47130. var points = lines[l];
  47131. for (var p = 0; p < points.length; p++) {
  47132. positions[i] = points[p].x;
  47133. positions[i + 1] = points[p].y;
  47134. positions[i + 2] = points[p].z;
  47135. i += 3;
  47136. }
  47137. }
  47138. };
  47139. instance.updateMeshPositions(positionFunction, false);
  47140. return instance;
  47141. }
  47142. // line system creation
  47143. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47144. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47145. vertexData.applyToMesh(lineSystem, options.updatable);
  47146. return lineSystem;
  47147. };
  47148. /**
  47149. * Creates a line mesh.
  47150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47151. * 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.
  47152. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47153. * The parameter `points` is an array successive Vector3.
  47154. * 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
  47155. * When updating an instance, remember that only point positions can change, not the number of points.
  47156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47157. */
  47158. MeshBuilder.CreateLines = function (name, options, scene) {
  47159. if (scene === void 0) { scene = null; }
  47160. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47161. return lines;
  47162. };
  47163. /**
  47164. * Creates a dashed line mesh.
  47165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47166. * 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.
  47167. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47168. * The parameter `points` is an array successive Vector3.
  47169. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47170. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47171. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47172. * 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
  47173. * When updating an instance, remember that only point positions can change, not the number of points.
  47174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47175. */
  47176. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47177. if (scene === void 0) { scene = null; }
  47178. var points = options.points;
  47179. var instance = options.instance;
  47180. var gapSize = options.gapSize || 1;
  47181. var dashSize = options.dashSize || 3;
  47182. if (instance) {
  47183. var positionFunction = function (positions) {
  47184. var curvect = BABYLON.Vector3.Zero();
  47185. var nbSeg = positions.length / 6;
  47186. var lg = 0;
  47187. var nb = 0;
  47188. var shft = 0;
  47189. var dashshft = 0;
  47190. var curshft = 0;
  47191. var p = 0;
  47192. var i = 0;
  47193. var j = 0;
  47194. for (i = 0; i < points.length - 1; i++) {
  47195. points[i + 1].subtractToRef(points[i], curvect);
  47196. lg += curvect.length();
  47197. }
  47198. shft = lg / nbSeg;
  47199. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47200. for (i = 0; i < points.length - 1; i++) {
  47201. points[i + 1].subtractToRef(points[i], curvect);
  47202. nb = Math.floor(curvect.length() / shft);
  47203. curvect.normalize();
  47204. j = 0;
  47205. while (j < nb && p < positions.length) {
  47206. curshft = shft * j;
  47207. positions[p] = points[i].x + curshft * curvect.x;
  47208. positions[p + 1] = points[i].y + curshft * curvect.y;
  47209. positions[p + 2] = points[i].z + curshft * curvect.z;
  47210. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47211. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47212. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47213. p += 6;
  47214. j++;
  47215. }
  47216. }
  47217. while (p < positions.length) {
  47218. positions[p] = points[i].x;
  47219. positions[p + 1] = points[i].y;
  47220. positions[p + 2] = points[i].z;
  47221. p += 3;
  47222. }
  47223. };
  47224. instance.updateMeshPositions(positionFunction, false);
  47225. return instance;
  47226. }
  47227. // dashed lines creation
  47228. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47229. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47230. vertexData.applyToMesh(dashedLines, options.updatable);
  47231. dashedLines.dashSize = dashSize;
  47232. dashedLines.gapSize = gapSize;
  47233. return dashedLines;
  47234. };
  47235. /**
  47236. * Creates an extruded shape mesh.
  47237. * 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.
  47238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47239. *
  47240. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47241. * 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
  47242. * extruded along the Z axis.
  47243. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47244. * 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.
  47245. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47246. * 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
  47247. * 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
  47248. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47250. * 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).
  47251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47252. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47254. */
  47255. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47256. if (scene === void 0) { scene = null; }
  47257. var path = options.path;
  47258. var shape = options.shape;
  47259. var scale = options.scale || 1;
  47260. var rotation = options.rotation || 0;
  47261. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47262. var updatable = options.updatable;
  47263. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47264. var instance = options.instance || null;
  47265. var invertUV = options.invertUV || false;
  47266. 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);
  47267. };
  47268. /**
  47269. * Creates an custom extruded shape mesh.
  47270. * 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.
  47271. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47272. *
  47273. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47274. * 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
  47275. * extruded along the Z axis.
  47276. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47277. * 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
  47278. * and the distance of this point from the begining of the path :
  47279. * ```javascript
  47280. * var rotationFunction = function(i, distance) {
  47281. * // do things
  47282. * return rotationValue; }
  47283. * ```
  47284. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47285. * 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
  47286. * and the distance of this point from the begining of the path :
  47287. * ```javascript
  47288. * var scaleFunction = function(i, distance) {
  47289. * // do things
  47290. * return scaleValue;}
  47291. * ```
  47292. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47293. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47294. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47295. * 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
  47296. * 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
  47297. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47299. * 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).
  47300. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47301. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47303. */
  47304. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47305. var path = options.path;
  47306. var shape = options.shape;
  47307. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47308. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47309. var ribbonCloseArray = options.ribbonCloseArray || false;
  47310. var ribbonClosePath = options.ribbonClosePath || false;
  47311. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47312. var updatable = options.updatable;
  47313. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47314. var instance = options.instance;
  47315. var invertUV = options.invertUV || false;
  47316. 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);
  47317. };
  47318. /**
  47319. * Creates lathe mesh.
  47320. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47322. *
  47323. * 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
  47324. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47325. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47326. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47327. * 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.
  47328. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47329. * 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
  47330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47331. * 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).
  47332. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47333. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47335. */
  47336. MeshBuilder.CreateLathe = function (name, options, scene) {
  47337. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47338. var closed = (options.closed === undefined) ? true : options.closed;
  47339. var shape = options.shape;
  47340. var radius = options.radius || 1;
  47341. var tessellation = options.tessellation || 64;
  47342. var updatable = options.updatable;
  47343. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47344. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47345. var pi2 = Math.PI * 2;
  47346. var paths = new Array();
  47347. var invertUV = options.invertUV || false;
  47348. var i = 0;
  47349. var p = 0;
  47350. var step = pi2 / tessellation * arc;
  47351. var rotated;
  47352. var path = new Array();
  47353. ;
  47354. for (i = 0; i <= tessellation; i++) {
  47355. var path = [];
  47356. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47357. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47358. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47359. }
  47360. for (p = 0; p < shape.length; p++) {
  47361. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47362. path.push(rotated);
  47363. }
  47364. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47365. 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));
  47366. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47367. }
  47368. paths.push(path);
  47369. }
  47370. // lathe ribbon
  47371. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47372. return lathe;
  47373. };
  47374. /**
  47375. * Creates a plane mesh.
  47376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47377. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47378. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47379. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47381. * 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).
  47382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47384. */
  47385. MeshBuilder.CreatePlane = function (name, options, scene) {
  47386. var plane = new BABYLON.Mesh(name, scene);
  47387. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47388. plane._originalBuilderSideOrientation = options.sideOrientation;
  47389. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47390. vertexData.applyToMesh(plane, options.updatable);
  47391. if (options.sourcePlane) {
  47392. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47393. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47394. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47395. plane.rotate(vectorProduct, product);
  47396. }
  47397. return plane;
  47398. };
  47399. /**
  47400. * Creates a ground mesh.
  47401. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47402. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47403. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47405. */
  47406. MeshBuilder.CreateGround = function (name, options, scene) {
  47407. var ground = new BABYLON.GroundMesh(name, scene);
  47408. ground._setReady(false);
  47409. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47410. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47411. ground._width = options.width || 1;
  47412. ground._height = options.height || 1;
  47413. ground._maxX = ground._width / 2;
  47414. ground._maxZ = ground._height / 2;
  47415. ground._minX = -ground._maxX;
  47416. ground._minZ = -ground._maxZ;
  47417. var vertexData = BABYLON.VertexData.CreateGround(options);
  47418. vertexData.applyToMesh(ground, options.updatable);
  47419. ground._setReady(true);
  47420. return ground;
  47421. };
  47422. /**
  47423. * Creates a tiled ground mesh.
  47424. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47425. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47426. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47427. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47428. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47429. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47430. * numbers of subdivisions on the ground width and height of each tile.
  47431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47432. */
  47433. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47434. var tiledGround = new BABYLON.Mesh(name, scene);
  47435. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47436. vertexData.applyToMesh(tiledGround, options.updatable);
  47437. return tiledGround;
  47438. };
  47439. /**
  47440. * Creates a ground mesh from a height map.
  47441. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47442. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47443. * The parameter `url` sets the URL of the height map image resource.
  47444. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47445. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47446. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47447. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47448. * 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.
  47449. * 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).
  47450. * This function is passed the newly built mesh :
  47451. * ```javascript
  47452. * function(mesh) { // do things
  47453. * return; }
  47454. * ```
  47455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47456. */
  47457. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47458. var width = options.width || 10.0;
  47459. var height = options.height || 10.0;
  47460. var subdivisions = options.subdivisions || 1 | 0;
  47461. var minHeight = options.minHeight || 0.0;
  47462. var maxHeight = options.maxHeight || 1.0;
  47463. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47464. var updatable = options.updatable;
  47465. var onReady = options.onReady;
  47466. var ground = new BABYLON.GroundMesh(name, scene);
  47467. ground._subdivisionsX = subdivisions;
  47468. ground._subdivisionsY = subdivisions;
  47469. ground._width = width;
  47470. ground._height = height;
  47471. ground._maxX = ground._width / 2.0;
  47472. ground._maxZ = ground._height / 2.0;
  47473. ground._minX = -ground._maxX;
  47474. ground._minZ = -ground._maxZ;
  47475. ground._setReady(false);
  47476. var onload = function (img) {
  47477. // Getting height map data
  47478. var canvas = document.createElement("canvas");
  47479. var context = canvas.getContext("2d");
  47480. if (!context) {
  47481. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47482. }
  47483. var bufferWidth = img.width;
  47484. var bufferHeight = img.height;
  47485. canvas.width = bufferWidth;
  47486. canvas.height = bufferHeight;
  47487. context.drawImage(img, 0, 0);
  47488. // Create VertexData from map data
  47489. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47490. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47491. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47492. width: width, height: height,
  47493. subdivisions: subdivisions,
  47494. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47495. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47496. });
  47497. vertexData.applyToMesh(ground, updatable);
  47498. ground._setReady(true);
  47499. //execute ready callback, if set
  47500. if (onReady) {
  47501. onReady(ground);
  47502. }
  47503. };
  47504. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47505. return ground;
  47506. };
  47507. /**
  47508. * Creates a polygon mesh.
  47509. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47510. * 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.
  47511. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47513. * 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).
  47514. * Remember you can only change the shape positions, not their number when updating a polygon.
  47515. */
  47516. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47517. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47518. var shape = options.shape;
  47519. var holes = options.holes || [];
  47520. var depth = options.depth || 0;
  47521. var contours = [];
  47522. var hole = [];
  47523. for (var i = 0; i < shape.length; i++) {
  47524. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47525. }
  47526. var epsilon = 0.00000001;
  47527. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47528. contours.pop();
  47529. }
  47530. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47531. for (var hNb = 0; hNb < holes.length; hNb++) {
  47532. hole = [];
  47533. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47534. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47535. }
  47536. polygonTriangulation.addHole(hole);
  47537. }
  47538. var polygon = polygonTriangulation.build(options.updatable, depth);
  47539. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47540. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47541. vertexData.applyToMesh(polygon, options.updatable);
  47542. return polygon;
  47543. };
  47544. ;
  47545. /**
  47546. * Creates an extruded polygon mesh, with depth in the Y direction.
  47547. * 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).
  47548. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47549. */
  47550. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47551. return MeshBuilder.CreatePolygon(name, options, scene);
  47552. };
  47553. ;
  47554. /**
  47555. * Creates a tube mesh.
  47556. * 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.
  47557. *
  47558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47559. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47560. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47561. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47562. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47563. * 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.
  47564. * It must return a radius value (positive float) :
  47565. * ```javascript
  47566. * var radiusFunction = function(i, distance) {
  47567. * // do things
  47568. * return radius; }
  47569. * ```
  47570. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47571. * 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
  47572. * 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
  47573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47574. * 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).
  47575. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47576. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47578. */
  47579. MeshBuilder.CreateTube = function (name, options, scene) {
  47580. var path = options.path;
  47581. var instance = options.instance;
  47582. var radius = 1.0;
  47583. if (instance) {
  47584. radius = instance.radius;
  47585. }
  47586. if (options.radius !== undefined) {
  47587. radius = options.radius;
  47588. }
  47589. ;
  47590. var tessellation = options.tessellation || 64 | 0;
  47591. var radiusFunction = options.radiusFunction || null;
  47592. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47593. var invertUV = options.invertUV || false;
  47594. var updatable = options.updatable;
  47595. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47596. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47597. // tube geometry
  47598. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47599. var tangents = path3D.getTangents();
  47600. var normals = path3D.getNormals();
  47601. var distances = path3D.getDistances();
  47602. var pi2 = Math.PI * 2;
  47603. var step = pi2 / tessellation * arc;
  47604. var returnRadius = function () { return radius; };
  47605. var radiusFunctionFinal = radiusFunction || returnRadius;
  47606. var circlePath;
  47607. var rad;
  47608. var normal;
  47609. var rotated;
  47610. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47611. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47612. for (var i = 0; i < path.length; i++) {
  47613. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47614. circlePath = Array(); // current circle array
  47615. normal = normals[i]; // current normal
  47616. for (var t = 0; t < tessellation; t++) {
  47617. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47618. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47619. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47620. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47621. circlePath[t] = rotated;
  47622. }
  47623. circlePaths[index] = circlePath;
  47624. index++;
  47625. }
  47626. // cap
  47627. var capPath = function (nbPoints, pathIndex) {
  47628. var pointCap = Array();
  47629. for (var i = 0; i < nbPoints; i++) {
  47630. pointCap.push(path[pathIndex]);
  47631. }
  47632. return pointCap;
  47633. };
  47634. switch (cap) {
  47635. case BABYLON.Mesh.NO_CAP:
  47636. break;
  47637. case BABYLON.Mesh.CAP_START:
  47638. circlePaths[0] = capPath(tessellation, 0);
  47639. circlePaths[1] = circlePaths[2].slice(0);
  47640. break;
  47641. case BABYLON.Mesh.CAP_END:
  47642. circlePaths[index] = circlePaths[index - 1].slice(0);
  47643. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47644. break;
  47645. case BABYLON.Mesh.CAP_ALL:
  47646. circlePaths[0] = capPath(tessellation, 0);
  47647. circlePaths[1] = circlePaths[2].slice(0);
  47648. circlePaths[index] = circlePaths[index - 1].slice(0);
  47649. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47650. break;
  47651. default:
  47652. break;
  47653. }
  47654. return circlePaths;
  47655. };
  47656. var path3D;
  47657. var pathArray;
  47658. if (instance) {
  47659. var arc = options.arc || instance.arc;
  47660. path3D = (instance.path3D).update(path);
  47661. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47662. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47663. instance.path3D = path3D;
  47664. instance.pathArray = pathArray;
  47665. instance.arc = arc;
  47666. instance.radius = radius;
  47667. return instance;
  47668. }
  47669. // tube creation
  47670. path3D = new BABYLON.Path3D(path);
  47671. var newPathArray = new Array();
  47672. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47673. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47674. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47675. tube.pathArray = pathArray;
  47676. tube.path3D = path3D;
  47677. tube.tessellation = tessellation;
  47678. tube.cap = cap;
  47679. tube.arc = options.arc;
  47680. tube.radius = radius;
  47681. return tube;
  47682. };
  47683. /**
  47684. * Creates a polyhedron mesh.
  47685. *
  47686. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47687. * 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
  47688. * to choose the wanted type.
  47689. * The parameter `size` (positive float, default 1) sets the polygon size.
  47690. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47691. * 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`.
  47692. * 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
  47693. * 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)`).
  47694. * 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
  47695. * 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.
  47696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47697. * 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).
  47698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47700. */
  47701. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47702. var polyhedron = new BABYLON.Mesh(name, scene);
  47703. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47704. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47705. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47706. vertexData.applyToMesh(polyhedron, options.updatable);
  47707. return polyhedron;
  47708. };
  47709. /**
  47710. * Creates a decal mesh.
  47711. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47712. * 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.
  47713. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47714. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47715. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47716. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47717. */
  47718. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47719. var indices = sourceMesh.getIndices();
  47720. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47721. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47722. var position = options.position || BABYLON.Vector3.Zero();
  47723. var normal = options.normal || BABYLON.Vector3.Up();
  47724. var size = options.size || BABYLON.Vector3.One();
  47725. var angle = options.angle || 0;
  47726. // Getting correct rotation
  47727. if (!normal) {
  47728. var target = new BABYLON.Vector3(0, 0, 1);
  47729. var camera = sourceMesh.getScene().activeCamera;
  47730. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47731. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47732. }
  47733. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47734. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47735. var pitch = Math.atan2(normal.y, len);
  47736. // Matrix
  47737. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47738. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47739. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47740. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47741. var vertexData = new BABYLON.VertexData();
  47742. vertexData.indices = [];
  47743. vertexData.positions = [];
  47744. vertexData.normals = [];
  47745. vertexData.uvs = [];
  47746. var currentVertexDataIndex = 0;
  47747. var extractDecalVector3 = function (indexId) {
  47748. var result = new BABYLON.PositionNormalVertex();
  47749. if (!indices || !positions || !normals) {
  47750. return result;
  47751. }
  47752. var vertexId = indices[indexId];
  47753. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47754. // Send vector to decal local world
  47755. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47756. // Get normal
  47757. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47758. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47759. return result;
  47760. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47761. var clip = function (vertices, axis) {
  47762. if (vertices.length === 0) {
  47763. return vertices;
  47764. }
  47765. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47766. var clipVertices = function (v0, v1) {
  47767. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47768. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47769. };
  47770. var result = new Array();
  47771. for (var index = 0; index < vertices.length; index += 3) {
  47772. var v1Out;
  47773. var v2Out;
  47774. var v3Out;
  47775. var total = 0;
  47776. var nV1 = null;
  47777. var nV2 = null;
  47778. var nV3 = null;
  47779. var nV4 = null;
  47780. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47781. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47782. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47783. v1Out = d1 > 0;
  47784. v2Out = d2 > 0;
  47785. v3Out = d3 > 0;
  47786. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47787. switch (total) {
  47788. case 0:
  47789. result.push(vertices[index]);
  47790. result.push(vertices[index + 1]);
  47791. result.push(vertices[index + 2]);
  47792. break;
  47793. case 1:
  47794. if (v1Out) {
  47795. nV1 = vertices[index + 1];
  47796. nV2 = vertices[index + 2];
  47797. nV3 = clipVertices(vertices[index], nV1);
  47798. nV4 = clipVertices(vertices[index], nV2);
  47799. }
  47800. if (v2Out) {
  47801. nV1 = vertices[index];
  47802. nV2 = vertices[index + 2];
  47803. nV3 = clipVertices(vertices[index + 1], nV1);
  47804. nV4 = clipVertices(vertices[index + 1], nV2);
  47805. result.push(nV3);
  47806. result.push(nV2.clone());
  47807. result.push(nV1.clone());
  47808. result.push(nV2.clone());
  47809. result.push(nV3.clone());
  47810. result.push(nV4);
  47811. break;
  47812. }
  47813. if (v3Out) {
  47814. nV1 = vertices[index];
  47815. nV2 = vertices[index + 1];
  47816. nV3 = clipVertices(vertices[index + 2], nV1);
  47817. nV4 = clipVertices(vertices[index + 2], nV2);
  47818. }
  47819. if (nV1 && nV2 && nV3 && nV4) {
  47820. result.push(nV1.clone());
  47821. result.push(nV2.clone());
  47822. result.push(nV3);
  47823. result.push(nV4);
  47824. result.push(nV3.clone());
  47825. result.push(nV2.clone());
  47826. }
  47827. break;
  47828. case 2:
  47829. if (!v1Out) {
  47830. nV1 = vertices[index].clone();
  47831. nV2 = clipVertices(nV1, vertices[index + 1]);
  47832. nV3 = clipVertices(nV1, vertices[index + 2]);
  47833. result.push(nV1);
  47834. result.push(nV2);
  47835. result.push(nV3);
  47836. }
  47837. if (!v2Out) {
  47838. nV1 = vertices[index + 1].clone();
  47839. nV2 = clipVertices(nV1, vertices[index + 2]);
  47840. nV3 = clipVertices(nV1, vertices[index]);
  47841. result.push(nV1);
  47842. result.push(nV2);
  47843. result.push(nV3);
  47844. }
  47845. if (!v3Out) {
  47846. nV1 = vertices[index + 2].clone();
  47847. nV2 = clipVertices(nV1, vertices[index]);
  47848. nV3 = clipVertices(nV1, vertices[index + 1]);
  47849. result.push(nV1);
  47850. result.push(nV2);
  47851. result.push(nV3);
  47852. }
  47853. break;
  47854. case 3:
  47855. break;
  47856. }
  47857. }
  47858. return result;
  47859. };
  47860. for (var index = 0; index < indices.length; index += 3) {
  47861. var faceVertices = new Array();
  47862. faceVertices.push(extractDecalVector3(index));
  47863. faceVertices.push(extractDecalVector3(index + 1));
  47864. faceVertices.push(extractDecalVector3(index + 2));
  47865. // Clip
  47866. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47867. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47868. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47869. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47870. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47871. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47872. if (faceVertices.length === 0) {
  47873. continue;
  47874. }
  47875. // Add UVs and get back to world
  47876. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47877. var vertex = faceVertices[vIndex];
  47878. //TODO check for Int32Array | Uint32Array | Uint16Array
  47879. vertexData.indices.push(currentVertexDataIndex);
  47880. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47881. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47882. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47883. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47884. currentVertexDataIndex++;
  47885. }
  47886. }
  47887. // Return mesh
  47888. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47889. vertexData.applyToMesh(decal);
  47890. decal.position = position.clone();
  47891. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47892. return decal;
  47893. };
  47894. // Privates
  47895. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47896. // extrusion geometry
  47897. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47898. var tangents = path3D.getTangents();
  47899. var normals = path3D.getNormals();
  47900. var binormals = path3D.getBinormals();
  47901. var distances = path3D.getDistances();
  47902. var angle = 0;
  47903. var returnScale = function () { return scale !== null ? scale : 1; };
  47904. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47905. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47906. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47907. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47908. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47909. for (var i = 0; i < curve.length; i++) {
  47910. var shapePath = new Array();
  47911. var angleStep = rotate(i, distances[i]);
  47912. var scaleRatio = scl(i, distances[i]);
  47913. for (var p = 0; p < shape.length; p++) {
  47914. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47915. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47916. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47917. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47918. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47919. shapePath[p] = rotated;
  47920. }
  47921. shapePaths[index] = shapePath;
  47922. angle += angleStep;
  47923. index++;
  47924. }
  47925. // cap
  47926. var capPath = function (shapePath) {
  47927. var pointCap = Array();
  47928. var barycenter = BABYLON.Vector3.Zero();
  47929. var i;
  47930. for (i = 0; i < shapePath.length; i++) {
  47931. barycenter.addInPlace(shapePath[i]);
  47932. }
  47933. barycenter.scaleInPlace(1.0 / shapePath.length);
  47934. for (i = 0; i < shapePath.length; i++) {
  47935. pointCap.push(barycenter);
  47936. }
  47937. return pointCap;
  47938. };
  47939. switch (cap) {
  47940. case BABYLON.Mesh.NO_CAP:
  47941. break;
  47942. case BABYLON.Mesh.CAP_START:
  47943. shapePaths[0] = capPath(shapePaths[2]);
  47944. shapePaths[1] = shapePaths[2];
  47945. break;
  47946. case BABYLON.Mesh.CAP_END:
  47947. shapePaths[index] = shapePaths[index - 1];
  47948. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47949. break;
  47950. case BABYLON.Mesh.CAP_ALL:
  47951. shapePaths[0] = capPath(shapePaths[2]);
  47952. shapePaths[1] = shapePaths[2];
  47953. shapePaths[index] = shapePaths[index - 1];
  47954. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47955. break;
  47956. default:
  47957. break;
  47958. }
  47959. return shapePaths;
  47960. };
  47961. var path3D;
  47962. var pathArray;
  47963. if (instance) {
  47964. path3D = (instance.path3D).update(curve);
  47965. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47966. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  47967. return instance;
  47968. }
  47969. // extruded shape creation
  47970. path3D = new BABYLON.Path3D(curve);
  47971. var newShapePaths = new Array();
  47972. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47973. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47974. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  47975. extrudedGeneric.pathArray = pathArray;
  47976. extrudedGeneric.path3D = path3D;
  47977. extrudedGeneric.cap = cap;
  47978. return extrudedGeneric;
  47979. };
  47980. return MeshBuilder;
  47981. }());
  47982. BABYLON.MeshBuilder = MeshBuilder;
  47983. })(BABYLON || (BABYLON = {}));
  47984. //# sourceMappingURL=babylon.meshBuilder.js.map
  47985. var BABYLON;
  47986. (function (BABYLON) {
  47987. var AudioEngine = /** @class */ (function () {
  47988. function AudioEngine() {
  47989. this._audioContext = null;
  47990. this._audioContextInitialized = false;
  47991. this.canUseWebAudio = false;
  47992. this.WarnedWebAudioUnsupported = false;
  47993. this.unlocked = false;
  47994. this.isMP3supported = false;
  47995. this.isOGGsupported = false;
  47996. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47997. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47998. this.canUseWebAudio = true;
  47999. }
  48000. var audioElem = document.createElement('audio');
  48001. try {
  48002. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48003. this.isMP3supported = true;
  48004. }
  48005. }
  48006. catch (e) {
  48007. // protect error during capability check.
  48008. }
  48009. try {
  48010. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48011. this.isOGGsupported = true;
  48012. }
  48013. }
  48014. catch (e) {
  48015. // protect error during capability check.
  48016. }
  48017. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48018. this._unlockiOSaudio();
  48019. }
  48020. else {
  48021. this.unlocked = true;
  48022. }
  48023. }
  48024. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48025. get: function () {
  48026. if (!this._audioContextInitialized) {
  48027. this._initializeAudioContext();
  48028. }
  48029. return this._audioContext;
  48030. },
  48031. enumerable: true,
  48032. configurable: true
  48033. });
  48034. AudioEngine.prototype._unlockiOSaudio = function () {
  48035. var _this = this;
  48036. var unlockaudio = function () {
  48037. if (!_this.audioContext) {
  48038. return;
  48039. }
  48040. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48041. var source = _this.audioContext.createBufferSource();
  48042. source.buffer = buffer;
  48043. source.connect(_this.audioContext.destination);
  48044. source.start(0);
  48045. setTimeout(function () {
  48046. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48047. _this.unlocked = true;
  48048. window.removeEventListener('touchend', unlockaudio, false);
  48049. if (_this.onAudioUnlocked) {
  48050. _this.onAudioUnlocked();
  48051. }
  48052. }
  48053. }, 0);
  48054. };
  48055. window.addEventListener('touchend', unlockaudio, false);
  48056. };
  48057. AudioEngine.prototype._initializeAudioContext = function () {
  48058. try {
  48059. if (this.canUseWebAudio) {
  48060. this._audioContext = new AudioContext();
  48061. // create a global volume gain node
  48062. this.masterGain = this._audioContext.createGain();
  48063. this.masterGain.gain.value = 1;
  48064. this.masterGain.connect(this._audioContext.destination);
  48065. this._audioContextInitialized = true;
  48066. }
  48067. }
  48068. catch (e) {
  48069. this.canUseWebAudio = false;
  48070. BABYLON.Tools.Error("Web Audio: " + e.message);
  48071. }
  48072. };
  48073. AudioEngine.prototype.dispose = function () {
  48074. if (this.canUseWebAudio && this._audioContextInitialized) {
  48075. if (this._connectedAnalyser && this._audioContext) {
  48076. this._connectedAnalyser.stopDebugCanvas();
  48077. this._connectedAnalyser.dispose();
  48078. this.masterGain.disconnect();
  48079. this.masterGain.connect(this._audioContext.destination);
  48080. this._connectedAnalyser = null;
  48081. }
  48082. this.masterGain.gain.value = 1;
  48083. }
  48084. this.WarnedWebAudioUnsupported = false;
  48085. };
  48086. AudioEngine.prototype.getGlobalVolume = function () {
  48087. if (this.canUseWebAudio && this._audioContextInitialized) {
  48088. return this.masterGain.gain.value;
  48089. }
  48090. else {
  48091. return -1;
  48092. }
  48093. };
  48094. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48095. if (this.canUseWebAudio && this._audioContextInitialized) {
  48096. this.masterGain.gain.value = newVolume;
  48097. }
  48098. };
  48099. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48100. if (this._connectedAnalyser) {
  48101. this._connectedAnalyser.stopDebugCanvas();
  48102. }
  48103. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48104. this._connectedAnalyser = analyser;
  48105. this.masterGain.disconnect();
  48106. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48107. }
  48108. };
  48109. return AudioEngine;
  48110. }());
  48111. BABYLON.AudioEngine = AudioEngine;
  48112. })(BABYLON || (BABYLON = {}));
  48113. //# sourceMappingURL=babylon.audioEngine.js.map
  48114. var BABYLON;
  48115. (function (BABYLON) {
  48116. var Sound = /** @class */ (function () {
  48117. /**
  48118. * Create a sound and attach it to a scene
  48119. * @param name Name of your sound
  48120. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48121. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48122. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48123. */
  48124. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48125. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48126. var _this = this;
  48127. this.autoplay = false;
  48128. this.loop = false;
  48129. this.useCustomAttenuation = false;
  48130. this.spatialSound = false;
  48131. this.refDistance = 1;
  48132. this.rolloffFactor = 1;
  48133. this.maxDistance = 100;
  48134. this.distanceModel = "linear";
  48135. this._panningModel = "equalpower";
  48136. this._playbackRate = 1;
  48137. this._streaming = false;
  48138. this._startTime = 0;
  48139. this._startOffset = 0;
  48140. this._position = BABYLON.Vector3.Zero();
  48141. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48142. this._volume = 1;
  48143. this._isLoaded = false;
  48144. this._isReadyToPlay = false;
  48145. this.isPlaying = false;
  48146. this.isPaused = false;
  48147. this._isDirectional = false;
  48148. // Used if you'd like to create a directional sound.
  48149. // If not set, the sound will be omnidirectional
  48150. this._coneInnerAngle = 360;
  48151. this._coneOuterAngle = 360;
  48152. this._coneOuterGain = 0;
  48153. this._isOutputConnected = false;
  48154. this._urlType = "Unknown";
  48155. this.name = name;
  48156. this._scene = scene;
  48157. this._readyToPlayCallback = readyToPlayCallback;
  48158. // Default custom attenuation function is a linear attenuation
  48159. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48160. if (currentDistance < maxDistance) {
  48161. return currentVolume * (1 - currentDistance / maxDistance);
  48162. }
  48163. else {
  48164. return 0;
  48165. }
  48166. };
  48167. if (options) {
  48168. this.autoplay = options.autoplay || false;
  48169. this.loop = options.loop || false;
  48170. // if volume === 0, we need another way to check this option
  48171. if (options.volume !== undefined) {
  48172. this._volume = options.volume;
  48173. }
  48174. this.spatialSound = options.spatialSound || false;
  48175. this.maxDistance = options.maxDistance || 100;
  48176. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48177. this.rolloffFactor = options.rolloffFactor || 1;
  48178. this.refDistance = options.refDistance || 1;
  48179. this.distanceModel = options.distanceModel || "linear";
  48180. this._playbackRate = options.playbackRate || 1;
  48181. this._streaming = options.streaming || false;
  48182. }
  48183. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48184. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48185. this._soundGain.gain.value = this._volume;
  48186. this._inputAudioNode = this._soundGain;
  48187. this._ouputAudioNode = this._soundGain;
  48188. if (this.spatialSound) {
  48189. this._createSpatialParameters();
  48190. }
  48191. this._scene.mainSoundTrack.AddSound(this);
  48192. var validParameter = true;
  48193. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48194. if (urlOrArrayBuffer) {
  48195. if (typeof (urlOrArrayBuffer) === "string")
  48196. this._urlType = "String";
  48197. if (Array.isArray(urlOrArrayBuffer))
  48198. this._urlType = "Array";
  48199. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48200. this._urlType = "ArrayBuffer";
  48201. var urls = [];
  48202. var codecSupportedFound = false;
  48203. switch (this._urlType) {
  48204. case "ArrayBuffer":
  48205. if (urlOrArrayBuffer.byteLength > 0) {
  48206. codecSupportedFound = true;
  48207. this._soundLoaded(urlOrArrayBuffer);
  48208. }
  48209. break;
  48210. case "String":
  48211. urls.push(urlOrArrayBuffer);
  48212. case "Array":
  48213. if (urls.length === 0)
  48214. urls = urlOrArrayBuffer;
  48215. // If we found a supported format, we load it immediately and stop the loop
  48216. for (var i = 0; i < urls.length; i++) {
  48217. var url = urls[i];
  48218. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48219. codecSupportedFound = true;
  48220. }
  48221. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48222. codecSupportedFound = true;
  48223. }
  48224. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48225. codecSupportedFound = true;
  48226. }
  48227. if (url.indexOf("blob:") !== -1) {
  48228. codecSupportedFound = true;
  48229. }
  48230. if (codecSupportedFound) {
  48231. // Loading sound using XHR2
  48232. if (!this._streaming) {
  48233. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48234. }
  48235. else {
  48236. this._htmlAudioElement = new Audio(url);
  48237. this._htmlAudioElement.controls = false;
  48238. this._htmlAudioElement.loop = this.loop;
  48239. this._htmlAudioElement.crossOrigin = "anonymous";
  48240. this._htmlAudioElement.preload = "auto";
  48241. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48242. _this._isReadyToPlay = true;
  48243. if (_this.autoplay) {
  48244. _this.play();
  48245. }
  48246. if (_this._readyToPlayCallback) {
  48247. _this._readyToPlayCallback();
  48248. }
  48249. });
  48250. document.body.appendChild(this._htmlAudioElement);
  48251. }
  48252. break;
  48253. }
  48254. }
  48255. break;
  48256. default:
  48257. validParameter = false;
  48258. break;
  48259. }
  48260. if (!validParameter) {
  48261. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48262. }
  48263. else {
  48264. if (!codecSupportedFound) {
  48265. this._isReadyToPlay = true;
  48266. // Simulating a ready to play event to avoid breaking code path
  48267. if (this._readyToPlayCallback) {
  48268. window.setTimeout(function () {
  48269. if (_this._readyToPlayCallback) {
  48270. _this._readyToPlayCallback();
  48271. }
  48272. }, 1000);
  48273. }
  48274. }
  48275. }
  48276. }
  48277. }
  48278. else {
  48279. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48280. this._scene.mainSoundTrack.AddSound(this);
  48281. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48282. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48283. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48284. }
  48285. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48286. if (this._readyToPlayCallback) {
  48287. window.setTimeout(function () {
  48288. if (_this._readyToPlayCallback) {
  48289. _this._readyToPlayCallback();
  48290. }
  48291. }, 1000);
  48292. }
  48293. }
  48294. }
  48295. Sound.prototype.dispose = function () {
  48296. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48297. if (this.isPlaying) {
  48298. this.stop();
  48299. }
  48300. this._isReadyToPlay = false;
  48301. if (this.soundTrackId === -1) {
  48302. this._scene.mainSoundTrack.RemoveSound(this);
  48303. }
  48304. else {
  48305. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48306. }
  48307. if (this._soundGain) {
  48308. this._soundGain.disconnect();
  48309. this._soundGain = null;
  48310. }
  48311. if (this._soundPanner) {
  48312. this._soundPanner.disconnect();
  48313. this._soundPanner = null;
  48314. }
  48315. if (this._soundSource) {
  48316. this._soundSource.disconnect();
  48317. this._soundSource = null;
  48318. }
  48319. this._audioBuffer = null;
  48320. if (this._htmlAudioElement) {
  48321. this._htmlAudioElement.pause();
  48322. this._htmlAudioElement.src = "";
  48323. document.body.removeChild(this._htmlAudioElement);
  48324. }
  48325. if (this._connectedMesh && this._registerFunc) {
  48326. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48327. this._connectedMesh = null;
  48328. }
  48329. }
  48330. };
  48331. Sound.prototype.isReady = function () {
  48332. return this._isReadyToPlay;
  48333. };
  48334. Sound.prototype._soundLoaded = function (audioData) {
  48335. var _this = this;
  48336. this._isLoaded = true;
  48337. if (!BABYLON.Engine.audioEngine.audioContext) {
  48338. return;
  48339. }
  48340. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48341. _this._audioBuffer = buffer;
  48342. _this._isReadyToPlay = true;
  48343. if (_this.autoplay) {
  48344. _this.play();
  48345. }
  48346. if (_this._readyToPlayCallback) {
  48347. _this._readyToPlayCallback();
  48348. }
  48349. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48350. };
  48351. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48353. this._audioBuffer = audioBuffer;
  48354. this._isReadyToPlay = true;
  48355. }
  48356. };
  48357. Sound.prototype.updateOptions = function (options) {
  48358. if (options) {
  48359. this.loop = options.loop || this.loop;
  48360. this.maxDistance = options.maxDistance || this.maxDistance;
  48361. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48362. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48363. this.refDistance = options.refDistance || this.refDistance;
  48364. this.distanceModel = options.distanceModel || this.distanceModel;
  48365. this._playbackRate = options.playbackRate || this._playbackRate;
  48366. this._updateSpatialParameters();
  48367. if (this.isPlaying) {
  48368. if (this._streaming) {
  48369. this._htmlAudioElement.playbackRate = this._playbackRate;
  48370. }
  48371. else {
  48372. if (this._soundSource) {
  48373. this._soundSource.playbackRate.value = this._playbackRate;
  48374. }
  48375. }
  48376. }
  48377. }
  48378. };
  48379. Sound.prototype._createSpatialParameters = function () {
  48380. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48381. if (this._scene.headphone) {
  48382. this._panningModel = "HRTF";
  48383. }
  48384. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48385. this._updateSpatialParameters();
  48386. this._soundPanner.connect(this._ouputAudioNode);
  48387. this._inputAudioNode = this._soundPanner;
  48388. }
  48389. };
  48390. Sound.prototype._updateSpatialParameters = function () {
  48391. if (this.spatialSound && this._soundPanner) {
  48392. if (this.useCustomAttenuation) {
  48393. // Tricks to disable in a way embedded Web Audio attenuation
  48394. this._soundPanner.distanceModel = "linear";
  48395. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48396. this._soundPanner.refDistance = 1;
  48397. this._soundPanner.rolloffFactor = 1;
  48398. this._soundPanner.panningModel = this._panningModel;
  48399. }
  48400. else {
  48401. this._soundPanner.distanceModel = this.distanceModel;
  48402. this._soundPanner.maxDistance = this.maxDistance;
  48403. this._soundPanner.refDistance = this.refDistance;
  48404. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48405. this._soundPanner.panningModel = this._panningModel;
  48406. }
  48407. }
  48408. };
  48409. Sound.prototype.switchPanningModelToHRTF = function () {
  48410. this._panningModel = "HRTF";
  48411. this._switchPanningModel();
  48412. };
  48413. Sound.prototype.switchPanningModelToEqualPower = function () {
  48414. this._panningModel = "equalpower";
  48415. this._switchPanningModel();
  48416. };
  48417. Sound.prototype._switchPanningModel = function () {
  48418. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48419. this._soundPanner.panningModel = this._panningModel;
  48420. }
  48421. };
  48422. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48424. if (this._isOutputConnected) {
  48425. this._ouputAudioNode.disconnect();
  48426. }
  48427. this._ouputAudioNode.connect(soundTrackAudioNode);
  48428. this._isOutputConnected = true;
  48429. }
  48430. };
  48431. /**
  48432. * Transform this sound into a directional source
  48433. * @param coneInnerAngle Size of the inner cone in degree
  48434. * @param coneOuterAngle Size of the outer cone in degree
  48435. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48436. */
  48437. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48438. if (coneOuterAngle < coneInnerAngle) {
  48439. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48440. return;
  48441. }
  48442. this._coneInnerAngle = coneInnerAngle;
  48443. this._coneOuterAngle = coneOuterAngle;
  48444. this._coneOuterGain = coneOuterGain;
  48445. this._isDirectional = true;
  48446. if (this.isPlaying && this.loop) {
  48447. this.stop();
  48448. this.play();
  48449. }
  48450. };
  48451. Sound.prototype.setPosition = function (newPosition) {
  48452. this._position = newPosition;
  48453. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48454. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48455. }
  48456. };
  48457. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48458. this._localDirection = newLocalDirection;
  48459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48460. this._updateDirection();
  48461. }
  48462. };
  48463. Sound.prototype._updateDirection = function () {
  48464. if (!this._connectedMesh || !this._soundPanner) {
  48465. return;
  48466. }
  48467. var mat = this._connectedMesh.getWorldMatrix();
  48468. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48469. direction.normalize();
  48470. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48471. };
  48472. Sound.prototype.updateDistanceFromListener = function () {
  48473. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48474. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48475. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48476. }
  48477. };
  48478. Sound.prototype.setAttenuationFunction = function (callback) {
  48479. this._customAttenuationFunction = callback;
  48480. };
  48481. /**
  48482. * Play the sound
  48483. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48484. * @param offset (optional) Start the sound setting it at a specific time
  48485. */
  48486. Sound.prototype.play = function (time, offset) {
  48487. var _this = this;
  48488. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48489. try {
  48490. if (this._startOffset < 0) {
  48491. time = -this._startOffset;
  48492. this._startOffset = 0;
  48493. }
  48494. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48495. if (!this._soundSource || !this._streamingSource) {
  48496. if (this.spatialSound && this._soundPanner) {
  48497. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48498. if (this._isDirectional) {
  48499. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48500. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48501. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48502. if (this._connectedMesh) {
  48503. this._updateDirection();
  48504. }
  48505. else {
  48506. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48507. }
  48508. }
  48509. }
  48510. }
  48511. if (this._streaming) {
  48512. if (!this._streamingSource) {
  48513. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48514. this._htmlAudioElement.onended = function () { _this._onended(); };
  48515. this._htmlAudioElement.playbackRate = this._playbackRate;
  48516. }
  48517. this._streamingSource.disconnect();
  48518. this._streamingSource.connect(this._inputAudioNode);
  48519. this._htmlAudioElement.play();
  48520. }
  48521. else {
  48522. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48523. this._soundSource.buffer = this._audioBuffer;
  48524. this._soundSource.connect(this._inputAudioNode);
  48525. this._soundSource.loop = this.loop;
  48526. this._soundSource.playbackRate.value = this._playbackRate;
  48527. this._soundSource.onended = function () { _this._onended(); };
  48528. if (this._soundSource.buffer) {
  48529. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48530. }
  48531. }
  48532. this._startTime = startTime;
  48533. this.isPlaying = true;
  48534. this.isPaused = false;
  48535. }
  48536. catch (ex) {
  48537. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48538. }
  48539. }
  48540. };
  48541. Sound.prototype._onended = function () {
  48542. this.isPlaying = false;
  48543. if (this.onended) {
  48544. this.onended();
  48545. }
  48546. };
  48547. /**
  48548. * Stop the sound
  48549. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48550. */
  48551. Sound.prototype.stop = function (time) {
  48552. if (this.isPlaying) {
  48553. if (this._streaming) {
  48554. this._htmlAudioElement.pause();
  48555. // Test needed for Firefox or it will generate an Invalid State Error
  48556. if (this._htmlAudioElement.currentTime > 0) {
  48557. this._htmlAudioElement.currentTime = 0;
  48558. }
  48559. }
  48560. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48561. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48562. this._soundSource.stop(stopTime);
  48563. this._soundSource.onended = function () { };
  48564. if (!this.isPaused) {
  48565. this._startOffset = 0;
  48566. }
  48567. }
  48568. this.isPlaying = false;
  48569. }
  48570. };
  48571. Sound.prototype.pause = function () {
  48572. if (this.isPlaying) {
  48573. this.isPaused = true;
  48574. if (this._streaming) {
  48575. this._htmlAudioElement.pause();
  48576. }
  48577. else if (BABYLON.Engine.audioEngine.audioContext) {
  48578. this.stop(0);
  48579. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48580. }
  48581. }
  48582. };
  48583. Sound.prototype.setVolume = function (newVolume, time) {
  48584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48585. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48586. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48587. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48588. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48589. }
  48590. else {
  48591. this._soundGain.gain.value = newVolume;
  48592. }
  48593. }
  48594. this._volume = newVolume;
  48595. };
  48596. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48597. this._playbackRate = newPlaybackRate;
  48598. if (this.isPlaying) {
  48599. if (this._streaming) {
  48600. this._htmlAudioElement.playbackRate = this._playbackRate;
  48601. }
  48602. else if (this._soundSource) {
  48603. this._soundSource.playbackRate.value = this._playbackRate;
  48604. }
  48605. }
  48606. };
  48607. Sound.prototype.getVolume = function () {
  48608. return this._volume;
  48609. };
  48610. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48611. var _this = this;
  48612. if (this._connectedMesh && this._registerFunc) {
  48613. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48614. this._registerFunc = null;
  48615. }
  48616. this._connectedMesh = meshToConnectTo;
  48617. if (!this.spatialSound) {
  48618. this.spatialSound = true;
  48619. this._createSpatialParameters();
  48620. if (this.isPlaying && this.loop) {
  48621. this.stop();
  48622. this.play();
  48623. }
  48624. }
  48625. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48626. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48627. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48628. };
  48629. Sound.prototype.detachFromMesh = function () {
  48630. if (this._connectedMesh && this._registerFunc) {
  48631. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48632. this._registerFunc = null;
  48633. this._connectedMesh = null;
  48634. }
  48635. };
  48636. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48637. var boundingInfo = connectedMesh.getBoundingInfo();
  48638. if (!boundingInfo) {
  48639. return;
  48640. }
  48641. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48642. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48643. this._updateDirection();
  48644. }
  48645. };
  48646. Sound.prototype.clone = function () {
  48647. var _this = this;
  48648. if (!this._streaming) {
  48649. var setBufferAndRun = function () {
  48650. if (_this._isReadyToPlay) {
  48651. clonedSound._audioBuffer = _this.getAudioBuffer();
  48652. clonedSound._isReadyToPlay = true;
  48653. if (clonedSound.autoplay) {
  48654. clonedSound.play();
  48655. }
  48656. }
  48657. else {
  48658. window.setTimeout(setBufferAndRun, 300);
  48659. }
  48660. };
  48661. var currentOptions = {
  48662. autoplay: this.autoplay, loop: this.loop,
  48663. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48664. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48665. refDistance: this.refDistance, distanceModel: this.distanceModel
  48666. };
  48667. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48668. if (this.useCustomAttenuation) {
  48669. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48670. }
  48671. clonedSound.setPosition(this._position);
  48672. clonedSound.setPlaybackRate(this._playbackRate);
  48673. setBufferAndRun();
  48674. return clonedSound;
  48675. }
  48676. else {
  48677. return null;
  48678. }
  48679. };
  48680. Sound.prototype.getAudioBuffer = function () {
  48681. return this._audioBuffer;
  48682. };
  48683. Sound.prototype.serialize = function () {
  48684. var serializationObject = {
  48685. name: this.name,
  48686. url: this.name,
  48687. autoplay: this.autoplay,
  48688. loop: this.loop,
  48689. volume: this._volume,
  48690. spatialSound: this.spatialSound,
  48691. maxDistance: this.maxDistance,
  48692. rolloffFactor: this.rolloffFactor,
  48693. refDistance: this.refDistance,
  48694. distanceModel: this.distanceModel,
  48695. playbackRate: this._playbackRate,
  48696. panningModel: this._panningModel,
  48697. soundTrackId: this.soundTrackId
  48698. };
  48699. if (this.spatialSound) {
  48700. if (this._connectedMesh)
  48701. serializationObject.connectedMeshId = this._connectedMesh.id;
  48702. serializationObject.position = this._position.asArray();
  48703. serializationObject.refDistance = this.refDistance;
  48704. serializationObject.distanceModel = this.distanceModel;
  48705. serializationObject.isDirectional = this._isDirectional;
  48706. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48707. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48708. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48709. serializationObject.coneOuterGain = this._coneOuterGain;
  48710. }
  48711. return serializationObject;
  48712. };
  48713. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48714. var soundName = parsedSound.name;
  48715. var soundUrl;
  48716. if (parsedSound.url) {
  48717. soundUrl = rootUrl + parsedSound.url;
  48718. }
  48719. else {
  48720. soundUrl = rootUrl + soundName;
  48721. }
  48722. var options = {
  48723. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48724. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48725. rolloffFactor: parsedSound.rolloffFactor,
  48726. refDistance: parsedSound.refDistance,
  48727. distanceModel: parsedSound.distanceModel,
  48728. playbackRate: parsedSound.playbackRate
  48729. };
  48730. var newSound;
  48731. if (!sourceSound) {
  48732. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48733. scene._addPendingData(newSound);
  48734. }
  48735. else {
  48736. var setBufferAndRun = function () {
  48737. if (sourceSound._isReadyToPlay) {
  48738. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48739. newSound._isReadyToPlay = true;
  48740. if (newSound.autoplay) {
  48741. newSound.play();
  48742. }
  48743. }
  48744. else {
  48745. window.setTimeout(setBufferAndRun, 300);
  48746. }
  48747. };
  48748. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48749. setBufferAndRun();
  48750. }
  48751. if (parsedSound.position) {
  48752. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48753. newSound.setPosition(soundPosition);
  48754. }
  48755. if (parsedSound.isDirectional) {
  48756. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48757. if (parsedSound.localDirectionToMesh) {
  48758. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48759. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48760. }
  48761. }
  48762. if (parsedSound.connectedMeshId) {
  48763. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48764. if (connectedMesh) {
  48765. newSound.attachToMesh(connectedMesh);
  48766. }
  48767. }
  48768. return newSound;
  48769. };
  48770. return Sound;
  48771. }());
  48772. BABYLON.Sound = Sound;
  48773. })(BABYLON || (BABYLON = {}));
  48774. //# sourceMappingURL=babylon.sound.js.map
  48775. var BABYLON;
  48776. (function (BABYLON) {
  48777. var SoundTrack = /** @class */ (function () {
  48778. function SoundTrack(scene, options) {
  48779. this.id = -1;
  48780. this._isMainTrack = false;
  48781. this._isInitialized = false;
  48782. this._scene = scene;
  48783. this.soundCollection = new Array();
  48784. this._options = options;
  48785. if (!this._isMainTrack) {
  48786. this._scene.soundTracks.push(this);
  48787. this.id = this._scene.soundTracks.length - 1;
  48788. }
  48789. }
  48790. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48791. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48792. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48793. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48794. if (this._options) {
  48795. if (this._options.volume) {
  48796. this._outputAudioNode.gain.value = this._options.volume;
  48797. }
  48798. if (this._options.mainTrack) {
  48799. this._isMainTrack = this._options.mainTrack;
  48800. }
  48801. }
  48802. this._isInitialized = true;
  48803. }
  48804. };
  48805. SoundTrack.prototype.dispose = function () {
  48806. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48807. if (this._connectedAnalyser) {
  48808. this._connectedAnalyser.stopDebugCanvas();
  48809. }
  48810. while (this.soundCollection.length) {
  48811. this.soundCollection[0].dispose();
  48812. }
  48813. if (this._outputAudioNode) {
  48814. this._outputAudioNode.disconnect();
  48815. }
  48816. this._outputAudioNode = null;
  48817. }
  48818. };
  48819. SoundTrack.prototype.AddSound = function (sound) {
  48820. if (!this._isInitialized) {
  48821. this._initializeSoundTrackAudioGraph();
  48822. }
  48823. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48824. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48825. }
  48826. if (sound.soundTrackId) {
  48827. if (sound.soundTrackId === -1) {
  48828. this._scene.mainSoundTrack.RemoveSound(sound);
  48829. }
  48830. else {
  48831. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48832. }
  48833. }
  48834. this.soundCollection.push(sound);
  48835. sound.soundTrackId = this.id;
  48836. };
  48837. SoundTrack.prototype.RemoveSound = function (sound) {
  48838. var index = this.soundCollection.indexOf(sound);
  48839. if (index !== -1) {
  48840. this.soundCollection.splice(index, 1);
  48841. }
  48842. };
  48843. SoundTrack.prototype.setVolume = function (newVolume) {
  48844. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48845. this._outputAudioNode.gain.value = newVolume;
  48846. }
  48847. };
  48848. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48850. for (var i = 0; i < this.soundCollection.length; i++) {
  48851. this.soundCollection[i].switchPanningModelToHRTF();
  48852. }
  48853. }
  48854. };
  48855. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48856. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48857. for (var i = 0; i < this.soundCollection.length; i++) {
  48858. this.soundCollection[i].switchPanningModelToEqualPower();
  48859. }
  48860. }
  48861. };
  48862. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48863. if (this._connectedAnalyser) {
  48864. this._connectedAnalyser.stopDebugCanvas();
  48865. }
  48866. this._connectedAnalyser = analyser;
  48867. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48868. this._outputAudioNode.disconnect();
  48869. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48870. }
  48871. };
  48872. return SoundTrack;
  48873. }());
  48874. BABYLON.SoundTrack = SoundTrack;
  48875. })(BABYLON || (BABYLON = {}));
  48876. //# sourceMappingURL=babylon.soundtrack.js.map
  48877. var BABYLON;
  48878. (function (BABYLON) {
  48879. var Analyser = /** @class */ (function () {
  48880. function Analyser(scene) {
  48881. this.SMOOTHING = 0.75;
  48882. this.FFT_SIZE = 512;
  48883. this.BARGRAPHAMPLITUDE = 256;
  48884. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48885. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48886. this._scene = scene;
  48887. this._audioEngine = BABYLON.Engine.audioEngine;
  48888. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48889. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48890. this._webAudioAnalyser.minDecibels = -140;
  48891. this._webAudioAnalyser.maxDecibels = 0;
  48892. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48893. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48894. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48895. }
  48896. }
  48897. Analyser.prototype.getFrequencyBinCount = function () {
  48898. if (this._audioEngine.canUseWebAudio) {
  48899. return this._webAudioAnalyser.frequencyBinCount;
  48900. }
  48901. else {
  48902. return 0;
  48903. }
  48904. };
  48905. Analyser.prototype.getByteFrequencyData = function () {
  48906. if (this._audioEngine.canUseWebAudio) {
  48907. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48908. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48909. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48910. }
  48911. return this._byteFreqs;
  48912. };
  48913. Analyser.prototype.getByteTimeDomainData = function () {
  48914. if (this._audioEngine.canUseWebAudio) {
  48915. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48916. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48917. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48918. }
  48919. return this._byteTime;
  48920. };
  48921. Analyser.prototype.getFloatFrequencyData = function () {
  48922. if (this._audioEngine.canUseWebAudio) {
  48923. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48924. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48925. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48926. }
  48927. return this._floatFreqs;
  48928. };
  48929. Analyser.prototype.drawDebugCanvas = function () {
  48930. var _this = this;
  48931. if (this._audioEngine.canUseWebAudio) {
  48932. if (!this._debugCanvas) {
  48933. this._debugCanvas = document.createElement("canvas");
  48934. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48935. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48936. this._debugCanvas.style.position = "absolute";
  48937. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48938. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48939. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48940. document.body.appendChild(this._debugCanvas);
  48941. this._registerFunc = function () {
  48942. _this.drawDebugCanvas();
  48943. };
  48944. this._scene.registerBeforeRender(this._registerFunc);
  48945. }
  48946. if (this._registerFunc && this._debugCanvasContext) {
  48947. var workingArray = this.getByteFrequencyData();
  48948. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48949. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48950. // Draw the frequency domain chart.
  48951. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48952. var value = workingArray[i];
  48953. var percent = value / this.BARGRAPHAMPLITUDE;
  48954. var height = this.DEBUGCANVASSIZE.height * percent;
  48955. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48956. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48957. var hue = i / this.getFrequencyBinCount() * 360;
  48958. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48959. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48960. }
  48961. }
  48962. }
  48963. };
  48964. Analyser.prototype.stopDebugCanvas = function () {
  48965. if (this._debugCanvas) {
  48966. if (this._registerFunc) {
  48967. this._scene.unregisterBeforeRender(this._registerFunc);
  48968. this._registerFunc = null;
  48969. }
  48970. document.body.removeChild(this._debugCanvas);
  48971. this._debugCanvas = null;
  48972. this._debugCanvasContext = null;
  48973. }
  48974. };
  48975. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48976. if (this._audioEngine.canUseWebAudio) {
  48977. inputAudioNode.connect(this._webAudioAnalyser);
  48978. this._webAudioAnalyser.connect(outputAudioNode);
  48979. }
  48980. };
  48981. Analyser.prototype.dispose = function () {
  48982. if (this._audioEngine.canUseWebAudio) {
  48983. this._webAudioAnalyser.disconnect();
  48984. }
  48985. };
  48986. return Analyser;
  48987. }());
  48988. BABYLON.Analyser = Analyser;
  48989. })(BABYLON || (BABYLON = {}));
  48990. //# sourceMappingURL=babylon.analyser.js.map
  48991. var BABYLON;
  48992. (function (BABYLON) {
  48993. var CubeTexture = /** @class */ (function (_super) {
  48994. __extends(CubeTexture, _super);
  48995. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48996. if (extensions === void 0) { extensions = null; }
  48997. if (noMipmap === void 0) { noMipmap = false; }
  48998. if (files === void 0) { files = null; }
  48999. if (onLoad === void 0) { onLoad = null; }
  49000. if (onError === void 0) { onError = null; }
  49001. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49002. if (prefiltered === void 0) { prefiltered = false; }
  49003. if (forcedExtension === void 0) { forcedExtension = null; }
  49004. var _this = _super.call(this, scene) || this;
  49005. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49006. _this.name = rootUrl;
  49007. _this.url = rootUrl;
  49008. _this._noMipmap = noMipmap;
  49009. _this.hasAlpha = false;
  49010. _this._format = format;
  49011. _this._prefiltered = prefiltered;
  49012. _this.isCube = true;
  49013. _this._textureMatrix = BABYLON.Matrix.Identity();
  49014. if (prefiltered) {
  49015. _this.gammaSpace = false;
  49016. }
  49017. if (!rootUrl && !files) {
  49018. return _this;
  49019. }
  49020. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49021. if (!files) {
  49022. if (!extensions) {
  49023. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49024. }
  49025. files = [];
  49026. for (var index = 0; index < extensions.length; index++) {
  49027. files.push(rootUrl + extensions[index]);
  49028. }
  49029. _this._extensions = extensions;
  49030. }
  49031. _this._files = files;
  49032. if (!_this._texture) {
  49033. if (!scene.useDelayedTextureLoading) {
  49034. if (prefiltered) {
  49035. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49036. }
  49037. else {
  49038. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49039. }
  49040. }
  49041. else {
  49042. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49043. }
  49044. }
  49045. else if (onLoad) {
  49046. if (_this._texture.isReady) {
  49047. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49048. }
  49049. else {
  49050. _this._texture.onLoadedObservable.add(onLoad);
  49051. }
  49052. }
  49053. return _this;
  49054. }
  49055. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49056. return new CubeTexture("", scene, null, noMipmap, files);
  49057. };
  49058. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49059. if (forcedExtension === void 0) { forcedExtension = null; }
  49060. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49061. };
  49062. // Methods
  49063. CubeTexture.prototype.delayLoad = function () {
  49064. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49065. return;
  49066. }
  49067. var scene = this.getScene();
  49068. if (!scene) {
  49069. return;
  49070. }
  49071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49072. this._texture = this._getFromCache(this.url, this._noMipmap);
  49073. if (!this._texture) {
  49074. if (this._prefiltered) {
  49075. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49076. }
  49077. else {
  49078. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49079. }
  49080. }
  49081. };
  49082. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49083. return this._textureMatrix;
  49084. };
  49085. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49086. this._textureMatrix = value;
  49087. };
  49088. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49089. var texture = BABYLON.SerializationHelper.Parse(function () {
  49090. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49091. }, parsedTexture, scene);
  49092. // Animations
  49093. if (parsedTexture.animations) {
  49094. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49095. var parsedAnimation = parsedTexture.animations[animationIndex];
  49096. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49097. }
  49098. }
  49099. return texture;
  49100. };
  49101. CubeTexture.prototype.clone = function () {
  49102. var _this = this;
  49103. return BABYLON.SerializationHelper.Clone(function () {
  49104. var scene = _this.getScene();
  49105. if (!scene) {
  49106. return _this;
  49107. }
  49108. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49109. }, this);
  49110. };
  49111. return CubeTexture;
  49112. }(BABYLON.BaseTexture));
  49113. BABYLON.CubeTexture = CubeTexture;
  49114. })(BABYLON || (BABYLON = {}));
  49115. //# sourceMappingURL=babylon.cubeTexture.js.map
  49116. var BABYLON;
  49117. (function (BABYLON) {
  49118. var RenderTargetTexture = /** @class */ (function (_super) {
  49119. __extends(RenderTargetTexture, _super);
  49120. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49121. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49122. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49123. if (isCube === void 0) { isCube = false; }
  49124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49125. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49126. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49127. if (isMulti === void 0) { isMulti = false; }
  49128. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49129. _this.isCube = isCube;
  49130. /**
  49131. * Use this list to define the list of mesh you want to render.
  49132. */
  49133. _this.renderList = new Array();
  49134. _this.renderParticles = true;
  49135. _this.renderSprites = false;
  49136. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49137. _this.ignoreCameraViewport = false;
  49138. // Events
  49139. /**
  49140. * An event triggered when the texture is unbind.
  49141. * @type {BABYLON.Observable}
  49142. */
  49143. _this.onBeforeBindObservable = new BABYLON.Observable();
  49144. /**
  49145. * An event triggered when the texture is unbind.
  49146. * @type {BABYLON.Observable}
  49147. */
  49148. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49149. /**
  49150. * An event triggered before rendering the texture
  49151. * @type {BABYLON.Observable}
  49152. */
  49153. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49154. /**
  49155. * An event triggered after rendering the texture
  49156. * @type {BABYLON.Observable}
  49157. */
  49158. _this.onAfterRenderObservable = new BABYLON.Observable();
  49159. /**
  49160. * An event triggered after the texture clear
  49161. * @type {BABYLON.Observable}
  49162. */
  49163. _this.onClearObservable = new BABYLON.Observable();
  49164. _this._currentRefreshId = -1;
  49165. _this._refreshRate = 1;
  49166. _this._samples = 1;
  49167. scene = _this.getScene();
  49168. if (!scene) {
  49169. return _this;
  49170. }
  49171. _this.name = name;
  49172. _this.isRenderTarget = true;
  49173. _this._size = size;
  49174. _this._generateMipMaps = generateMipMaps ? true : false;
  49175. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49176. // Rendering groups
  49177. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49178. if (isMulti) {
  49179. return _this;
  49180. }
  49181. _this._renderTargetOptions = {
  49182. generateMipMaps: generateMipMaps,
  49183. type: type,
  49184. samplingMode: samplingMode,
  49185. generateDepthBuffer: generateDepthBuffer,
  49186. generateStencilBuffer: generateStencilBuffer
  49187. };
  49188. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49189. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49190. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49191. }
  49192. if (isCube) {
  49193. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49194. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49195. _this._textureMatrix = BABYLON.Matrix.Identity();
  49196. }
  49197. else {
  49198. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49199. }
  49200. return _this;
  49201. }
  49202. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49203. get: function () {
  49204. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49205. },
  49206. enumerable: true,
  49207. configurable: true
  49208. });
  49209. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49210. get: function () {
  49211. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49217. get: function () {
  49218. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49219. },
  49220. enumerable: true,
  49221. configurable: true
  49222. });
  49223. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49224. set: function (callback) {
  49225. if (this._onAfterUnbindObserver) {
  49226. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49227. }
  49228. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49234. set: function (callback) {
  49235. if (this._onBeforeRenderObserver) {
  49236. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49237. }
  49238. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49244. set: function (callback) {
  49245. if (this._onAfterRenderObserver) {
  49246. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49247. }
  49248. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49249. },
  49250. enumerable: true,
  49251. configurable: true
  49252. });
  49253. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49254. set: function (callback) {
  49255. if (this._onClearObserver) {
  49256. this.onClearObservable.remove(this._onClearObserver);
  49257. }
  49258. this._onClearObserver = this.onClearObservable.add(callback);
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49264. get: function () {
  49265. return this._renderTargetOptions;
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49271. get: function () {
  49272. return this._samples;
  49273. },
  49274. set: function (value) {
  49275. if (this._samples === value) {
  49276. return;
  49277. }
  49278. var scene = this.getScene();
  49279. if (!scene) {
  49280. return;
  49281. }
  49282. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49283. },
  49284. enumerable: true,
  49285. configurable: true
  49286. });
  49287. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49288. this._currentRefreshId = -1;
  49289. };
  49290. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49291. get: function () {
  49292. return this._refreshRate;
  49293. },
  49294. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49295. set: function (value) {
  49296. this._refreshRate = value;
  49297. this.resetRefreshCounter();
  49298. },
  49299. enumerable: true,
  49300. configurable: true
  49301. });
  49302. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49303. if (!this._postProcessManager) {
  49304. var scene = this.getScene();
  49305. if (!scene) {
  49306. return;
  49307. }
  49308. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49309. this._postProcesses = new Array();
  49310. }
  49311. this._postProcesses.push(postProcess);
  49312. this._postProcesses[0].autoClear = false;
  49313. };
  49314. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49315. if (!this._postProcesses) {
  49316. return;
  49317. }
  49318. if (dispose) {
  49319. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49320. var postProcess = _a[_i];
  49321. postProcess.dispose();
  49322. }
  49323. }
  49324. this._postProcesses = [];
  49325. };
  49326. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49327. if (!this._postProcesses) {
  49328. return;
  49329. }
  49330. var index = this._postProcesses.indexOf(postProcess);
  49331. if (index === -1) {
  49332. return;
  49333. }
  49334. this._postProcesses.splice(index, 1);
  49335. if (this._postProcesses.length > 0) {
  49336. this._postProcesses[0].autoClear = false;
  49337. }
  49338. };
  49339. RenderTargetTexture.prototype._shouldRender = function () {
  49340. if (this._currentRefreshId === -1) {
  49341. this._currentRefreshId = 1;
  49342. return true;
  49343. }
  49344. if (this.refreshRate === this._currentRefreshId) {
  49345. this._currentRefreshId = 1;
  49346. return true;
  49347. }
  49348. this._currentRefreshId++;
  49349. return false;
  49350. };
  49351. RenderTargetTexture.prototype.getRenderSize = function () {
  49352. return this._size;
  49353. };
  49354. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49355. get: function () {
  49356. return true;
  49357. },
  49358. enumerable: true,
  49359. configurable: true
  49360. });
  49361. RenderTargetTexture.prototype.scale = function (ratio) {
  49362. var newSize = this._size * ratio;
  49363. this.resize(newSize);
  49364. };
  49365. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49366. if (this.isCube) {
  49367. return this._textureMatrix;
  49368. }
  49369. return _super.prototype.getReflectionTextureMatrix.call(this);
  49370. };
  49371. RenderTargetTexture.prototype.resize = function (size) {
  49372. this.releaseInternalTexture();
  49373. var scene = this.getScene();
  49374. if (!scene) {
  49375. return;
  49376. }
  49377. if (this.isCube) {
  49378. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49379. }
  49380. else {
  49381. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49382. }
  49383. this._size = size;
  49384. };
  49385. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49386. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49387. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49388. var scene = this.getScene();
  49389. if (!scene) {
  49390. return;
  49391. }
  49392. var engine = scene.getEngine();
  49393. if (this.useCameraPostProcesses !== undefined) {
  49394. useCameraPostProcess = this.useCameraPostProcesses;
  49395. }
  49396. if (this._waitingRenderList) {
  49397. this.renderList = [];
  49398. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49399. var id = this._waitingRenderList[index];
  49400. var mesh_1 = scene.getMeshByID(id);
  49401. if (mesh_1) {
  49402. this.renderList.push(mesh_1);
  49403. }
  49404. }
  49405. delete this._waitingRenderList;
  49406. }
  49407. // Is predicate defined?
  49408. if (this.renderListPredicate) {
  49409. if (this.renderList) {
  49410. this.renderList.splice(0); // Clear previous renderList
  49411. }
  49412. else {
  49413. this.renderList = [];
  49414. }
  49415. var scene = this.getScene();
  49416. if (!scene) {
  49417. return;
  49418. }
  49419. var sceneMeshes = scene.meshes;
  49420. for (var index = 0; index < sceneMeshes.length; index++) {
  49421. var mesh = sceneMeshes[index];
  49422. if (this.renderListPredicate(mesh)) {
  49423. this.renderList.push(mesh);
  49424. }
  49425. }
  49426. }
  49427. this.onBeforeBindObservable.notifyObservers(this);
  49428. // Set custom projection.
  49429. // Needs to be before binding to prevent changing the aspect ratio.
  49430. var camera;
  49431. if (this.activeCamera) {
  49432. camera = this.activeCamera;
  49433. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49434. if (this.activeCamera !== scene.activeCamera) {
  49435. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49436. }
  49437. }
  49438. else {
  49439. camera = scene.activeCamera;
  49440. if (camera) {
  49441. engine.setViewport(camera.viewport, this._size, this._size);
  49442. }
  49443. }
  49444. // Prepare renderingManager
  49445. this._renderingManager.reset();
  49446. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49447. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49448. var sceneRenderId = scene.getRenderId();
  49449. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49450. var mesh = currentRenderList[meshIndex];
  49451. if (mesh) {
  49452. if (!mesh.isReady()) {
  49453. // Reset _currentRefreshId
  49454. this.resetRefreshCounter();
  49455. continue;
  49456. }
  49457. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49458. var isMasked = void 0;
  49459. if (!this.renderList && camera) {
  49460. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49461. }
  49462. else {
  49463. isMasked = false;
  49464. }
  49465. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49466. mesh._activate(sceneRenderId);
  49467. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49468. var subMesh = mesh.subMeshes[subIndex];
  49469. scene._activeIndices.addCount(subMesh.indexCount, false);
  49470. this._renderingManager.dispatch(subMesh);
  49471. }
  49472. }
  49473. }
  49474. }
  49475. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49476. var particleSystem = scene.particleSystems[particleIndex];
  49477. var emitter = particleSystem.emitter;
  49478. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49479. continue;
  49480. }
  49481. if (currentRenderList.indexOf(emitter) >= 0) {
  49482. this._renderingManager.dispatchParticles(particleSystem);
  49483. }
  49484. }
  49485. if (this.isCube) {
  49486. for (var face = 0; face < 6; face++) {
  49487. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49488. scene.incrementRenderId();
  49489. scene.resetCachedMaterial();
  49490. }
  49491. }
  49492. else {
  49493. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49494. }
  49495. this.onAfterUnbindObservable.notifyObservers(this);
  49496. if (scene.activeCamera) {
  49497. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49498. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49499. }
  49500. engine.setViewport(scene.activeCamera.viewport);
  49501. }
  49502. scene.resetCachedMaterial();
  49503. };
  49504. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49505. var _this = this;
  49506. var scene = this.getScene();
  49507. if (!scene) {
  49508. return;
  49509. }
  49510. var engine = scene.getEngine();
  49511. if (!this._texture) {
  49512. return;
  49513. }
  49514. // Bind
  49515. if (this._postProcessManager) {
  49516. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49517. }
  49518. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49519. if (this._texture) {
  49520. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49521. }
  49522. }
  49523. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49524. // Clear
  49525. if (this.onClearObservable.hasObservers()) {
  49526. this.onClearObservable.notifyObservers(engine);
  49527. }
  49528. else {
  49529. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49530. }
  49531. if (!this._doNotChangeAspectRatio) {
  49532. scene.updateTransformMatrix(true);
  49533. }
  49534. // Render
  49535. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49536. if (this._postProcessManager) {
  49537. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49538. }
  49539. else if (useCameraPostProcess) {
  49540. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49541. }
  49542. if (!this._doNotChangeAspectRatio) {
  49543. scene.updateTransformMatrix(true);
  49544. }
  49545. // Dump ?
  49546. if (dumpForDebug) {
  49547. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49548. }
  49549. // Unbind
  49550. if (!this.isCube || faceIndex === 5) {
  49551. if (this.isCube) {
  49552. if (faceIndex === 5) {
  49553. engine.generateMipMapsForCubemap(this._texture);
  49554. }
  49555. }
  49556. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49557. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49558. });
  49559. }
  49560. else {
  49561. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49562. }
  49563. };
  49564. /**
  49565. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49566. * This allowed control for front to back rendering or reversly depending of the special needs.
  49567. *
  49568. * @param renderingGroupId The rendering group id corresponding to its index
  49569. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49570. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49571. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49572. */
  49573. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49574. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49575. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49576. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49577. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49578. };
  49579. /**
  49580. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49581. *
  49582. * @param renderingGroupId The rendering group id corresponding to its index
  49583. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49584. */
  49585. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49586. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49587. };
  49588. RenderTargetTexture.prototype.clone = function () {
  49589. var textureSize = this.getSize();
  49590. 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);
  49591. // Base texture
  49592. newTexture.hasAlpha = this.hasAlpha;
  49593. newTexture.level = this.level;
  49594. // RenderTarget Texture
  49595. newTexture.coordinatesMode = this.coordinatesMode;
  49596. if (this.renderList) {
  49597. newTexture.renderList = this.renderList.slice(0);
  49598. }
  49599. return newTexture;
  49600. };
  49601. RenderTargetTexture.prototype.serialize = function () {
  49602. if (!this.name) {
  49603. return null;
  49604. }
  49605. var serializationObject = _super.prototype.serialize.call(this);
  49606. serializationObject.renderTargetSize = this.getRenderSize();
  49607. serializationObject.renderList = [];
  49608. if (this.renderList) {
  49609. for (var index = 0; index < this.renderList.length; index++) {
  49610. serializationObject.renderList.push(this.renderList[index].id);
  49611. }
  49612. }
  49613. return serializationObject;
  49614. };
  49615. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49616. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49617. var objBuffer = this.getInternalTexture();
  49618. var scene = this.getScene();
  49619. if (objBuffer && scene) {
  49620. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49621. }
  49622. };
  49623. RenderTargetTexture.prototype.dispose = function () {
  49624. if (this._postProcessManager) {
  49625. this._postProcessManager.dispose();
  49626. this._postProcessManager = null;
  49627. }
  49628. this.clearPostProcesses(true);
  49629. this.renderList = null;
  49630. // Remove from custom render targets
  49631. var scene = this.getScene();
  49632. if (!scene) {
  49633. return;
  49634. }
  49635. var index = scene.customRenderTargets.indexOf(this);
  49636. if (index >= 0) {
  49637. scene.customRenderTargets.splice(index, 1);
  49638. }
  49639. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49640. var camera = _a[_i];
  49641. index = camera.customRenderTargets.indexOf(this);
  49642. if (index >= 0) {
  49643. camera.customRenderTargets.splice(index, 1);
  49644. }
  49645. }
  49646. _super.prototype.dispose.call(this);
  49647. };
  49648. RenderTargetTexture.prototype._rebuild = function () {
  49649. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49650. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49651. }
  49652. if (this._postProcessManager) {
  49653. this._postProcessManager._rebuild();
  49654. }
  49655. };
  49656. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49657. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49658. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49659. return RenderTargetTexture;
  49660. }(BABYLON.Texture));
  49661. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49662. })(BABYLON || (BABYLON = {}));
  49663. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49664. var BABYLON;
  49665. (function (BABYLON) {
  49666. ;
  49667. var MultiRenderTarget = /** @class */ (function (_super) {
  49668. __extends(MultiRenderTarget, _super);
  49669. function MultiRenderTarget(name, size, count, scene, options) {
  49670. var _this = this;
  49671. options = options || {};
  49672. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49673. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49674. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49675. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49676. _this._engine = scene.getEngine();
  49677. if (!_this.isSupported) {
  49678. _this.dispose();
  49679. return;
  49680. }
  49681. var types = [];
  49682. var samplingModes = [];
  49683. for (var i = 0; i < count; i++) {
  49684. if (options.types && options.types[i]) {
  49685. types.push(options.types[i]);
  49686. }
  49687. else {
  49688. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49689. }
  49690. if (options.samplingModes && options.samplingModes[i]) {
  49691. samplingModes.push(options.samplingModes[i]);
  49692. }
  49693. else {
  49694. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49695. }
  49696. }
  49697. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49698. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49699. _this._count = count;
  49700. _this._size = size;
  49701. _this._multiRenderTargetOptions = {
  49702. samplingModes: samplingModes,
  49703. generateMipMaps: generateMipMaps,
  49704. generateDepthBuffer: generateDepthBuffer,
  49705. generateStencilBuffer: generateStencilBuffer,
  49706. generateDepthTexture: generateDepthTexture,
  49707. types: types,
  49708. textureCount: count
  49709. };
  49710. _this._createInternalTextures();
  49711. _this._createTextures();
  49712. return _this;
  49713. }
  49714. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49715. get: function () {
  49716. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49717. },
  49718. enumerable: true,
  49719. configurable: true
  49720. });
  49721. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49722. get: function () {
  49723. return this._textures;
  49724. },
  49725. enumerable: true,
  49726. configurable: true
  49727. });
  49728. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49729. get: function () {
  49730. return this._textures[this._textures.length - 1];
  49731. },
  49732. enumerable: true,
  49733. configurable: true
  49734. });
  49735. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49736. set: function (wrap) {
  49737. if (this._textures) {
  49738. for (var i = 0; i < this._textures.length; i++) {
  49739. this._textures[i].wrapU = wrap;
  49740. }
  49741. }
  49742. },
  49743. enumerable: true,
  49744. configurable: true
  49745. });
  49746. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49747. set: function (wrap) {
  49748. if (this._textures) {
  49749. for (var i = 0; i < this._textures.length; i++) {
  49750. this._textures[i].wrapV = wrap;
  49751. }
  49752. }
  49753. },
  49754. enumerable: true,
  49755. configurable: true
  49756. });
  49757. MultiRenderTarget.prototype._rebuild = function () {
  49758. this.releaseInternalTextures();
  49759. this._createInternalTextures();
  49760. for (var i = 0; i < this._internalTextures.length; i++) {
  49761. var texture = this._textures[i];
  49762. texture._texture = this._internalTextures[i];
  49763. }
  49764. // Keeps references to frame buffer and stencil/depth buffer
  49765. this._texture = this._internalTextures[0];
  49766. };
  49767. MultiRenderTarget.prototype._createInternalTextures = function () {
  49768. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49769. };
  49770. MultiRenderTarget.prototype._createTextures = function () {
  49771. this._textures = [];
  49772. for (var i = 0; i < this._internalTextures.length; i++) {
  49773. var texture = new BABYLON.Texture(null, this.getScene());
  49774. texture._texture = this._internalTextures[i];
  49775. this._textures.push(texture);
  49776. }
  49777. // Keeps references to frame buffer and stencil/depth buffer
  49778. this._texture = this._internalTextures[0];
  49779. };
  49780. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49781. get: function () {
  49782. return this._samples;
  49783. },
  49784. set: function (value) {
  49785. if (this._samples === value) {
  49786. return;
  49787. }
  49788. for (var i = 0; i < this._internalTextures.length; i++) {
  49789. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49790. }
  49791. },
  49792. enumerable: true,
  49793. configurable: true
  49794. });
  49795. MultiRenderTarget.prototype.resize = function (size) {
  49796. this.releaseInternalTextures();
  49797. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49798. this._createInternalTextures();
  49799. };
  49800. MultiRenderTarget.prototype.dispose = function () {
  49801. this.releaseInternalTextures();
  49802. _super.prototype.dispose.call(this);
  49803. };
  49804. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49805. if (!this._internalTextures) {
  49806. return;
  49807. }
  49808. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49809. if (this._internalTextures[i] !== undefined) {
  49810. this._internalTextures[i].dispose();
  49811. this._internalTextures.splice(i, 1);
  49812. }
  49813. }
  49814. };
  49815. return MultiRenderTarget;
  49816. }(BABYLON.RenderTargetTexture));
  49817. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49818. })(BABYLON || (BABYLON = {}));
  49819. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49820. var BABYLON;
  49821. (function (BABYLON) {
  49822. var MirrorTexture = /** @class */ (function (_super) {
  49823. __extends(MirrorTexture, _super);
  49824. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49825. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49827. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49828. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49829. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49830. _this._transformMatrix = BABYLON.Matrix.Zero();
  49831. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49832. _this._blurKernelX = 0;
  49833. _this._blurKernelY = 0;
  49834. _this._blurRatio = 1.0;
  49835. _this.ignoreCameraViewport = true;
  49836. _this.onBeforeRenderObservable.add(function () {
  49837. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49838. _this._savedViewMatrix = scene.getViewMatrix();
  49839. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49840. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49841. scene.clipPlane = _this.mirrorPlane;
  49842. scene.getEngine().cullBackFaces = false;
  49843. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49844. });
  49845. _this.onAfterRenderObservable.add(function () {
  49846. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49847. scene.getEngine().cullBackFaces = true;
  49848. scene._mirroredCameraPosition = null;
  49849. delete scene.clipPlane;
  49850. });
  49851. return _this;
  49852. }
  49853. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49854. get: function () {
  49855. return this._blurRatio;
  49856. },
  49857. set: function (value) {
  49858. if (this._blurRatio === value) {
  49859. return;
  49860. }
  49861. this._blurRatio = value;
  49862. this._preparePostProcesses();
  49863. },
  49864. enumerable: true,
  49865. configurable: true
  49866. });
  49867. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49868. set: function (value) {
  49869. this.blurKernelX = value;
  49870. this.blurKernelY = value;
  49871. },
  49872. enumerable: true,
  49873. configurable: true
  49874. });
  49875. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49876. get: function () {
  49877. return this._blurKernelX;
  49878. },
  49879. set: function (value) {
  49880. if (this._blurKernelX === value) {
  49881. return;
  49882. }
  49883. this._blurKernelX = value;
  49884. this._preparePostProcesses();
  49885. },
  49886. enumerable: true,
  49887. configurable: true
  49888. });
  49889. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49890. get: function () {
  49891. return this._blurKernelY;
  49892. },
  49893. set: function (value) {
  49894. if (this._blurKernelY === value) {
  49895. return;
  49896. }
  49897. this._blurKernelY = value;
  49898. this._preparePostProcesses();
  49899. },
  49900. enumerable: true,
  49901. configurable: true
  49902. });
  49903. MirrorTexture.prototype._preparePostProcesses = function () {
  49904. this.clearPostProcesses(true);
  49905. if (this._blurKernelX && this._blurKernelY) {
  49906. var engine = this.getScene().getEngine();
  49907. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49908. 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);
  49909. this._blurX.autoClear = false;
  49910. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49911. this._blurX.outputTexture = this._texture;
  49912. }
  49913. else {
  49914. this._blurX.alwaysForcePOT = true;
  49915. }
  49916. 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);
  49917. this._blurY.autoClear = false;
  49918. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49919. this.addPostProcess(this._blurX);
  49920. this.addPostProcess(this._blurY);
  49921. }
  49922. };
  49923. MirrorTexture.prototype.clone = function () {
  49924. var scene = this.getScene();
  49925. if (!scene) {
  49926. return this;
  49927. }
  49928. var textureSize = this.getSize();
  49929. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49930. // Base texture
  49931. newTexture.hasAlpha = this.hasAlpha;
  49932. newTexture.level = this.level;
  49933. // Mirror Texture
  49934. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49935. if (this.renderList) {
  49936. newTexture.renderList = this.renderList.slice(0);
  49937. }
  49938. return newTexture;
  49939. };
  49940. MirrorTexture.prototype.serialize = function () {
  49941. if (!this.name) {
  49942. return null;
  49943. }
  49944. var serializationObject = _super.prototype.serialize.call(this);
  49945. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49946. return serializationObject;
  49947. };
  49948. return MirrorTexture;
  49949. }(BABYLON.RenderTargetTexture));
  49950. BABYLON.MirrorTexture = MirrorTexture;
  49951. })(BABYLON || (BABYLON = {}));
  49952. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49953. var BABYLON;
  49954. (function (BABYLON) {
  49955. /**
  49956. * Creates a refraction texture used by refraction channel of the standard material.
  49957. * @param name the texture name
  49958. * @param size size of the underlying texture
  49959. * @param scene root scene
  49960. */
  49961. var RefractionTexture = /** @class */ (function (_super) {
  49962. __extends(RefractionTexture, _super);
  49963. function RefractionTexture(name, size, scene, generateMipMaps) {
  49964. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49965. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49966. _this.depth = 2.0;
  49967. _this.onBeforeRenderObservable.add(function () {
  49968. scene.clipPlane = _this.refractionPlane;
  49969. });
  49970. _this.onAfterRenderObservable.add(function () {
  49971. delete scene.clipPlane;
  49972. });
  49973. return _this;
  49974. }
  49975. RefractionTexture.prototype.clone = function () {
  49976. var scene = this.getScene();
  49977. if (!scene) {
  49978. return this;
  49979. }
  49980. var textureSize = this.getSize();
  49981. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  49982. // Base texture
  49983. newTexture.hasAlpha = this.hasAlpha;
  49984. newTexture.level = this.level;
  49985. // Refraction Texture
  49986. newTexture.refractionPlane = this.refractionPlane.clone();
  49987. if (this.renderList) {
  49988. newTexture.renderList = this.renderList.slice(0);
  49989. }
  49990. newTexture.depth = this.depth;
  49991. return newTexture;
  49992. };
  49993. RefractionTexture.prototype.serialize = function () {
  49994. if (!this.name) {
  49995. return null;
  49996. }
  49997. var serializationObject = _super.prototype.serialize.call(this);
  49998. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49999. serializationObject.depth = this.depth;
  50000. return serializationObject;
  50001. };
  50002. return RefractionTexture;
  50003. }(BABYLON.RenderTargetTexture));
  50004. BABYLON.RefractionTexture = RefractionTexture;
  50005. })(BABYLON || (BABYLON = {}));
  50006. //# sourceMappingURL=babylon.refractionTexture.js.map
  50007. var BABYLON;
  50008. (function (BABYLON) {
  50009. var DynamicTexture = /** @class */ (function (_super) {
  50010. __extends(DynamicTexture, _super);
  50011. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50012. if (scene === void 0) { scene = null; }
  50013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50014. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50015. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50016. _this.name = name;
  50017. _this._engine = _this.getScene().getEngine();
  50018. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50019. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50020. _this._generateMipMaps = generateMipMaps;
  50021. if (options.getContext) {
  50022. _this._canvas = options;
  50023. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50024. }
  50025. else {
  50026. _this._canvas = document.createElement("canvas");
  50027. if (options.width) {
  50028. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50029. }
  50030. else {
  50031. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50032. }
  50033. }
  50034. var textureSize = _this.getSize();
  50035. _this._canvas.width = textureSize.width;
  50036. _this._canvas.height = textureSize.height;
  50037. _this._context = _this._canvas.getContext("2d");
  50038. return _this;
  50039. }
  50040. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50041. get: function () {
  50042. return true;
  50043. },
  50044. enumerable: true,
  50045. configurable: true
  50046. });
  50047. DynamicTexture.prototype._recreate = function (textureSize) {
  50048. this._canvas.width = textureSize.width;
  50049. this._canvas.height = textureSize.height;
  50050. this.releaseInternalTexture();
  50051. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50052. };
  50053. DynamicTexture.prototype.scale = function (ratio) {
  50054. var textureSize = this.getSize();
  50055. textureSize.width *= ratio;
  50056. textureSize.height *= ratio;
  50057. this._recreate(textureSize);
  50058. };
  50059. DynamicTexture.prototype.scaleTo = function (width, height) {
  50060. var textureSize = this.getSize();
  50061. textureSize.width = width;
  50062. textureSize.height = height;
  50063. this._recreate(textureSize);
  50064. };
  50065. DynamicTexture.prototype.getContext = function () {
  50066. return this._context;
  50067. };
  50068. DynamicTexture.prototype.clear = function () {
  50069. var size = this.getSize();
  50070. this._context.fillRect(0, 0, size.width, size.height);
  50071. };
  50072. DynamicTexture.prototype.update = function (invertY) {
  50073. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50074. };
  50075. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50076. if (update === void 0) { update = true; }
  50077. var size = this.getSize();
  50078. if (clearColor) {
  50079. this._context.fillStyle = clearColor;
  50080. this._context.fillRect(0, 0, size.width, size.height);
  50081. }
  50082. this._context.font = font;
  50083. if (x === null || x === undefined) {
  50084. var textSize = this._context.measureText(text);
  50085. x = (size.width - textSize.width) / 2;
  50086. }
  50087. if (y === null || y === undefined) {
  50088. var fontSize = parseInt((font.replace(/\D/g, '')));
  50089. ;
  50090. y = (size.height / 2) + (fontSize / 3.65);
  50091. }
  50092. this._context.fillStyle = color;
  50093. this._context.fillText(text, x, y);
  50094. if (update) {
  50095. this.update(invertY);
  50096. }
  50097. };
  50098. DynamicTexture.prototype.clone = function () {
  50099. var scene = this.getScene();
  50100. if (!scene) {
  50101. return this;
  50102. }
  50103. var textureSize = this.getSize();
  50104. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50105. // Base texture
  50106. newTexture.hasAlpha = this.hasAlpha;
  50107. newTexture.level = this.level;
  50108. // Dynamic Texture
  50109. newTexture.wrapU = this.wrapU;
  50110. newTexture.wrapV = this.wrapV;
  50111. return newTexture;
  50112. };
  50113. DynamicTexture.prototype._rebuild = function () {
  50114. this.update();
  50115. };
  50116. return DynamicTexture;
  50117. }(BABYLON.Texture));
  50118. BABYLON.DynamicTexture = DynamicTexture;
  50119. })(BABYLON || (BABYLON = {}));
  50120. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50121. var BABYLON;
  50122. (function (BABYLON) {
  50123. var VideoTexture = /** @class */ (function (_super) {
  50124. __extends(VideoTexture, _super);
  50125. /**
  50126. * Creates a video texture.
  50127. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50128. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50129. * @param {BABYLON.Scene} scene is obviously the current scene.
  50130. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50131. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50132. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50133. */
  50134. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50135. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50136. if (invertY === void 0) { invertY = false; }
  50137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50138. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50139. _this._autoLaunch = true;
  50140. var urls = null;
  50141. _this.name = name;
  50142. if (urlsOrVideo instanceof HTMLVideoElement) {
  50143. _this.video = urlsOrVideo;
  50144. }
  50145. else {
  50146. urls = urlsOrVideo;
  50147. _this.video = document.createElement("video");
  50148. _this.video.autoplay = false;
  50149. _this.video.loop = true;
  50150. }
  50151. _this._engine = _this.getScene().getEngine();
  50152. _this._generateMipMaps = generateMipMaps;
  50153. _this._samplingMode = samplingMode;
  50154. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50155. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50156. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50157. }
  50158. else {
  50159. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50160. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50161. _this._generateMipMaps = false;
  50162. }
  50163. if (urls) {
  50164. _this.video.addEventListener("canplay", function () {
  50165. _this._createTexture();
  50166. });
  50167. urls.forEach(function (url) {
  50168. var source = document.createElement("source");
  50169. source.src = url;
  50170. _this.video.appendChild(source);
  50171. });
  50172. }
  50173. else {
  50174. _this._createTexture();
  50175. }
  50176. _this._lastUpdate = BABYLON.Tools.Now;
  50177. return _this;
  50178. }
  50179. VideoTexture.prototype.__setTextureReady = function () {
  50180. if (this._texture) {
  50181. this._texture.isReady = true;
  50182. }
  50183. };
  50184. VideoTexture.prototype._createTexture = function () {
  50185. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50186. if (this._autoLaunch) {
  50187. this._autoLaunch = false;
  50188. this.video.play();
  50189. }
  50190. this._setTextureReady = this.__setTextureReady.bind(this);
  50191. this.video.addEventListener("playing", this._setTextureReady);
  50192. };
  50193. VideoTexture.prototype._rebuild = function () {
  50194. this.update();
  50195. };
  50196. VideoTexture.prototype.update = function () {
  50197. var now = BABYLON.Tools.Now;
  50198. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50199. return false;
  50200. }
  50201. this._lastUpdate = now;
  50202. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50203. return true;
  50204. };
  50205. VideoTexture.prototype.dispose = function () {
  50206. _super.prototype.dispose.call(this);
  50207. this.video.removeEventListener("playing", this._setTextureReady);
  50208. };
  50209. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50210. var video = document.createElement("video");
  50211. var constraintsDeviceId;
  50212. if (constraints && constraints.deviceId) {
  50213. constraintsDeviceId = {
  50214. exact: constraints.deviceId
  50215. };
  50216. }
  50217. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50218. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50219. if (navigator.getUserMedia) {
  50220. navigator.getUserMedia({
  50221. video: {
  50222. deviceId: constraintsDeviceId,
  50223. width: {
  50224. min: (constraints && constraints.minWidth) || 256,
  50225. max: (constraints && constraints.maxWidth) || 640
  50226. },
  50227. height: {
  50228. min: (constraints && constraints.minHeight) || 256,
  50229. max: (constraints && constraints.maxHeight) || 480
  50230. }
  50231. }
  50232. }, function (stream) {
  50233. if (video.mozSrcObject !== undefined) {
  50234. video.mozSrcObject = stream;
  50235. }
  50236. else {
  50237. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50238. }
  50239. video.play();
  50240. if (onReady) {
  50241. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50242. }
  50243. }, function (e) {
  50244. BABYLON.Tools.Error(e.name);
  50245. });
  50246. }
  50247. };
  50248. return VideoTexture;
  50249. }(BABYLON.Texture));
  50250. BABYLON.VideoTexture = VideoTexture;
  50251. })(BABYLON || (BABYLON = {}));
  50252. //# sourceMappingURL=babylon.videoTexture.js.map
  50253. var BABYLON;
  50254. (function (BABYLON) {
  50255. var RawTexture = /** @class */ (function (_super) {
  50256. __extends(RawTexture, _super);
  50257. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50258. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50259. if (invertY === void 0) { invertY = false; }
  50260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50261. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50262. _this.format = format;
  50263. _this._engine = scene.getEngine();
  50264. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50265. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50266. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50267. return _this;
  50268. }
  50269. RawTexture.prototype.update = function (data) {
  50270. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50271. };
  50272. // Statics
  50273. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50274. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50275. if (invertY === void 0) { invertY = false; }
  50276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50277. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50278. };
  50279. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50281. if (invertY === void 0) { invertY = false; }
  50282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50283. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50284. };
  50285. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50287. if (invertY === void 0) { invertY = false; }
  50288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50289. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50290. };
  50291. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50292. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50293. if (invertY === void 0) { invertY = false; }
  50294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50295. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50296. };
  50297. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50298. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50299. if (invertY === void 0) { invertY = false; }
  50300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50301. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50302. };
  50303. return RawTexture;
  50304. }(BABYLON.Texture));
  50305. BABYLON.RawTexture = RawTexture;
  50306. })(BABYLON || (BABYLON = {}));
  50307. //# sourceMappingURL=babylon.rawTexture.js.map
  50308. var BABYLON;
  50309. (function (BABYLON) {
  50310. var PostProcess = /** @class */ (function () {
  50311. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50313. if (defines === void 0) { defines = null; }
  50314. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50315. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50316. if (blockCompilation === void 0) { blockCompilation = false; }
  50317. this.name = name;
  50318. this.width = -1;
  50319. this.height = -1;
  50320. this.autoClear = true;
  50321. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50322. /*
  50323. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50324. Can only be used on a single postprocess or on the last one of a chain.
  50325. */
  50326. this.enablePixelPerfectMode = false;
  50327. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50328. this.alwaysForcePOT = false;
  50329. this.samples = 1;
  50330. this.adaptScaleToCurrentViewport = false;
  50331. this._reusable = false;
  50332. this._textures = new BABYLON.SmartArray(2);
  50333. this._currentRenderTextureInd = 0;
  50334. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50335. this._texelSize = BABYLON.Vector2.Zero();
  50336. // Events
  50337. /**
  50338. * An event triggered when the postprocess is activated.
  50339. * @type {BABYLON.Observable}
  50340. */
  50341. this.onActivateObservable = new BABYLON.Observable();
  50342. /**
  50343. * An event triggered when the postprocess changes its size.
  50344. * @type {BABYLON.Observable}
  50345. */
  50346. this.onSizeChangedObservable = new BABYLON.Observable();
  50347. /**
  50348. * An event triggered when the postprocess applies its effect.
  50349. * @type {BABYLON.Observable}
  50350. */
  50351. this.onApplyObservable = new BABYLON.Observable();
  50352. /**
  50353. * An event triggered before rendering the postprocess
  50354. * @type {BABYLON.Observable}
  50355. */
  50356. this.onBeforeRenderObservable = new BABYLON.Observable();
  50357. /**
  50358. * An event triggered after rendering the postprocess
  50359. * @type {BABYLON.Observable}
  50360. */
  50361. this.onAfterRenderObservable = new BABYLON.Observable();
  50362. if (camera != null) {
  50363. this._camera = camera;
  50364. this._scene = camera.getScene();
  50365. camera.attachPostProcess(this);
  50366. this._engine = this._scene.getEngine();
  50367. this._scene.postProcesses.push(this);
  50368. }
  50369. else if (engine) {
  50370. this._engine = engine;
  50371. this._engine.postProcesses.push(this);
  50372. }
  50373. this._options = options;
  50374. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50375. this._reusable = reusable || false;
  50376. this._textureType = textureType;
  50377. this._samplers = samplers || [];
  50378. this._samplers.push("textureSampler");
  50379. this._fragmentUrl = fragmentUrl;
  50380. this._vertexUrl = vertexUrl;
  50381. this._parameters = parameters || [];
  50382. this._parameters.push("scale");
  50383. this._indexParameters = indexParameters;
  50384. if (!blockCompilation) {
  50385. this.updateEffect(defines);
  50386. }
  50387. }
  50388. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50389. set: function (callback) {
  50390. if (this._onActivateObserver) {
  50391. this.onActivateObservable.remove(this._onActivateObserver);
  50392. }
  50393. if (callback) {
  50394. this._onActivateObserver = this.onActivateObservable.add(callback);
  50395. }
  50396. },
  50397. enumerable: true,
  50398. configurable: true
  50399. });
  50400. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50401. set: function (callback) {
  50402. if (this._onSizeChangedObserver) {
  50403. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50404. }
  50405. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50406. },
  50407. enumerable: true,
  50408. configurable: true
  50409. });
  50410. Object.defineProperty(PostProcess.prototype, "onApply", {
  50411. set: function (callback) {
  50412. if (this._onApplyObserver) {
  50413. this.onApplyObservable.remove(this._onApplyObserver);
  50414. }
  50415. this._onApplyObserver = this.onApplyObservable.add(callback);
  50416. },
  50417. enumerable: true,
  50418. configurable: true
  50419. });
  50420. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50421. set: function (callback) {
  50422. if (this._onBeforeRenderObserver) {
  50423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50424. }
  50425. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50426. },
  50427. enumerable: true,
  50428. configurable: true
  50429. });
  50430. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50431. set: function (callback) {
  50432. if (this._onAfterRenderObserver) {
  50433. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50434. }
  50435. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50436. },
  50437. enumerable: true,
  50438. configurable: true
  50439. });
  50440. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50441. get: function () {
  50442. return this._textures.data[this._currentRenderTextureInd];
  50443. },
  50444. set: function (value) {
  50445. this._forcedOutputTexture = value;
  50446. },
  50447. enumerable: true,
  50448. configurable: true
  50449. });
  50450. PostProcess.prototype.getCamera = function () {
  50451. return this._camera;
  50452. };
  50453. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50454. get: function () {
  50455. if (this._shareOutputWithPostProcess) {
  50456. return this._shareOutputWithPostProcess.texelSize;
  50457. }
  50458. if (this._forcedOutputTexture) {
  50459. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50460. }
  50461. return this._texelSize;
  50462. },
  50463. enumerable: true,
  50464. configurable: true
  50465. });
  50466. PostProcess.prototype.getEngine = function () {
  50467. return this._engine;
  50468. };
  50469. PostProcess.prototype.getEffect = function () {
  50470. return this._effect;
  50471. };
  50472. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50473. this._disposeTextures();
  50474. this._shareOutputWithPostProcess = postProcess;
  50475. return this;
  50476. };
  50477. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50478. if (defines === void 0) { defines = null; }
  50479. if (uniforms === void 0) { uniforms = null; }
  50480. if (samplers === void 0) { samplers = null; }
  50481. 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);
  50482. };
  50483. PostProcess.prototype.isReusable = function () {
  50484. return this._reusable;
  50485. };
  50486. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50487. PostProcess.prototype.markTextureDirty = function () {
  50488. this.width = -1;
  50489. };
  50490. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50491. var _this = this;
  50492. if (sourceTexture === void 0) { sourceTexture = null; }
  50493. camera = camera || this._camera;
  50494. var scene = camera.getScene();
  50495. var engine = scene.getEngine();
  50496. var maxSize = engine.getCaps().maxTextureSize;
  50497. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50498. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50499. var desiredWidth = (this._options.width || requiredWidth);
  50500. var desiredHeight = this._options.height || requiredHeight;
  50501. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50502. if (this.adaptScaleToCurrentViewport) {
  50503. var currentViewport = engine.currentViewport;
  50504. if (currentViewport) {
  50505. desiredWidth *= currentViewport.width;
  50506. desiredHeight *= currentViewport.height;
  50507. }
  50508. }
  50509. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50510. if (!this._options.width) {
  50511. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50512. }
  50513. if (!this._options.height) {
  50514. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50515. }
  50516. }
  50517. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50518. if (this._textures.length > 0) {
  50519. for (var i = 0; i < this._textures.length; i++) {
  50520. this._engine._releaseTexture(this._textures.data[i]);
  50521. }
  50522. this._textures.reset();
  50523. }
  50524. this.width = desiredWidth;
  50525. this.height = desiredHeight;
  50526. var textureSize = { width: this.width, height: this.height };
  50527. var textureOptions = {
  50528. generateMipMaps: false,
  50529. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50530. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50531. samplingMode: this.renderTargetSamplingMode,
  50532. type: this._textureType
  50533. };
  50534. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50535. if (this._reusable) {
  50536. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50537. }
  50538. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50539. this.onSizeChangedObservable.notifyObservers(this);
  50540. }
  50541. this._textures.forEach(function (texture) {
  50542. if (texture.samples !== _this.samples) {
  50543. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50544. }
  50545. });
  50546. }
  50547. var target;
  50548. if (this._shareOutputWithPostProcess) {
  50549. target = this._shareOutputWithPostProcess.outputTexture;
  50550. }
  50551. else if (this._forcedOutputTexture) {
  50552. target = this._forcedOutputTexture;
  50553. this.width = this._forcedOutputTexture.width;
  50554. this.height = this._forcedOutputTexture.height;
  50555. }
  50556. else {
  50557. target = this.outputTexture;
  50558. }
  50559. if (this.enablePixelPerfectMode) {
  50560. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50561. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50562. }
  50563. else {
  50564. this._scaleRatio.copyFromFloats(1, 1);
  50565. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50566. }
  50567. this.onActivateObservable.notifyObservers(camera);
  50568. // Clear
  50569. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50570. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50571. }
  50572. if (this._reusable) {
  50573. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50574. }
  50575. };
  50576. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50577. get: function () {
  50578. return this._effect.isSupported;
  50579. },
  50580. enumerable: true,
  50581. configurable: true
  50582. });
  50583. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50584. get: function () {
  50585. if (this._shareOutputWithPostProcess) {
  50586. return this._shareOutputWithPostProcess.aspectRatio;
  50587. }
  50588. if (this._forcedOutputTexture) {
  50589. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50590. }
  50591. return this.width / this.height;
  50592. },
  50593. enumerable: true,
  50594. configurable: true
  50595. });
  50596. PostProcess.prototype.apply = function () {
  50597. // Check
  50598. if (!this._effect || !this._effect.isReady())
  50599. return null;
  50600. // States
  50601. this._engine.enableEffect(this._effect);
  50602. this._engine.setState(false);
  50603. this._engine.setDepthBuffer(false);
  50604. this._engine.setDepthWrite(false);
  50605. // Alpha
  50606. this._engine.setAlphaMode(this.alphaMode);
  50607. if (this.alphaConstants) {
  50608. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50609. }
  50610. // Texture
  50611. var source;
  50612. if (this._shareOutputWithPostProcess) {
  50613. source = this._shareOutputWithPostProcess.outputTexture;
  50614. }
  50615. else if (this._forcedOutputTexture) {
  50616. source = this._forcedOutputTexture;
  50617. }
  50618. else {
  50619. source = this.outputTexture;
  50620. }
  50621. this._effect._bindTexture("textureSampler", source);
  50622. // Parameters
  50623. this._effect.setVector2("scale", this._scaleRatio);
  50624. this.onApplyObservable.notifyObservers(this._effect);
  50625. return this._effect;
  50626. };
  50627. PostProcess.prototype._disposeTextures = function () {
  50628. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50629. return;
  50630. }
  50631. if (this._textures.length > 0) {
  50632. for (var i = 0; i < this._textures.length; i++) {
  50633. this._engine._releaseTexture(this._textures.data[i]);
  50634. }
  50635. }
  50636. this._textures.dispose();
  50637. };
  50638. PostProcess.prototype.dispose = function (camera) {
  50639. camera = camera || this._camera;
  50640. this._disposeTextures();
  50641. if (this._scene) {
  50642. var index_1 = this._scene.postProcesses.indexOf(this);
  50643. if (index_1 !== -1) {
  50644. this._scene.postProcesses.splice(index_1, 1);
  50645. }
  50646. }
  50647. else {
  50648. var index_2 = this._engine.postProcesses.indexOf(this);
  50649. if (index_2 !== -1) {
  50650. this._engine.postProcesses.splice(index_2, 1);
  50651. }
  50652. }
  50653. if (!camera) {
  50654. return;
  50655. }
  50656. camera.detachPostProcess(this);
  50657. var index = camera._postProcesses.indexOf(this);
  50658. if (index === 0 && camera._postProcesses.length > 0) {
  50659. this._camera._postProcesses[0].markTextureDirty();
  50660. }
  50661. this.onActivateObservable.clear();
  50662. this.onAfterRenderObservable.clear();
  50663. this.onApplyObservable.clear();
  50664. this.onBeforeRenderObservable.clear();
  50665. this.onSizeChangedObservable.clear();
  50666. };
  50667. return PostProcess;
  50668. }());
  50669. BABYLON.PostProcess = PostProcess;
  50670. })(BABYLON || (BABYLON = {}));
  50671. //# sourceMappingURL=babylon.postProcess.js.map
  50672. var BABYLON;
  50673. (function (BABYLON) {
  50674. var PassPostProcess = /** @class */ (function (_super) {
  50675. __extends(PassPostProcess, _super);
  50676. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50677. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50678. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50679. }
  50680. return PassPostProcess;
  50681. }(BABYLON.PostProcess));
  50682. BABYLON.PassPostProcess = PassPostProcess;
  50683. })(BABYLON || (BABYLON = {}));
  50684. //# sourceMappingURL=babylon.passPostProcess.js.map
  50685. var BABYLON;
  50686. (function (BABYLON) {
  50687. var ShadowGenerator = /** @class */ (function () {
  50688. /**
  50689. * Creates a ShadowGenerator object.
  50690. * A ShadowGenerator is the required tool to use the shadows.
  50691. * Each light casting shadows needs to use its own ShadowGenerator.
  50692. * Required parameters :
  50693. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50694. * - `light`: the light object generating the shadows.
  50695. * - `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.
  50696. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50697. */
  50698. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50699. // Members
  50700. this._bias = 0.00005;
  50701. this._blurBoxOffset = 1;
  50702. this._blurScale = 2;
  50703. this._blurKernel = 1;
  50704. this._useKernelBlur = false;
  50705. this._filter = ShadowGenerator.FILTER_NONE;
  50706. this._darkness = 0;
  50707. this._transparencyShadow = false;
  50708. /**
  50709. * Controls the extent to which the shadows fade out at the edge of the frustum
  50710. * Used only by directionals and spots
  50711. */
  50712. this.frustumEdgeFalloff = 0;
  50713. this.forceBackFacesOnly = false;
  50714. this._lightDirection = BABYLON.Vector3.Zero();
  50715. this._viewMatrix = BABYLON.Matrix.Zero();
  50716. this._projectionMatrix = BABYLON.Matrix.Zero();
  50717. this._transformMatrix = BABYLON.Matrix.Zero();
  50718. this._currentFaceIndex = 0;
  50719. this._currentFaceIndexCache = 0;
  50720. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50721. this._mapSize = mapSize;
  50722. this._light = light;
  50723. this._scene = light.getScene();
  50724. light._shadowGenerator = this;
  50725. // Texture type fallback from float to int if not supported.
  50726. var caps = this._scene.getEngine().getCaps();
  50727. if (!useFullFloatFirst) {
  50728. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50729. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50730. }
  50731. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50732. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50733. }
  50734. else {
  50735. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50736. }
  50737. }
  50738. else {
  50739. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50740. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50741. }
  50742. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50743. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50744. }
  50745. else {
  50746. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50747. }
  50748. }
  50749. this._initializeGenerator();
  50750. }
  50751. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50752. // Static
  50753. get: function () {
  50754. return ShadowGenerator._FILTER_NONE;
  50755. },
  50756. enumerable: true,
  50757. configurable: true
  50758. });
  50759. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50760. get: function () {
  50761. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50762. },
  50763. enumerable: true,
  50764. configurable: true
  50765. });
  50766. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50767. get: function () {
  50768. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50769. },
  50770. enumerable: true,
  50771. configurable: true
  50772. });
  50773. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50774. get: function () {
  50775. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50781. get: function () {
  50782. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50783. },
  50784. enumerable: true,
  50785. configurable: true
  50786. });
  50787. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50788. get: function () {
  50789. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50795. get: function () {
  50796. return this._bias;
  50797. },
  50798. set: function (bias) {
  50799. this._bias = bias;
  50800. },
  50801. enumerable: true,
  50802. configurable: true
  50803. });
  50804. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50805. get: function () {
  50806. return this._blurBoxOffset;
  50807. },
  50808. set: function (value) {
  50809. if (this._blurBoxOffset === value) {
  50810. return;
  50811. }
  50812. this._blurBoxOffset = value;
  50813. this._disposeBlurPostProcesses();
  50814. },
  50815. enumerable: true,
  50816. configurable: true
  50817. });
  50818. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50819. get: function () {
  50820. return this._blurScale;
  50821. },
  50822. set: function (value) {
  50823. if (this._blurScale === value) {
  50824. return;
  50825. }
  50826. this._blurScale = value;
  50827. this._disposeBlurPostProcesses();
  50828. },
  50829. enumerable: true,
  50830. configurable: true
  50831. });
  50832. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50833. get: function () {
  50834. return this._blurKernel;
  50835. },
  50836. set: function (value) {
  50837. if (this._blurKernel === value) {
  50838. return;
  50839. }
  50840. this._blurKernel = value;
  50841. this._disposeBlurPostProcesses();
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50847. get: function () {
  50848. return this._useKernelBlur;
  50849. },
  50850. set: function (value) {
  50851. if (this._useKernelBlur === value) {
  50852. return;
  50853. }
  50854. this._useKernelBlur = value;
  50855. this._disposeBlurPostProcesses();
  50856. },
  50857. enumerable: true,
  50858. configurable: true
  50859. });
  50860. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50861. get: function () {
  50862. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50863. },
  50864. set: function (value) {
  50865. this._depthScale = value;
  50866. },
  50867. enumerable: true,
  50868. configurable: true
  50869. });
  50870. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50871. get: function () {
  50872. return this._filter;
  50873. },
  50874. set: function (value) {
  50875. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50876. if (this._light.needCube()) {
  50877. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50878. this.useExponentialShadowMap = true;
  50879. return;
  50880. }
  50881. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50882. this.useCloseExponentialShadowMap = true;
  50883. return;
  50884. }
  50885. }
  50886. if (this._filter === value) {
  50887. return;
  50888. }
  50889. this._filter = value;
  50890. this._disposeBlurPostProcesses();
  50891. this._applyFilterValues();
  50892. this._light._markMeshesAsLightDirty();
  50893. },
  50894. enumerable: true,
  50895. configurable: true
  50896. });
  50897. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50898. get: function () {
  50899. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50900. },
  50901. set: function (value) {
  50902. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50903. return;
  50904. }
  50905. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50911. get: function () {
  50912. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50913. return this.useExponentialShadowMap;
  50914. },
  50915. set: function (value) {
  50916. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50917. this.useExponentialShadowMap = value;
  50918. },
  50919. enumerable: true,
  50920. configurable: true
  50921. });
  50922. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50923. get: function () {
  50924. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50925. return this.useBlurExponentialShadowMap;
  50926. },
  50927. set: function (value) {
  50928. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50929. this.useBlurExponentialShadowMap = value;
  50930. },
  50931. enumerable: true,
  50932. configurable: true
  50933. });
  50934. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50935. get: function () {
  50936. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50937. },
  50938. set: function (value) {
  50939. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50940. return;
  50941. }
  50942. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50943. },
  50944. enumerable: true,
  50945. configurable: true
  50946. });
  50947. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50948. get: function () {
  50949. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50950. },
  50951. set: function (value) {
  50952. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50953. return;
  50954. }
  50955. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50961. get: function () {
  50962. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50963. },
  50964. set: function (value) {
  50965. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50966. return;
  50967. }
  50968. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50969. },
  50970. enumerable: true,
  50971. configurable: true
  50972. });
  50973. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50974. get: function () {
  50975. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50976. },
  50977. set: function (value) {
  50978. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50979. return;
  50980. }
  50981. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50982. },
  50983. enumerable: true,
  50984. configurable: true
  50985. });
  50986. /**
  50987. * Returns the darkness value (float).
  50988. */
  50989. ShadowGenerator.prototype.getDarkness = function () {
  50990. return this._darkness;
  50991. };
  50992. /**
  50993. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50994. * Returns the ShadowGenerator.
  50995. */
  50996. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50997. if (darkness >= 1.0)
  50998. this._darkness = 1.0;
  50999. else if (darkness <= 0.0)
  51000. this._darkness = 0.0;
  51001. else
  51002. this._darkness = darkness;
  51003. return this;
  51004. };
  51005. /**
  51006. * Sets the ability to have transparent shadow (boolean).
  51007. * Returns the ShadowGenerator.
  51008. */
  51009. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51010. this._transparencyShadow = hasShadow;
  51011. return this;
  51012. };
  51013. /**
  51014. * Returns a RenderTargetTexture object : the shadow map texture.
  51015. */
  51016. ShadowGenerator.prototype.getShadowMap = function () {
  51017. return this._shadowMap;
  51018. };
  51019. /**
  51020. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51021. */
  51022. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51023. if (this._shadowMap2) {
  51024. return this._shadowMap2;
  51025. }
  51026. return this._shadowMap;
  51027. };
  51028. /**
  51029. * Helper function to add a mesh and its descendants to the list of shadow casters
  51030. * @param mesh Mesh to add
  51031. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51032. */
  51033. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51034. if (includeDescendants === void 0) { includeDescendants = true; }
  51035. if (!this._shadowMap) {
  51036. return this;
  51037. }
  51038. if (!this._shadowMap.renderList) {
  51039. this._shadowMap.renderList = [];
  51040. }
  51041. this._shadowMap.renderList.push(mesh);
  51042. if (includeDescendants) {
  51043. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51044. }
  51045. return this;
  51046. var _a;
  51047. };
  51048. /**
  51049. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51050. * @param mesh Mesh to remove
  51051. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51052. */
  51053. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51054. if (includeDescendants === void 0) { includeDescendants = true; }
  51055. if (!this._shadowMap || !this._shadowMap.renderList) {
  51056. return this;
  51057. }
  51058. var index = this._shadowMap.renderList.indexOf(mesh);
  51059. if (index !== -1) {
  51060. this._shadowMap.renderList.splice(index, 1);
  51061. }
  51062. if (includeDescendants) {
  51063. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51064. var child = _a[_i];
  51065. this.removeShadowCaster(child);
  51066. }
  51067. }
  51068. return this;
  51069. };
  51070. /**
  51071. * Returns the associated light object.
  51072. */
  51073. ShadowGenerator.prototype.getLight = function () {
  51074. return this._light;
  51075. };
  51076. ShadowGenerator.prototype._initializeGenerator = function () {
  51077. this._light._markMeshesAsLightDirty();
  51078. this._initializeShadowMap();
  51079. };
  51080. ShadowGenerator.prototype._initializeShadowMap = function () {
  51081. var _this = this;
  51082. // Render target
  51083. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51084. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51085. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51086. this._shadowMap.anisotropicFilteringLevel = 1;
  51087. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51088. this._shadowMap.renderParticles = false;
  51089. this._shadowMap.ignoreCameraViewport = true;
  51090. // Record Face Index before render.
  51091. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51092. _this._currentFaceIndex = faceIndex;
  51093. });
  51094. // Custom render function.
  51095. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51096. // Blur if required afer render.
  51097. this._shadowMap.onAfterUnbindObservable.add(function () {
  51098. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51099. return;
  51100. }
  51101. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51102. _this._initializeBlurRTTAndPostProcesses();
  51103. }
  51104. var shadowMap = _this.getShadowMapForRendering();
  51105. if (shadowMap) {
  51106. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51107. }
  51108. });
  51109. // Clear according to the chosen filter.
  51110. this._shadowMap.onClearObservable.add(function (engine) {
  51111. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51112. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51113. }
  51114. else {
  51115. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51116. }
  51117. });
  51118. };
  51119. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51120. var _this = this;
  51121. var engine = this._scene.getEngine();
  51122. var targetSize = this._mapSize / this.blurScale;
  51123. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51124. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51125. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51126. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51127. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51128. }
  51129. if (this.useKernelBlur) {
  51130. 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);
  51131. this._kernelBlurXPostprocess.width = targetSize;
  51132. this._kernelBlurXPostprocess.height = targetSize;
  51133. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51134. effect.setTexture("textureSampler", _this._shadowMap);
  51135. });
  51136. 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);
  51137. this._kernelBlurXPostprocess.autoClear = false;
  51138. this._kernelBlurYPostprocess.autoClear = false;
  51139. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51140. this._kernelBlurXPostprocess.packedFloat = true;
  51141. this._kernelBlurYPostprocess.packedFloat = true;
  51142. }
  51143. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51144. }
  51145. else {
  51146. 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);
  51147. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51148. effect.setFloat2("screenSize", targetSize, targetSize);
  51149. effect.setTexture("textureSampler", _this._shadowMap);
  51150. });
  51151. this._boxBlurPostprocess.autoClear = false;
  51152. this._blurPostProcesses = [this._boxBlurPostprocess];
  51153. }
  51154. };
  51155. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51156. var index;
  51157. var engine = this._scene.getEngine();
  51158. if (depthOnlySubMeshes.length) {
  51159. engine.setColorWrite(false);
  51160. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51161. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51162. }
  51163. engine.setColorWrite(true);
  51164. }
  51165. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51166. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51167. }
  51168. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51169. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51170. }
  51171. if (this._transparencyShadow) {
  51172. for (index = 0; index < transparentSubMeshes.length; index++) {
  51173. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51174. }
  51175. }
  51176. };
  51177. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51178. var _this = this;
  51179. var mesh = subMesh.getRenderingMesh();
  51180. var scene = this._scene;
  51181. var engine = scene.getEngine();
  51182. var material = subMesh.getMaterial();
  51183. if (!material) {
  51184. return;
  51185. }
  51186. // Culling
  51187. engine.setState(material.backFaceCulling);
  51188. // Managing instances
  51189. var batch = mesh._getInstancesRenderList(subMesh._id);
  51190. if (batch.mustReturn) {
  51191. return;
  51192. }
  51193. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51194. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51195. engine.enableEffect(this._effect);
  51196. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51197. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51198. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51199. this._effect.setVector3("lightPosition", this.getLight().position);
  51200. if (scene.activeCamera) {
  51201. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51202. }
  51203. // Alpha test
  51204. if (material && material.needAlphaTesting()) {
  51205. var alphaTexture = material.getAlphaTestTexture();
  51206. if (alphaTexture) {
  51207. this._effect.setTexture("diffuseSampler", alphaTexture);
  51208. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51209. }
  51210. }
  51211. // Bones
  51212. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51213. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51214. }
  51215. if (this.forceBackFacesOnly) {
  51216. engine.setState(true, 0, false, true);
  51217. }
  51218. // Draw
  51219. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51220. if (this.forceBackFacesOnly) {
  51221. engine.setState(true, 0, false, false);
  51222. }
  51223. }
  51224. else {
  51225. // Need to reset refresh rate of the shadowMap
  51226. if (this._shadowMap) {
  51227. this._shadowMap.resetRefreshCounter();
  51228. }
  51229. }
  51230. };
  51231. ShadowGenerator.prototype._applyFilterValues = function () {
  51232. if (!this._shadowMap) {
  51233. return;
  51234. }
  51235. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51236. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51237. }
  51238. else {
  51239. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51240. }
  51241. };
  51242. /**
  51243. * Force shader compilation including textures ready check
  51244. */
  51245. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51246. var _this = this;
  51247. var shadowMap = this.getShadowMap();
  51248. if (!shadowMap) {
  51249. return;
  51250. }
  51251. var subMeshes = new Array();
  51252. var currentIndex = 0;
  51253. var renderList = shadowMap.renderList;
  51254. if (!renderList) {
  51255. return;
  51256. }
  51257. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51258. var mesh = renderList_1[_i];
  51259. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51260. }
  51261. var checkReady = function () {
  51262. if (!_this._scene || !_this._scene.getEngine()) {
  51263. return;
  51264. }
  51265. var subMesh = subMeshes[currentIndex];
  51266. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51267. currentIndex++;
  51268. if (currentIndex >= subMeshes.length) {
  51269. if (onCompiled) {
  51270. onCompiled(_this);
  51271. }
  51272. return;
  51273. }
  51274. }
  51275. setTimeout(checkReady, 16);
  51276. };
  51277. if (subMeshes.length > 0) {
  51278. checkReady();
  51279. }
  51280. };
  51281. /**
  51282. * Boolean : true when the ShadowGenerator is finally computed.
  51283. */
  51284. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51285. var defines = [];
  51286. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51287. defines.push("#define FLOAT");
  51288. }
  51289. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51290. defines.push("#define ESM");
  51291. }
  51292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51293. var mesh = subMesh.getMesh();
  51294. var material = subMesh.getMaterial();
  51295. // Alpha test
  51296. if (material && material.needAlphaTesting()) {
  51297. var alphaTexture = material.getAlphaTestTexture();
  51298. if (alphaTexture) {
  51299. defines.push("#define ALPHATEST");
  51300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51301. attribs.push(BABYLON.VertexBuffer.UVKind);
  51302. defines.push("#define UV1");
  51303. }
  51304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51305. if (alphaTexture.coordinatesIndex === 1) {
  51306. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51307. defines.push("#define UV2");
  51308. }
  51309. }
  51310. }
  51311. }
  51312. // Bones
  51313. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51314. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51315. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51316. if (mesh.numBoneInfluencers > 4) {
  51317. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51318. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51319. }
  51320. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51321. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51322. }
  51323. else {
  51324. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51325. }
  51326. // Instances
  51327. if (useInstances) {
  51328. defines.push("#define INSTANCES");
  51329. attribs.push("world0");
  51330. attribs.push("world1");
  51331. attribs.push("world2");
  51332. attribs.push("world3");
  51333. }
  51334. // Get correct effect
  51335. var join = defines.join("\n");
  51336. if (this._cachedDefines !== join) {
  51337. this._cachedDefines = join;
  51338. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51339. }
  51340. return this._effect.isReady();
  51341. };
  51342. /**
  51343. * This creates the defines related to the standard BJS materials.
  51344. */
  51345. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51346. var scene = this._scene;
  51347. var light = this._light;
  51348. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51349. return;
  51350. }
  51351. defines["SHADOW" + lightIndex] = true;
  51352. if (this.usePoissonSampling) {
  51353. defines["SHADOWPCF" + lightIndex] = true;
  51354. }
  51355. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51356. defines["SHADOWESM" + lightIndex] = true;
  51357. }
  51358. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51359. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51360. }
  51361. if (light.needCube()) {
  51362. defines["SHADOWCUBE" + lightIndex] = true;
  51363. }
  51364. };
  51365. /**
  51366. * This binds shadow lights related to the standard BJS materials.
  51367. * It implies the unifroms available on the materials are the standard BJS ones.
  51368. */
  51369. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51370. var light = this._light;
  51371. var scene = this._scene;
  51372. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51373. return;
  51374. }
  51375. var camera = scene.activeCamera;
  51376. if (!camera) {
  51377. return;
  51378. }
  51379. var shadowMap = this.getShadowMap();
  51380. if (!shadowMap) {
  51381. return;
  51382. }
  51383. if (!light.needCube()) {
  51384. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51385. }
  51386. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51387. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51388. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51389. };
  51390. // Methods
  51391. /**
  51392. * Returns a Matrix object : the updated transformation matrix.
  51393. */
  51394. ShadowGenerator.prototype.getTransformMatrix = function () {
  51395. var scene = this._scene;
  51396. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51397. return this._transformMatrix;
  51398. }
  51399. this._currentRenderID = scene.getRenderId();
  51400. this._currentFaceIndexCache = this._currentFaceIndex;
  51401. var lightPosition = this._light.position;
  51402. if (this._light.computeTransformedInformation()) {
  51403. lightPosition = this._light.transformedPosition;
  51404. }
  51405. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51406. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51407. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51408. }
  51409. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51410. this._cachedPosition = lightPosition.clone();
  51411. this._cachedDirection = this._lightDirection.clone();
  51412. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51413. var shadowMap = this.getShadowMap();
  51414. if (shadowMap) {
  51415. var renderList = shadowMap.renderList;
  51416. if (renderList) {
  51417. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51418. }
  51419. }
  51420. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51421. }
  51422. return this._transformMatrix;
  51423. };
  51424. ShadowGenerator.prototype.recreateShadowMap = function () {
  51425. var shadowMap = this._shadowMap;
  51426. if (!shadowMap) {
  51427. return;
  51428. }
  51429. // Track render list.
  51430. var renderList = shadowMap.renderList;
  51431. // Clean up existing data.
  51432. this._disposeRTTandPostProcesses();
  51433. // Reinitializes.
  51434. this._initializeGenerator();
  51435. // Reaffect the filter to ensure a correct fallback if necessary.
  51436. this.filter = this.filter;
  51437. // Reaffect the filter.
  51438. this._applyFilterValues();
  51439. // Reaffect Render List.
  51440. this._shadowMap.renderList = renderList;
  51441. };
  51442. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51443. if (this._shadowMap2) {
  51444. this._shadowMap2.dispose();
  51445. this._shadowMap2 = null;
  51446. }
  51447. if (this._downSamplePostprocess) {
  51448. this._downSamplePostprocess.dispose();
  51449. this._downSamplePostprocess = null;
  51450. }
  51451. if (this._boxBlurPostprocess) {
  51452. this._boxBlurPostprocess.dispose();
  51453. this._boxBlurPostprocess = null;
  51454. }
  51455. if (this._kernelBlurXPostprocess) {
  51456. this._kernelBlurXPostprocess.dispose();
  51457. this._kernelBlurXPostprocess = null;
  51458. }
  51459. if (this._kernelBlurYPostprocess) {
  51460. this._kernelBlurYPostprocess.dispose();
  51461. this._kernelBlurYPostprocess = null;
  51462. }
  51463. this._blurPostProcesses = [];
  51464. };
  51465. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51466. if (this._shadowMap) {
  51467. this._shadowMap.dispose();
  51468. this._shadowMap = null;
  51469. }
  51470. this._disposeBlurPostProcesses();
  51471. };
  51472. /**
  51473. * Disposes the ShadowGenerator.
  51474. * Returns nothing.
  51475. */
  51476. ShadowGenerator.prototype.dispose = function () {
  51477. this._disposeRTTandPostProcesses();
  51478. if (this._light) {
  51479. this._light._shadowGenerator = null;
  51480. this._light._markMeshesAsLightDirty();
  51481. }
  51482. };
  51483. /**
  51484. * Serializes the ShadowGenerator and returns a serializationObject.
  51485. */
  51486. ShadowGenerator.prototype.serialize = function () {
  51487. var serializationObject = {};
  51488. var shadowMap = this.getShadowMap();
  51489. if (!shadowMap) {
  51490. return serializationObject;
  51491. }
  51492. serializationObject.lightId = this._light.id;
  51493. serializationObject.mapSize = shadowMap.getRenderSize();
  51494. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51495. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51496. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51497. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51498. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51499. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51500. serializationObject.depthScale = this.depthScale;
  51501. serializationObject.darkness = this.getDarkness();
  51502. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51503. serializationObject.blurKernel = this.blurKernel;
  51504. serializationObject.blurScale = this.blurScale;
  51505. serializationObject.useKernelBlur = this.useKernelBlur;
  51506. serializationObject.transparencyShadow = this._transparencyShadow;
  51507. serializationObject.renderList = [];
  51508. if (shadowMap.renderList) {
  51509. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51510. var mesh = shadowMap.renderList[meshIndex];
  51511. serializationObject.renderList.push(mesh.id);
  51512. }
  51513. }
  51514. return serializationObject;
  51515. };
  51516. /**
  51517. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51518. */
  51519. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51520. //casting to point light, as light is missing the position attr and typescript complains.
  51521. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51522. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51523. var shadowMap = shadowGenerator.getShadowMap();
  51524. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51525. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51526. meshes.forEach(function (mesh) {
  51527. if (!shadowMap) {
  51528. return;
  51529. }
  51530. if (!shadowMap.renderList) {
  51531. shadowMap.renderList = [];
  51532. }
  51533. shadowMap.renderList.push(mesh);
  51534. });
  51535. }
  51536. if (parsedShadowGenerator.usePoissonSampling) {
  51537. shadowGenerator.usePoissonSampling = true;
  51538. }
  51539. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51540. shadowGenerator.useExponentialShadowMap = true;
  51541. }
  51542. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51543. shadowGenerator.useBlurExponentialShadowMap = true;
  51544. }
  51545. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51546. shadowGenerator.useCloseExponentialShadowMap = true;
  51547. }
  51548. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51549. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51550. }
  51551. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51552. shadowGenerator.useExponentialShadowMap = true;
  51553. }
  51554. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51555. shadowGenerator.useBlurExponentialShadowMap = true;
  51556. }
  51557. if (parsedShadowGenerator.depthScale) {
  51558. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51559. }
  51560. if (parsedShadowGenerator.blurScale) {
  51561. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51562. }
  51563. if (parsedShadowGenerator.blurBoxOffset) {
  51564. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51565. }
  51566. if (parsedShadowGenerator.useKernelBlur) {
  51567. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51568. }
  51569. if (parsedShadowGenerator.blurKernel) {
  51570. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51571. }
  51572. if (parsedShadowGenerator.bias !== undefined) {
  51573. shadowGenerator.bias = parsedShadowGenerator.bias;
  51574. }
  51575. if (parsedShadowGenerator.darkness) {
  51576. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51577. }
  51578. if (parsedShadowGenerator.transparencyShadow) {
  51579. shadowGenerator.setTransparencyShadow(true);
  51580. }
  51581. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51582. return shadowGenerator;
  51583. };
  51584. ShadowGenerator._FILTER_NONE = 0;
  51585. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51586. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51587. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51588. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51589. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51590. return ShadowGenerator;
  51591. }());
  51592. BABYLON.ShadowGenerator = ShadowGenerator;
  51593. })(BABYLON || (BABYLON = {}));
  51594. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51595. var BABYLON;
  51596. (function (BABYLON) {
  51597. var DefaultLoadingScreen = /** @class */ (function () {
  51598. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51599. if (_loadingText === void 0) { _loadingText = ""; }
  51600. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51601. var _this = this;
  51602. this._renderingCanvas = _renderingCanvas;
  51603. this._loadingText = _loadingText;
  51604. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51605. // Resize
  51606. this._resizeLoadingUI = function () {
  51607. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51608. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51609. if (!_this._loadingDiv) {
  51610. return;
  51611. }
  51612. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51613. _this._loadingDiv.style.left = canvasRect.left + "px";
  51614. _this._loadingDiv.style.top = canvasRect.top + "px";
  51615. _this._loadingDiv.style.width = canvasRect.width + "px";
  51616. _this._loadingDiv.style.height = canvasRect.height + "px";
  51617. };
  51618. }
  51619. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51620. if (this._loadingDiv) {
  51621. // Do not add a loading screen if there is already one
  51622. return;
  51623. }
  51624. this._loadingDiv = document.createElement("div");
  51625. this._loadingDiv.id = "babylonjsLoadingDiv";
  51626. this._loadingDiv.style.opacity = "0";
  51627. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51628. this._loadingDiv.style.pointerEvents = "none";
  51629. // Loading text
  51630. this._loadingTextDiv = document.createElement("div");
  51631. this._loadingTextDiv.style.position = "absolute";
  51632. this._loadingTextDiv.style.left = "0";
  51633. this._loadingTextDiv.style.top = "50%";
  51634. this._loadingTextDiv.style.marginTop = "80px";
  51635. this._loadingTextDiv.style.width = "100%";
  51636. this._loadingTextDiv.style.height = "20px";
  51637. this._loadingTextDiv.style.fontFamily = "Arial";
  51638. this._loadingTextDiv.style.fontSize = "14px";
  51639. this._loadingTextDiv.style.color = "white";
  51640. this._loadingTextDiv.style.textAlign = "center";
  51641. this._loadingTextDiv.innerHTML = "Loading";
  51642. this._loadingDiv.appendChild(this._loadingTextDiv);
  51643. //set the predefined text
  51644. this._loadingTextDiv.innerHTML = this._loadingText;
  51645. // Generating keyframes
  51646. var style = document.createElement('style');
  51647. style.type = 'text/css';
  51648. 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 }";
  51649. style.innerHTML = keyFrames;
  51650. document.getElementsByTagName('head')[0].appendChild(style);
  51651. // Loading img
  51652. var imgBack = new Image();
  51653. 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";
  51654. imgBack.style.position = "absolute";
  51655. imgBack.style.left = "50%";
  51656. imgBack.style.top = "50%";
  51657. imgBack.style.marginLeft = "-60px";
  51658. imgBack.style.marginTop = "-60px";
  51659. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51660. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51661. imgBack.style.transformOrigin = "50% 50%";
  51662. imgBack.style.webkitTransformOrigin = "50% 50%";
  51663. this._loadingDiv.appendChild(imgBack);
  51664. this._resizeLoadingUI();
  51665. window.addEventListener("resize", this._resizeLoadingUI);
  51666. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51667. document.body.appendChild(this._loadingDiv);
  51668. this._loadingDiv.style.opacity = "1";
  51669. };
  51670. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51671. var _this = this;
  51672. if (!this._loadingDiv) {
  51673. return;
  51674. }
  51675. var onTransitionEnd = function () {
  51676. if (!_this._loadingDiv) {
  51677. return;
  51678. }
  51679. document.body.removeChild(_this._loadingDiv);
  51680. window.removeEventListener("resize", _this._resizeLoadingUI);
  51681. _this._loadingDiv = null;
  51682. };
  51683. this._loadingDiv.style.opacity = "0";
  51684. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51685. };
  51686. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51687. set: function (text) {
  51688. this._loadingText = text;
  51689. if (this._loadingTextDiv) {
  51690. this._loadingTextDiv.innerHTML = this._loadingText;
  51691. }
  51692. },
  51693. enumerable: true,
  51694. configurable: true
  51695. });
  51696. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51697. get: function () {
  51698. return this._loadingDivBackgroundColor;
  51699. },
  51700. set: function (color) {
  51701. this._loadingDivBackgroundColor = color;
  51702. if (!this._loadingDiv) {
  51703. return;
  51704. }
  51705. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51706. },
  51707. enumerable: true,
  51708. configurable: true
  51709. });
  51710. return DefaultLoadingScreen;
  51711. }());
  51712. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51713. })(BABYLON || (BABYLON = {}));
  51714. //# sourceMappingURL=babylon.loadingScreen.js.map
  51715. var BABYLON;
  51716. (function (BABYLON) {
  51717. var SceneLoader = /** @class */ (function () {
  51718. function SceneLoader() {
  51719. }
  51720. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51721. get: function () {
  51722. return 0;
  51723. },
  51724. enumerable: true,
  51725. configurable: true
  51726. });
  51727. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51728. get: function () {
  51729. return 1;
  51730. },
  51731. enumerable: true,
  51732. configurable: true
  51733. });
  51734. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51735. get: function () {
  51736. return 2;
  51737. },
  51738. enumerable: true,
  51739. configurable: true
  51740. });
  51741. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51742. get: function () {
  51743. return 3;
  51744. },
  51745. enumerable: true,
  51746. configurable: true
  51747. });
  51748. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51749. get: function () {
  51750. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51751. },
  51752. set: function (value) {
  51753. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51759. get: function () {
  51760. return SceneLoader._ShowLoadingScreen;
  51761. },
  51762. set: function (value) {
  51763. SceneLoader._ShowLoadingScreen = value;
  51764. },
  51765. enumerable: true,
  51766. configurable: true
  51767. });
  51768. Object.defineProperty(SceneLoader, "loggingLevel", {
  51769. get: function () {
  51770. return SceneLoader._loggingLevel;
  51771. },
  51772. set: function (value) {
  51773. SceneLoader._loggingLevel = value;
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51779. get: function () {
  51780. return SceneLoader._CleanBoneMatrixWeights;
  51781. },
  51782. set: function (value) {
  51783. SceneLoader._CleanBoneMatrixWeights = value;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. SceneLoader._getDefaultPlugin = function () {
  51789. return SceneLoader._registeredPlugins[".babylon"];
  51790. };
  51791. SceneLoader._getPluginForExtension = function (extension) {
  51792. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51793. if (registeredPlugin) {
  51794. return registeredPlugin;
  51795. }
  51796. return SceneLoader._getDefaultPlugin();
  51797. };
  51798. SceneLoader._getPluginForDirectLoad = function (data) {
  51799. for (var extension in SceneLoader._registeredPlugins) {
  51800. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51801. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51802. return SceneLoader._registeredPlugins[extension];
  51803. }
  51804. }
  51805. return SceneLoader._getDefaultPlugin();
  51806. };
  51807. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51808. if (sceneFilename.name) {
  51809. sceneFilename = sceneFilename.name;
  51810. }
  51811. var dotPosition = sceneFilename.lastIndexOf(".");
  51812. var queryStringPosition = sceneFilename.indexOf("?");
  51813. if (queryStringPosition === -1) {
  51814. queryStringPosition = sceneFilename.length;
  51815. }
  51816. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51817. return SceneLoader._getPluginForExtension(extension);
  51818. };
  51819. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51820. SceneLoader._getDirectLoad = function (sceneFilename) {
  51821. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51822. return sceneFilename.substr(5);
  51823. }
  51824. return null;
  51825. };
  51826. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51827. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51828. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51829. var plugin = registeredPlugin.plugin;
  51830. var useArrayBuffer = registeredPlugin.isBinary;
  51831. var database;
  51832. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51833. var dataCallback = function (data) {
  51834. if (scene.isDisposed) {
  51835. onError("Scene has been disposed");
  51836. return;
  51837. }
  51838. scene.database = database;
  51839. try {
  51840. onSuccess(plugin, data);
  51841. }
  51842. catch (e) {
  51843. onError(null, e);
  51844. }
  51845. };
  51846. var manifestChecked = function (success) {
  51847. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51848. if (request) {
  51849. onError(request.status + " " + request.statusText);
  51850. }
  51851. });
  51852. };
  51853. if (directLoad) {
  51854. dataCallback(directLoad);
  51855. return;
  51856. }
  51857. if (rootUrl.indexOf("file:") === -1) {
  51858. if (scene.getEngine().enableOfflineSupport) {
  51859. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51860. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51861. }
  51862. else {
  51863. manifestChecked(true);
  51864. }
  51865. }
  51866. else {
  51867. var fileOrString = sceneFilename;
  51868. if (fileOrString.name) {
  51869. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51870. }
  51871. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51872. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51873. }
  51874. else {
  51875. onError("Unable to find file named " + sceneFilename);
  51876. return;
  51877. }
  51878. }
  51879. };
  51880. // Public functions
  51881. SceneLoader.GetPluginForExtension = function (extension) {
  51882. return SceneLoader._getPluginForExtension(extension).plugin;
  51883. };
  51884. SceneLoader.RegisterPlugin = function (plugin) {
  51885. if (typeof plugin.extensions === "string") {
  51886. var extension = plugin.extensions;
  51887. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51888. plugin: plugin,
  51889. isBinary: false
  51890. };
  51891. }
  51892. else {
  51893. var extensions = plugin.extensions;
  51894. Object.keys(extensions).forEach(function (extension) {
  51895. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51896. plugin: plugin,
  51897. isBinary: extensions[extension].isBinary
  51898. };
  51899. });
  51900. }
  51901. };
  51902. /**
  51903. * Import meshes into a scene
  51904. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51905. * @param rootUrl a string that defines the root url for scene and resources
  51906. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51907. * @param scene the instance of BABYLON.Scene to append to
  51908. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51909. * @param onProgress a callback with a progress event for each file being loaded
  51910. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51911. */
  51912. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51913. if (onSuccess === void 0) { onSuccess = null; }
  51914. if (onProgress === void 0) { onProgress = null; }
  51915. if (onError === void 0) { onError = null; }
  51916. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51917. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51918. return;
  51919. }
  51920. var loadingToken = {};
  51921. scene._addPendingData(loadingToken);
  51922. var errorHandler = function (message, exception) {
  51923. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51924. if (onError) {
  51925. onError(scene, errorMessage, exception);
  51926. }
  51927. else {
  51928. BABYLON.Tools.Error(errorMessage);
  51929. // should the exception be thrown?
  51930. }
  51931. scene._removePendingData(loadingToken);
  51932. };
  51933. var progressHandler = function (event) {
  51934. if (onProgress) {
  51935. onProgress(event);
  51936. }
  51937. };
  51938. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51939. if (plugin.importMesh) {
  51940. var syncedPlugin = plugin;
  51941. var meshes = new Array();
  51942. var particleSystems = new Array();
  51943. var skeletons = new Array();
  51944. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51945. return;
  51946. }
  51947. if (onSuccess) {
  51948. // wrap onSuccess with try-catch to know if something went wrong.
  51949. try {
  51950. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51951. onSuccess(meshes, particleSystems, skeletons);
  51952. scene._removePendingData(loadingToken);
  51953. }
  51954. catch (e) {
  51955. var message = 'Error in onSuccess callback.';
  51956. errorHandler(message, e);
  51957. }
  51958. }
  51959. }
  51960. else {
  51961. var asyncedPlugin = plugin;
  51962. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51963. if (onSuccess) {
  51964. try {
  51965. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51966. onSuccess(meshes, particleSystems, skeletons);
  51967. scene._removePendingData(loadingToken);
  51968. }
  51969. catch (e) {
  51970. var message = 'Error in onSuccess callback.';
  51971. errorHandler(message, e);
  51972. }
  51973. }
  51974. }, progressHandler, errorHandler);
  51975. }
  51976. }, progressHandler, errorHandler);
  51977. };
  51978. /**
  51979. * Load a scene
  51980. * @param rootUrl a string that defines the root url for scene and resources
  51981. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51982. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51983. * @param onSuccess a callback with the scene when import succeeds
  51984. * @param onProgress a callback with a progress event for each file being loaded
  51985. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51986. */
  51987. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51988. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51989. };
  51990. /**
  51991. * Append a scene
  51992. * @param rootUrl a string that defines the root url for scene and resources
  51993. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51994. * @param scene is the instance of BABYLON.Scene to append to
  51995. * @param onSuccess a callback with the scene when import succeeds
  51996. * @param onProgress a callback with a progress event for each file being loaded
  51997. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51998. */
  51999. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  52000. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52001. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52002. return;
  52003. }
  52004. if (SceneLoader.ShowLoadingScreen) {
  52005. scene.getEngine().displayLoadingUI();
  52006. }
  52007. var loadingToken = {};
  52008. scene._addPendingData(loadingToken);
  52009. var errorHandler = function (message, exception) {
  52010. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52011. if (onError) {
  52012. onError(scene, errorMessage, exception);
  52013. }
  52014. else {
  52015. BABYLON.Tools.Error(errorMessage);
  52016. // should the exception be thrown?
  52017. }
  52018. scene._removePendingData(loadingToken);
  52019. scene.getEngine().hideLoadingUI();
  52020. };
  52021. var progressHandler = function (event) {
  52022. if (onProgress) {
  52023. onProgress(event);
  52024. }
  52025. };
  52026. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52027. if (plugin.load) {
  52028. var syncedPlugin = plugin;
  52029. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52030. return;
  52031. }
  52032. if (onSuccess) {
  52033. try {
  52034. onSuccess(scene);
  52035. }
  52036. catch (e) {
  52037. errorHandler("Error in onSuccess callback", e);
  52038. }
  52039. }
  52040. scene.loadingPluginName = plugin.name;
  52041. scene._removePendingData(loadingToken);
  52042. }
  52043. else {
  52044. var asyncedPlugin = plugin;
  52045. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52046. if (onSuccess) {
  52047. onSuccess(scene);
  52048. }
  52049. scene.loadingPluginName = plugin.name;
  52050. scene._removePendingData(loadingToken);
  52051. }, progressHandler, errorHandler);
  52052. }
  52053. if (SceneLoader.ShowLoadingScreen) {
  52054. scene.executeWhenReady(function () {
  52055. scene.getEngine().hideLoadingUI();
  52056. });
  52057. }
  52058. }, progressHandler, errorHandler);
  52059. };
  52060. // Flags
  52061. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52062. SceneLoader._ShowLoadingScreen = true;
  52063. SceneLoader._CleanBoneMatrixWeights = false;
  52064. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52065. // Members
  52066. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52067. SceneLoader._registeredPlugins = {};
  52068. return SceneLoader;
  52069. }());
  52070. BABYLON.SceneLoader = SceneLoader;
  52071. ;
  52072. })(BABYLON || (BABYLON = {}));
  52073. //# sourceMappingURL=babylon.sceneLoader.js.map
  52074. var BABYLON;
  52075. (function (BABYLON) {
  52076. var Internals;
  52077. (function (Internals) {
  52078. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52079. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52080. var parsedMaterial = parsedData.materials[index];
  52081. if (parsedMaterial.id === id) {
  52082. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52083. }
  52084. }
  52085. return null;
  52086. };
  52087. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52088. for (var i in names) {
  52089. if (mesh.name === names[i]) {
  52090. hierarchyIds.push(mesh.id);
  52091. return true;
  52092. }
  52093. }
  52094. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52095. hierarchyIds.push(mesh.id);
  52096. return true;
  52097. }
  52098. return false;
  52099. };
  52100. var logOperation = function (operation, producer) {
  52101. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52102. };
  52103. BABYLON.SceneLoader.RegisterPlugin({
  52104. name: "babylon.js",
  52105. extensions: ".babylon",
  52106. canDirectLoad: function (data) {
  52107. if (data.indexOf("babylon") !== -1) {
  52108. return true;
  52109. }
  52110. return false;
  52111. },
  52112. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52113. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52114. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52115. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52116. // and avoid problems with multiple concurrent .babylon loads.
  52117. var log = "importMesh has failed JSON parse";
  52118. try {
  52119. var parsedData = JSON.parse(data);
  52120. log = "";
  52121. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52122. if (!meshesNames) {
  52123. meshesNames = null;
  52124. }
  52125. else if (!Array.isArray(meshesNames)) {
  52126. meshesNames = [meshesNames];
  52127. }
  52128. var hierarchyIds = new Array();
  52129. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52130. var loadedSkeletonsIds = [];
  52131. var loadedMaterialsIds = [];
  52132. var index;
  52133. var cache;
  52134. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52135. var parsedMesh = parsedData.meshes[index];
  52136. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52137. if (meshesNames !== null) {
  52138. // Remove found mesh name from list.
  52139. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52140. }
  52141. //Geometry?
  52142. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52143. //does the file contain geometries?
  52144. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52145. //find the correct geometry and add it to the scene
  52146. var found = false;
  52147. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52148. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52149. return;
  52150. }
  52151. else {
  52152. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52153. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52154. switch (geometryType) {
  52155. case "boxes":
  52156. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52157. break;
  52158. case "spheres":
  52159. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52160. break;
  52161. case "cylinders":
  52162. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52163. break;
  52164. case "toruses":
  52165. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52166. break;
  52167. case "grounds":
  52168. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52169. break;
  52170. case "planes":
  52171. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52172. break;
  52173. case "torusKnots":
  52174. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52175. break;
  52176. case "vertexData":
  52177. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52178. break;
  52179. }
  52180. found = true;
  52181. }
  52182. });
  52183. }
  52184. });
  52185. if (found === false) {
  52186. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52187. }
  52188. }
  52189. }
  52190. // Material ?
  52191. if (parsedMesh.materialId) {
  52192. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52193. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52194. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52195. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52196. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52197. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52198. var subMatId = parsedMultiMaterial.materials[matIndex];
  52199. loadedMaterialsIds.push(subMatId);
  52200. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52201. log += "\n\tMaterial " + mat.toString(fullDetails);
  52202. }
  52203. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52204. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52205. materialFound = true;
  52206. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52207. break;
  52208. }
  52209. }
  52210. }
  52211. if (materialFound === false) {
  52212. loadedMaterialsIds.push(parsedMesh.materialId);
  52213. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52214. if (!mat) {
  52215. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52216. }
  52217. else {
  52218. log += "\n\tMaterial " + mat.toString(fullDetails);
  52219. }
  52220. }
  52221. }
  52222. // Skeleton ?
  52223. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52224. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52225. if (skeletonAlreadyLoaded === false) {
  52226. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52227. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52228. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52229. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52230. skeletons.push(skeleton);
  52231. loadedSkeletonsIds.push(parsedSkeleton.id);
  52232. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52233. }
  52234. }
  52235. }
  52236. }
  52237. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52238. meshes.push(mesh);
  52239. log += "\n\tMesh " + mesh.toString(fullDetails);
  52240. }
  52241. }
  52242. // Connecting parents
  52243. var currentMesh;
  52244. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52245. currentMesh = scene.meshes[index];
  52246. if (currentMesh._waitingParentId) {
  52247. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52248. currentMesh._waitingParentId = null;
  52249. }
  52250. }
  52251. // freeze and compute world matrix application
  52252. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52253. currentMesh = scene.meshes[index];
  52254. if (currentMesh._waitingFreezeWorldMatrix) {
  52255. currentMesh.freezeWorldMatrix();
  52256. currentMesh._waitingFreezeWorldMatrix = null;
  52257. }
  52258. else {
  52259. currentMesh.computeWorldMatrix(true);
  52260. }
  52261. }
  52262. }
  52263. // Particles
  52264. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52265. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52266. var parsedParticleSystem = parsedData.particleSystems[index];
  52267. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52268. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52269. }
  52270. }
  52271. }
  52272. return true;
  52273. }
  52274. catch (err) {
  52275. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52276. if (onError) {
  52277. onError(msg, err);
  52278. }
  52279. else {
  52280. BABYLON.Tools.Log(msg);
  52281. throw err;
  52282. }
  52283. }
  52284. finally {
  52285. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52286. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52287. }
  52288. }
  52289. return false;
  52290. },
  52291. load: function (scene, data, rootUrl, onError) {
  52292. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52293. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52294. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52295. // and avoid problems with multiple concurrent .babylon loads.
  52296. var log = "importScene has failed JSON parse";
  52297. try {
  52298. var parsedData = JSON.parse(data);
  52299. log = "";
  52300. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52301. // Scene
  52302. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52303. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52304. }
  52305. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52306. scene.autoClear = parsedData.autoClear;
  52307. }
  52308. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52309. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52310. }
  52311. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52312. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52313. }
  52314. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52315. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52316. }
  52317. // Fog
  52318. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52319. scene.fogMode = parsedData.fogMode;
  52320. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52321. scene.fogStart = parsedData.fogStart;
  52322. scene.fogEnd = parsedData.fogEnd;
  52323. scene.fogDensity = parsedData.fogDensity;
  52324. log += "\tFog mode for scene: ";
  52325. switch (scene.fogMode) {
  52326. // getters not compiling, so using hardcoded
  52327. case 1:
  52328. log += "exp\n";
  52329. break;
  52330. case 2:
  52331. log += "exp2\n";
  52332. break;
  52333. case 3:
  52334. log += "linear\n";
  52335. break;
  52336. }
  52337. }
  52338. //Physics
  52339. if (parsedData.physicsEnabled) {
  52340. var physicsPlugin;
  52341. if (parsedData.physicsEngine === "cannon") {
  52342. physicsPlugin = new BABYLON.CannonJSPlugin();
  52343. }
  52344. else if (parsedData.physicsEngine === "oimo") {
  52345. physicsPlugin = new BABYLON.OimoJSPlugin();
  52346. }
  52347. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52348. //else - default engine, which is currently oimo
  52349. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52350. scene.enablePhysics(physicsGravity, physicsPlugin);
  52351. }
  52352. // Metadata
  52353. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52354. scene.metadata = parsedData.metadata;
  52355. }
  52356. //collisions, if defined. otherwise, default is true
  52357. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52358. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52359. }
  52360. scene.workerCollisions = !!parsedData.workerCollisions;
  52361. var index;
  52362. var cache;
  52363. // Lights
  52364. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52365. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52366. var parsedLight = parsedData.lights[index];
  52367. var light = BABYLON.Light.Parse(parsedLight, scene);
  52368. if (light) {
  52369. log += (index === 0 ? "\n\tLights:" : "");
  52370. log += "\n\t\t" + light.toString(fullDetails);
  52371. }
  52372. }
  52373. }
  52374. // Animations
  52375. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52376. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52377. var parsedAnimation = parsedData.animations[index];
  52378. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52379. scene.animations.push(animation);
  52380. log += (index === 0 ? "\n\tAnimations:" : "");
  52381. log += "\n\t\t" + animation.toString(fullDetails);
  52382. }
  52383. }
  52384. if (parsedData.autoAnimate) {
  52385. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52386. }
  52387. // Materials
  52388. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52389. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52390. var parsedMaterial = parsedData.materials[index];
  52391. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52392. log += (index === 0 ? "\n\tMaterials:" : "");
  52393. log += "\n\t\t" + mat.toString(fullDetails);
  52394. }
  52395. }
  52396. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52397. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52398. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52399. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52400. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52401. log += "\n\t\t" + mmat.toString(fullDetails);
  52402. }
  52403. }
  52404. // Morph targets
  52405. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52406. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52407. var managerData = _a[_i];
  52408. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52409. }
  52410. }
  52411. // Skeletons
  52412. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52413. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52414. var parsedSkeleton = parsedData.skeletons[index];
  52415. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52416. log += (index === 0 ? "\n\tSkeletons:" : "");
  52417. log += "\n\t\t" + skeleton.toString(fullDetails);
  52418. }
  52419. }
  52420. // Geometries
  52421. var geometries = parsedData.geometries;
  52422. if (geometries !== undefined && geometries !== null) {
  52423. // Boxes
  52424. var boxes = geometries.boxes;
  52425. if (boxes !== undefined && boxes !== null) {
  52426. for (index = 0, cache = boxes.length; index < cache; index++) {
  52427. var parsedBox = boxes[index];
  52428. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52429. }
  52430. }
  52431. // Spheres
  52432. var spheres = geometries.spheres;
  52433. if (spheres !== undefined && spheres !== null) {
  52434. for (index = 0, cache = spheres.length; index < cache; index++) {
  52435. var parsedSphere = spheres[index];
  52436. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52437. }
  52438. }
  52439. // Cylinders
  52440. var cylinders = geometries.cylinders;
  52441. if (cylinders !== undefined && cylinders !== null) {
  52442. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52443. var parsedCylinder = cylinders[index];
  52444. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52445. }
  52446. }
  52447. // Toruses
  52448. var toruses = geometries.toruses;
  52449. if (toruses !== undefined && toruses !== null) {
  52450. for (index = 0, cache = toruses.length; index < cache; index++) {
  52451. var parsedTorus = toruses[index];
  52452. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52453. }
  52454. }
  52455. // Grounds
  52456. var grounds = geometries.grounds;
  52457. if (grounds !== undefined && grounds !== null) {
  52458. for (index = 0, cache = grounds.length; index < cache; index++) {
  52459. var parsedGround = grounds[index];
  52460. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52461. }
  52462. }
  52463. // Planes
  52464. var planes = geometries.planes;
  52465. if (planes !== undefined && planes !== null) {
  52466. for (index = 0, cache = planes.length; index < cache; index++) {
  52467. var parsedPlane = planes[index];
  52468. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52469. }
  52470. }
  52471. // TorusKnots
  52472. var torusKnots = geometries.torusKnots;
  52473. if (torusKnots !== undefined && torusKnots !== null) {
  52474. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52475. var parsedTorusKnot = torusKnots[index];
  52476. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52477. }
  52478. }
  52479. // VertexData
  52480. var vertexData = geometries.vertexData;
  52481. if (vertexData !== undefined && vertexData !== null) {
  52482. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52483. var parsedVertexData = vertexData[index];
  52484. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52485. }
  52486. }
  52487. }
  52488. // Meshes
  52489. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52490. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52491. var parsedMesh = parsedData.meshes[index];
  52492. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52493. log += (index === 0 ? "\n\tMeshes:" : "");
  52494. log += "\n\t\t" + mesh.toString(fullDetails);
  52495. }
  52496. }
  52497. // Cameras
  52498. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52499. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52500. var parsedCamera = parsedData.cameras[index];
  52501. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52502. log += (index === 0 ? "\n\tCameras:" : "");
  52503. log += "\n\t\t" + camera.toString(fullDetails);
  52504. }
  52505. }
  52506. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52507. scene.setActiveCameraByID(parsedData.activeCameraID);
  52508. }
  52509. // Browsing all the graph to connect the dots
  52510. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52511. var camera = scene.cameras[index];
  52512. if (camera._waitingParentId) {
  52513. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52514. camera._waitingParentId = null;
  52515. }
  52516. }
  52517. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52518. var light_1 = scene.lights[index];
  52519. if (light_1 && light_1._waitingParentId) {
  52520. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52521. light_1._waitingParentId = null;
  52522. }
  52523. }
  52524. // Sounds
  52525. var loadedSounds = [];
  52526. var loadedSound;
  52527. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52528. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52529. var parsedSound = parsedData.sounds[index];
  52530. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52531. if (!parsedSound.url)
  52532. parsedSound.url = parsedSound.name;
  52533. if (!loadedSounds[parsedSound.url]) {
  52534. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52535. loadedSounds[parsedSound.url] = loadedSound;
  52536. }
  52537. else {
  52538. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52539. }
  52540. }
  52541. else {
  52542. new BABYLON.Sound(parsedSound.name, null, scene);
  52543. }
  52544. }
  52545. }
  52546. loadedSounds = [];
  52547. // Connect parents & children and parse actions
  52548. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52549. var mesh = scene.meshes[index];
  52550. if (mesh._waitingParentId) {
  52551. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52552. mesh._waitingParentId = null;
  52553. }
  52554. if (mesh._waitingActions) {
  52555. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52556. mesh._waitingActions = null;
  52557. }
  52558. }
  52559. // freeze world matrix application
  52560. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52561. var currentMesh = scene.meshes[index];
  52562. if (currentMesh._waitingFreezeWorldMatrix) {
  52563. currentMesh.freezeWorldMatrix();
  52564. currentMesh._waitingFreezeWorldMatrix = null;
  52565. }
  52566. else {
  52567. currentMesh.computeWorldMatrix(true);
  52568. }
  52569. }
  52570. // Particles Systems
  52571. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52572. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52573. var parsedParticleSystem = parsedData.particleSystems[index];
  52574. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52575. }
  52576. }
  52577. // Environment texture
  52578. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52579. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52580. if (parsedData.createDefaultSkybox === true) {
  52581. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52582. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52583. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52584. }
  52585. }
  52586. // Lens flares
  52587. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52588. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52589. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52590. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52591. }
  52592. }
  52593. // Shadows
  52594. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52595. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52596. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52597. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52598. }
  52599. }
  52600. // Lights exclusions / inclusions
  52601. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52602. var light_2 = scene.lights[index];
  52603. // Excluded check
  52604. if (light_2._excludedMeshesIds.length > 0) {
  52605. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52606. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52607. if (excludedMesh) {
  52608. light_2.excludedMeshes.push(excludedMesh);
  52609. }
  52610. }
  52611. light_2._excludedMeshesIds = [];
  52612. }
  52613. // Included check
  52614. if (light_2._includedOnlyMeshesIds.length > 0) {
  52615. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52616. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52617. if (includedOnlyMesh) {
  52618. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52619. }
  52620. }
  52621. light_2._includedOnlyMeshesIds = [];
  52622. }
  52623. }
  52624. // Actions (scene)
  52625. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52626. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52627. }
  52628. // Finish
  52629. return true;
  52630. }
  52631. catch (err) {
  52632. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52633. if (onError) {
  52634. onError(msg, err);
  52635. }
  52636. else {
  52637. BABYLON.Tools.Log(msg);
  52638. throw err;
  52639. }
  52640. }
  52641. finally {
  52642. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52643. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52644. }
  52645. }
  52646. return false;
  52647. }
  52648. });
  52649. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52650. })(BABYLON || (BABYLON = {}));
  52651. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52652. var BABYLON;
  52653. (function (BABYLON) {
  52654. var FilesInput = /** @class */ (function () {
  52655. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52656. this.onProcessFileCallback = function () { return true; };
  52657. this._engine = engine;
  52658. this._currentScene = scene;
  52659. this._sceneLoadedCallback = sceneLoadedCallback;
  52660. this._progressCallback = progressCallback;
  52661. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52662. this._textureLoadingCallback = textureLoadingCallback;
  52663. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52664. this._onReloadCallback = onReloadCallback;
  52665. this._errorCallback = errorCallback;
  52666. }
  52667. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52668. var _this = this;
  52669. if (elementToMonitor) {
  52670. this._elementToMonitor = elementToMonitor;
  52671. this._dragEnterHandler = function (e) { _this.drag(e); };
  52672. this._dragOverHandler = function (e) { _this.drag(e); };
  52673. this._dropHandler = function (e) { _this.drop(e); };
  52674. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52675. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52676. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52677. }
  52678. };
  52679. FilesInput.prototype.dispose = function () {
  52680. if (!this._elementToMonitor) {
  52681. return;
  52682. }
  52683. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52684. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52685. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52686. };
  52687. FilesInput.prototype.renderFunction = function () {
  52688. if (this._additionalRenderLoopLogicCallback) {
  52689. this._additionalRenderLoopLogicCallback();
  52690. }
  52691. if (this._currentScene) {
  52692. if (this._textureLoadingCallback) {
  52693. var remaining = this._currentScene.getWaitingItemsCount();
  52694. if (remaining > 0) {
  52695. this._textureLoadingCallback(remaining);
  52696. }
  52697. }
  52698. this._currentScene.render();
  52699. }
  52700. };
  52701. FilesInput.prototype.drag = function (e) {
  52702. e.stopPropagation();
  52703. e.preventDefault();
  52704. };
  52705. FilesInput.prototype.drop = function (eventDrop) {
  52706. eventDrop.stopPropagation();
  52707. eventDrop.preventDefault();
  52708. this.loadFiles(eventDrop);
  52709. };
  52710. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52711. var _this = this;
  52712. var reader = folder.createReader();
  52713. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52714. reader.readEntries(function (entries) {
  52715. remaining.count += entries.length;
  52716. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52717. var entry = entries_1[_i];
  52718. if (entry.isFile) {
  52719. entry.file(function (file) {
  52720. file.correctName = relativePath + file.name;
  52721. files.push(file);
  52722. if (--remaining.count === 0) {
  52723. callback();
  52724. }
  52725. });
  52726. }
  52727. else if (entry.isDirectory) {
  52728. _this._traverseFolder(entry, files, remaining, callback);
  52729. }
  52730. }
  52731. if (--remaining.count) {
  52732. callback();
  52733. }
  52734. });
  52735. };
  52736. FilesInput.prototype._processFiles = function (files) {
  52737. var skippedFiles = 0;
  52738. for (var i = 0; i < files.length; i++) {
  52739. var name = files[i].correctName.toLowerCase();
  52740. var extension = name.split('.').pop();
  52741. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52742. skippedFiles++;
  52743. continue;
  52744. }
  52745. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52746. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52747. this._sceneFileToLoad = files[i];
  52748. }
  52749. else {
  52750. FilesInput.FilesToLoad[name] = files[i];
  52751. }
  52752. }
  52753. if (this._onReloadCallback) {
  52754. this._onReloadCallback(this._sceneFileToLoad);
  52755. }
  52756. else if (skippedFiles < files.length) {
  52757. this.reload();
  52758. }
  52759. };
  52760. FilesInput.prototype.loadFiles = function (event) {
  52761. var _this = this;
  52762. if (this._startingProcessingFilesCallback)
  52763. this._startingProcessingFilesCallback();
  52764. // Handling data transfer via drag'n'drop
  52765. if (event && event.dataTransfer && event.dataTransfer.files) {
  52766. this._filesToLoad = event.dataTransfer.files;
  52767. }
  52768. // Handling files from input files
  52769. if (event && event.target && event.target.files) {
  52770. this._filesToLoad = event.target.files;
  52771. }
  52772. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52773. var files_1 = new Array();
  52774. var folders = [];
  52775. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52776. for (var i = 0; i < this._filesToLoad.length; i++) {
  52777. var fileToLoad = this._filesToLoad[i];
  52778. var name_1 = fileToLoad.name.toLowerCase();
  52779. var entry = void 0;
  52780. fileToLoad.correctName = name_1;
  52781. if (items) {
  52782. var item = items[i];
  52783. if (item.getAsEntry) {
  52784. entry = item.getAsEntry();
  52785. }
  52786. else if (item.webkitGetAsEntry) {
  52787. entry = item.webkitGetAsEntry();
  52788. }
  52789. }
  52790. if (!entry) {
  52791. files_1.push(fileToLoad);
  52792. }
  52793. else {
  52794. if (entry.isDirectory) {
  52795. folders.push(entry);
  52796. }
  52797. else {
  52798. files_1.push(fileToLoad);
  52799. }
  52800. }
  52801. }
  52802. if (folders.length === 0) {
  52803. this._processFiles(files_1);
  52804. }
  52805. else {
  52806. var remaining = { count: folders.length };
  52807. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52808. var folder = folders_1[_i];
  52809. this._traverseFolder(folder, files_1, remaining, function () {
  52810. _this._processFiles(files_1);
  52811. });
  52812. }
  52813. }
  52814. }
  52815. };
  52816. FilesInput.prototype.reload = function () {
  52817. var _this = this;
  52818. // If a ".babylon" file has been provided
  52819. if (this._sceneFileToLoad) {
  52820. if (this._currentScene) {
  52821. if (BABYLON.Tools.errorsCount > 0) {
  52822. BABYLON.Tools.ClearLogCache();
  52823. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52824. }
  52825. this._engine.stopRenderLoop();
  52826. this._currentScene.dispose();
  52827. }
  52828. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52829. _this._currentScene = newScene;
  52830. if (_this._sceneLoadedCallback) {
  52831. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52832. }
  52833. // Wait for textures and shaders to be ready
  52834. _this._currentScene.executeWhenReady(function () {
  52835. _this._engine.runRenderLoop(function () {
  52836. _this.renderFunction();
  52837. });
  52838. });
  52839. }, function (progress) {
  52840. if (_this._progressCallback) {
  52841. _this._progressCallback(progress);
  52842. }
  52843. }, function (scene, message) {
  52844. _this._currentScene = scene;
  52845. if (_this._errorCallback) {
  52846. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52847. }
  52848. });
  52849. }
  52850. else {
  52851. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52852. }
  52853. };
  52854. FilesInput.FilesToLoad = {};
  52855. return FilesInput;
  52856. }());
  52857. BABYLON.FilesInput = FilesInput;
  52858. })(BABYLON || (BABYLON = {}));
  52859. //# sourceMappingURL=babylon.filesInput.js.map
  52860. var BABYLON;
  52861. (function (BABYLON) {
  52862. /**
  52863. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52864. * The underlying implementation relies on an associative array to ensure the best performances.
  52865. * The value can be anything including 'null' but except 'undefined'
  52866. */
  52867. var StringDictionary = /** @class */ (function () {
  52868. function StringDictionary() {
  52869. this._count = 0;
  52870. this._data = {};
  52871. }
  52872. /**
  52873. * This will clear this dictionary and copy the content from the 'source' one.
  52874. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52875. * @param source the dictionary to take the content from and copy to this dictionary
  52876. */
  52877. StringDictionary.prototype.copyFrom = function (source) {
  52878. var _this = this;
  52879. this.clear();
  52880. source.forEach(function (t, v) { return _this.add(t, v); });
  52881. };
  52882. /**
  52883. * Get a value based from its key
  52884. * @param key the given key to get the matching value from
  52885. * @return the value if found, otherwise undefined is returned
  52886. */
  52887. StringDictionary.prototype.get = function (key) {
  52888. var val = this._data[key];
  52889. if (val !== undefined) {
  52890. return val;
  52891. }
  52892. return undefined;
  52893. };
  52894. /**
  52895. * Get a value from its key or add it if it doesn't exist.
  52896. * This method will ensure you that a given key/data will be present in the dictionary.
  52897. * @param key the given key to get the matching value from
  52898. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52899. * The factory will only be invoked if there's no data for the given key.
  52900. * @return the value corresponding to the key.
  52901. */
  52902. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52903. var val = this.get(key);
  52904. if (val !== undefined) {
  52905. return val;
  52906. }
  52907. val = factory(key);
  52908. if (val) {
  52909. this.add(key, val);
  52910. }
  52911. return val;
  52912. };
  52913. /**
  52914. * Get a value from its key if present in the dictionary otherwise add it
  52915. * @param key the key to get the value from
  52916. * @param val if there's no such key/value pair in the dictionary add it with this value
  52917. * @return the value corresponding to the key
  52918. */
  52919. StringDictionary.prototype.getOrAdd = function (key, val) {
  52920. var curVal = this.get(key);
  52921. if (curVal !== undefined) {
  52922. return curVal;
  52923. }
  52924. this.add(key, val);
  52925. return val;
  52926. };
  52927. /**
  52928. * Check if there's a given key in the dictionary
  52929. * @param key the key to check for
  52930. * @return true if the key is present, false otherwise
  52931. */
  52932. StringDictionary.prototype.contains = function (key) {
  52933. return this._data[key] !== undefined;
  52934. };
  52935. /**
  52936. * Add a new key and its corresponding value
  52937. * @param key the key to add
  52938. * @param value the value corresponding to the key
  52939. * @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
  52940. */
  52941. StringDictionary.prototype.add = function (key, value) {
  52942. if (this._data[key] !== undefined) {
  52943. return false;
  52944. }
  52945. this._data[key] = value;
  52946. ++this._count;
  52947. return true;
  52948. };
  52949. StringDictionary.prototype.set = function (key, value) {
  52950. if (this._data[key] === undefined) {
  52951. return false;
  52952. }
  52953. this._data[key] = value;
  52954. return true;
  52955. };
  52956. /**
  52957. * Get the element of the given key and remove it from the dictionary
  52958. * @param key
  52959. */
  52960. StringDictionary.prototype.getAndRemove = function (key) {
  52961. var val = this.get(key);
  52962. if (val !== undefined) {
  52963. delete this._data[key];
  52964. --this._count;
  52965. return val;
  52966. }
  52967. return null;
  52968. };
  52969. /**
  52970. * Remove a key/value from the dictionary.
  52971. * @param key the key to remove
  52972. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52973. */
  52974. StringDictionary.prototype.remove = function (key) {
  52975. if (this.contains(key)) {
  52976. delete this._data[key];
  52977. --this._count;
  52978. return true;
  52979. }
  52980. return false;
  52981. };
  52982. /**
  52983. * Clear the whole content of the dictionary
  52984. */
  52985. StringDictionary.prototype.clear = function () {
  52986. this._data = {};
  52987. this._count = 0;
  52988. };
  52989. Object.defineProperty(StringDictionary.prototype, "count", {
  52990. get: function () {
  52991. return this._count;
  52992. },
  52993. enumerable: true,
  52994. configurable: true
  52995. });
  52996. /**
  52997. * Execute a callback on each key/val of the dictionary.
  52998. * Note that you can remove any element in this dictionary in the callback implementation
  52999. * @param callback the callback to execute on a given key/value pair
  53000. */
  53001. StringDictionary.prototype.forEach = function (callback) {
  53002. for (var cur in this._data) {
  53003. var val = this._data[cur];
  53004. callback(cur, val);
  53005. }
  53006. };
  53007. /**
  53008. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53009. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53010. * Note that you can remove any element in this dictionary in the callback implementation
  53011. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53012. */
  53013. StringDictionary.prototype.first = function (callback) {
  53014. for (var cur in this._data) {
  53015. var val = this._data[cur];
  53016. var res = callback(cur, val);
  53017. if (res) {
  53018. return res;
  53019. }
  53020. }
  53021. return null;
  53022. };
  53023. return StringDictionary;
  53024. }());
  53025. BABYLON.StringDictionary = StringDictionary;
  53026. })(BABYLON || (BABYLON = {}));
  53027. //# sourceMappingURL=babylon.stringDictionary.js.map
  53028. var BABYLON;
  53029. (function (BABYLON) {
  53030. var Tags = /** @class */ (function () {
  53031. function Tags() {
  53032. }
  53033. Tags.EnableFor = function (obj) {
  53034. obj._tags = obj._tags || {};
  53035. obj.hasTags = function () {
  53036. return Tags.HasTags(obj);
  53037. };
  53038. obj.addTags = function (tagsString) {
  53039. return Tags.AddTagsTo(obj, tagsString);
  53040. };
  53041. obj.removeTags = function (tagsString) {
  53042. return Tags.RemoveTagsFrom(obj, tagsString);
  53043. };
  53044. obj.matchesTagsQuery = function (tagsQuery) {
  53045. return Tags.MatchesQuery(obj, tagsQuery);
  53046. };
  53047. };
  53048. Tags.DisableFor = function (obj) {
  53049. delete obj._tags;
  53050. delete obj.hasTags;
  53051. delete obj.addTags;
  53052. delete obj.removeTags;
  53053. delete obj.matchesTagsQuery;
  53054. };
  53055. Tags.HasTags = function (obj) {
  53056. if (!obj._tags) {
  53057. return false;
  53058. }
  53059. return !BABYLON.Tools.IsEmpty(obj._tags);
  53060. };
  53061. Tags.GetTags = function (obj, asString) {
  53062. if (asString === void 0) { asString = true; }
  53063. if (!obj._tags) {
  53064. return null;
  53065. }
  53066. if (asString) {
  53067. var tagsArray = [];
  53068. for (var tag in obj._tags) {
  53069. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53070. tagsArray.push(tag);
  53071. }
  53072. }
  53073. return tagsArray.join(" ");
  53074. }
  53075. else {
  53076. return obj._tags;
  53077. }
  53078. };
  53079. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53080. // a tag cannot start with '||', '&&', and '!'
  53081. // it cannot contain whitespaces
  53082. Tags.AddTagsTo = function (obj, tagsString) {
  53083. if (!tagsString) {
  53084. return;
  53085. }
  53086. if (typeof tagsString !== "string") {
  53087. return;
  53088. }
  53089. var tags = tagsString.split(" ");
  53090. tags.forEach(function (tag, index, array) {
  53091. Tags._AddTagTo(obj, tag);
  53092. });
  53093. };
  53094. Tags._AddTagTo = function (obj, tag) {
  53095. tag = tag.trim();
  53096. if (tag === "" || tag === "true" || tag === "false") {
  53097. return;
  53098. }
  53099. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53100. return;
  53101. }
  53102. Tags.EnableFor(obj);
  53103. obj._tags[tag] = true;
  53104. };
  53105. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53106. if (!Tags.HasTags(obj)) {
  53107. return;
  53108. }
  53109. var tags = tagsString.split(" ");
  53110. for (var t in tags) {
  53111. Tags._RemoveTagFrom(obj, tags[t]);
  53112. }
  53113. };
  53114. Tags._RemoveTagFrom = function (obj, tag) {
  53115. delete obj._tags[tag];
  53116. };
  53117. Tags.MatchesQuery = function (obj, tagsQuery) {
  53118. if (tagsQuery === undefined) {
  53119. return true;
  53120. }
  53121. if (tagsQuery === "") {
  53122. return Tags.HasTags(obj);
  53123. }
  53124. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53125. };
  53126. return Tags;
  53127. }());
  53128. BABYLON.Tags = Tags;
  53129. })(BABYLON || (BABYLON = {}));
  53130. //# sourceMappingURL=babylon.tags.js.map
  53131. var BABYLON;
  53132. (function (BABYLON) {
  53133. var Internals;
  53134. (function (Internals) {
  53135. var AndOrNotEvaluator = /** @class */ (function () {
  53136. function AndOrNotEvaluator() {
  53137. }
  53138. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53139. if (!query.match(/\([^\(\)]*\)/g)) {
  53140. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53141. }
  53142. else {
  53143. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53144. // remove parenthesis
  53145. r = r.slice(1, r.length - 1);
  53146. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53147. });
  53148. }
  53149. if (query === "true") {
  53150. return true;
  53151. }
  53152. if (query === "false") {
  53153. return false;
  53154. }
  53155. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53156. };
  53157. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53158. evaluateCallback = evaluateCallback || (function (r) {
  53159. return r === "true" ? true : false;
  53160. });
  53161. var result;
  53162. var or = parenthesisContent.split("||");
  53163. for (var i in or) {
  53164. if (or.hasOwnProperty(i)) {
  53165. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53166. var and = ori.split("&&");
  53167. if (and.length > 1) {
  53168. for (var j = 0; j < and.length; ++j) {
  53169. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53170. if (andj !== "true" && andj !== "false") {
  53171. if (andj[0] === "!") {
  53172. result = !evaluateCallback(andj.substring(1));
  53173. }
  53174. else {
  53175. result = evaluateCallback(andj);
  53176. }
  53177. }
  53178. else {
  53179. result = andj === "true" ? true : false;
  53180. }
  53181. if (!result) {
  53182. ori = "false";
  53183. break;
  53184. }
  53185. }
  53186. }
  53187. if (result || ori === "true") {
  53188. result = true;
  53189. break;
  53190. }
  53191. // result equals false (or undefined)
  53192. if (ori !== "true" && ori !== "false") {
  53193. if (ori[0] === "!") {
  53194. result = !evaluateCallback(ori.substring(1));
  53195. }
  53196. else {
  53197. result = evaluateCallback(ori);
  53198. }
  53199. }
  53200. else {
  53201. result = ori === "true" ? true : false;
  53202. }
  53203. }
  53204. }
  53205. // the whole parenthesis scope is replaced by 'true' or 'false'
  53206. return result ? "true" : "false";
  53207. };
  53208. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53209. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53210. // remove whitespaces
  53211. r = r.replace(/[\s]/g, function () { return ""; });
  53212. return r.length % 2 ? "!" : "";
  53213. });
  53214. booleanString = booleanString.trim();
  53215. if (booleanString === "!true") {
  53216. booleanString = "false";
  53217. }
  53218. else if (booleanString === "!false") {
  53219. booleanString = "true";
  53220. }
  53221. return booleanString;
  53222. };
  53223. return AndOrNotEvaluator;
  53224. }());
  53225. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53227. })(BABYLON || (BABYLON = {}));
  53228. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53229. var BABYLON;
  53230. (function (BABYLON) {
  53231. var Database = /** @class */ (function () {
  53232. function Database(urlToScene, callbackManifestChecked) {
  53233. // Handling various flavors of prefixed version of IndexedDB
  53234. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53235. this.callbackManifestChecked = callbackManifestChecked;
  53236. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53237. this.db = null;
  53238. this._enableSceneOffline = false;
  53239. this._enableTexturesOffline = false;
  53240. this.manifestVersionFound = 0;
  53241. this.mustUpdateRessources = false;
  53242. this.hasReachedQuota = false;
  53243. if (!Database.IDBStorageEnabled) {
  53244. this.callbackManifestChecked(true);
  53245. }
  53246. else {
  53247. this.checkManifestFile();
  53248. }
  53249. }
  53250. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53251. get: function () {
  53252. return this._enableSceneOffline;
  53253. },
  53254. enumerable: true,
  53255. configurable: true
  53256. });
  53257. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53258. get: function () {
  53259. return this._enableTexturesOffline;
  53260. },
  53261. enumerable: true,
  53262. configurable: true
  53263. });
  53264. Database.prototype.checkManifestFile = function () {
  53265. var _this = this;
  53266. var noManifestFile = function () {
  53267. _this._enableSceneOffline = false;
  53268. _this._enableTexturesOffline = false;
  53269. _this.callbackManifestChecked(false);
  53270. };
  53271. var timeStampUsed = false;
  53272. var manifestURL = this.currentSceneUrl + ".manifest";
  53273. var xhr = new XMLHttpRequest();
  53274. if (navigator.onLine) {
  53275. // Adding a timestamp to by-pass browsers' cache
  53276. timeStampUsed = true;
  53277. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53278. }
  53279. xhr.open("GET", manifestURL, true);
  53280. xhr.addEventListener("load", function () {
  53281. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53282. try {
  53283. var manifestFile = JSON.parse(xhr.response);
  53284. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53285. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53286. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53287. _this.manifestVersionFound = manifestFile.version;
  53288. }
  53289. if (_this.callbackManifestChecked) {
  53290. _this.callbackManifestChecked(true);
  53291. }
  53292. }
  53293. catch (ex) {
  53294. noManifestFile();
  53295. }
  53296. }
  53297. else {
  53298. noManifestFile();
  53299. }
  53300. }, false);
  53301. xhr.addEventListener("error", function (event) {
  53302. if (timeStampUsed) {
  53303. timeStampUsed = false;
  53304. // Let's retry without the timeStamp
  53305. // It could fail when coupled with HTML5 Offline API
  53306. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53307. xhr.open("GET", retryManifestURL, true);
  53308. xhr.send();
  53309. }
  53310. else {
  53311. noManifestFile();
  53312. }
  53313. }, false);
  53314. try {
  53315. xhr.send();
  53316. }
  53317. catch (ex) {
  53318. BABYLON.Tools.Error("Error on XHR send request.");
  53319. this.callbackManifestChecked(false);
  53320. }
  53321. };
  53322. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53323. var _this = this;
  53324. var handleError = function () {
  53325. _this.isSupported = false;
  53326. if (errorCallback)
  53327. errorCallback();
  53328. };
  53329. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53330. // Your browser doesn't support IndexedDB
  53331. this.isSupported = false;
  53332. if (errorCallback)
  53333. errorCallback();
  53334. }
  53335. else {
  53336. // If the DB hasn't been opened or created yet
  53337. if (!this.db) {
  53338. this.hasReachedQuota = false;
  53339. this.isSupported = true;
  53340. var request = this.idbFactory.open("babylonjs", 1);
  53341. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53342. request.onerror = function (event) {
  53343. handleError();
  53344. };
  53345. // executes when a version change transaction cannot complete due to other active transactions
  53346. request.onblocked = function (event) {
  53347. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53348. handleError();
  53349. };
  53350. // DB has been opened successfully
  53351. request.onsuccess = function (event) {
  53352. _this.db = request.result;
  53353. successCallback();
  53354. };
  53355. // Initialization of the DB. Creating Scenes & Textures stores
  53356. request.onupgradeneeded = function (event) {
  53357. _this.db = (event.target).result;
  53358. if (_this.db) {
  53359. try {
  53360. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53361. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53362. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53363. }
  53364. catch (ex) {
  53365. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53366. handleError();
  53367. }
  53368. }
  53369. };
  53370. }
  53371. else {
  53372. if (successCallback)
  53373. successCallback();
  53374. }
  53375. }
  53376. };
  53377. Database.prototype.loadImageFromDB = function (url, image) {
  53378. var _this = this;
  53379. var completeURL = Database.ReturnFullUrlLocation(url);
  53380. var saveAndLoadImage = function () {
  53381. if (!_this.hasReachedQuota && _this.db !== null) {
  53382. // the texture is not yet in the DB, let's try to save it
  53383. _this._saveImageIntoDBAsync(completeURL, image);
  53384. }
  53385. else {
  53386. image.src = url;
  53387. }
  53388. };
  53389. if (!this.mustUpdateRessources) {
  53390. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53391. }
  53392. else {
  53393. saveAndLoadImage();
  53394. }
  53395. };
  53396. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53397. if (this.isSupported && this.db !== null) {
  53398. var texture;
  53399. var transaction = this.db.transaction(["textures"]);
  53400. transaction.onabort = function (event) {
  53401. image.src = url;
  53402. };
  53403. transaction.oncomplete = function (event) {
  53404. var blobTextureURL;
  53405. if (texture) {
  53406. var URL = window.URL || window.webkitURL;
  53407. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53408. image.onerror = function () {
  53409. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53410. image.src = url;
  53411. };
  53412. image.src = blobTextureURL;
  53413. }
  53414. else {
  53415. notInDBCallback();
  53416. }
  53417. };
  53418. var getRequest = transaction.objectStore("textures").get(url);
  53419. getRequest.onsuccess = function (event) {
  53420. texture = (event.target).result;
  53421. };
  53422. getRequest.onerror = function (event) {
  53423. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53424. image.src = url;
  53425. };
  53426. }
  53427. else {
  53428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53429. image.src = url;
  53430. }
  53431. };
  53432. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53433. var _this = this;
  53434. if (this.isSupported) {
  53435. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53436. var generateBlobUrl = function () {
  53437. var blobTextureURL;
  53438. if (blob) {
  53439. var URL = window.URL || window.webkitURL;
  53440. try {
  53441. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53442. }
  53443. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53444. catch (ex) {
  53445. blobTextureURL = URL.createObjectURL(blob);
  53446. }
  53447. }
  53448. if (blobTextureURL) {
  53449. image.src = blobTextureURL;
  53450. }
  53451. };
  53452. if (Database.IsUASupportingBlobStorage) {
  53453. var xhr = new XMLHttpRequest(), blob;
  53454. xhr.open("GET", url, true);
  53455. xhr.responseType = "blob";
  53456. xhr.addEventListener("load", function () {
  53457. if (xhr.status === 200 && _this.db) {
  53458. // Blob as response (XHR2)
  53459. blob = xhr.response;
  53460. var transaction = _this.db.transaction(["textures"], "readwrite");
  53461. // the transaction could abort because of a QuotaExceededError error
  53462. transaction.onabort = function (event) {
  53463. try {
  53464. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53465. var srcElement = (event.srcElement || event.target);
  53466. var error = srcElement.error;
  53467. if (error && error.name === "QuotaExceededError") {
  53468. _this.hasReachedQuota = true;
  53469. }
  53470. }
  53471. catch (ex) { }
  53472. generateBlobUrl();
  53473. };
  53474. transaction.oncomplete = function (event) {
  53475. generateBlobUrl();
  53476. };
  53477. var newTexture = { textureUrl: url, data: blob };
  53478. try {
  53479. // Put the blob into the dabase
  53480. var addRequest = transaction.objectStore("textures").put(newTexture);
  53481. addRequest.onsuccess = function (event) {
  53482. };
  53483. addRequest.onerror = function (event) {
  53484. generateBlobUrl();
  53485. };
  53486. }
  53487. catch (ex) {
  53488. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53489. if (ex.code === 25) {
  53490. Database.IsUASupportingBlobStorage = false;
  53491. }
  53492. image.src = url;
  53493. }
  53494. }
  53495. else {
  53496. image.src = url;
  53497. }
  53498. }, false);
  53499. xhr.addEventListener("error", function (event) {
  53500. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53501. image.src = url;
  53502. }, false);
  53503. xhr.send();
  53504. }
  53505. else {
  53506. image.src = url;
  53507. }
  53508. }
  53509. else {
  53510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53511. image.src = url;
  53512. }
  53513. };
  53514. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53515. var _this = this;
  53516. var updateVersion = function () {
  53517. // the version is not yet in the DB or we need to update it
  53518. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53519. };
  53520. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53521. };
  53522. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53523. var _this = this;
  53524. if (this.isSupported && this.db) {
  53525. var version;
  53526. try {
  53527. var transaction = this.db.transaction(["versions"]);
  53528. transaction.oncomplete = function (event) {
  53529. if (version) {
  53530. // If the version in the JSON file is > than the version in DB
  53531. if (_this.manifestVersionFound > version.data) {
  53532. _this.mustUpdateRessources = true;
  53533. updateInDBCallback();
  53534. }
  53535. else {
  53536. callback(version.data);
  53537. }
  53538. }
  53539. else {
  53540. _this.mustUpdateRessources = true;
  53541. updateInDBCallback();
  53542. }
  53543. };
  53544. transaction.onabort = function (event) {
  53545. callback(-1);
  53546. };
  53547. var getRequest = transaction.objectStore("versions").get(url);
  53548. getRequest.onsuccess = function (event) {
  53549. version = (event.target).result;
  53550. };
  53551. getRequest.onerror = function (event) {
  53552. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53553. callback(-1);
  53554. };
  53555. }
  53556. catch (ex) {
  53557. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53558. callback(-1);
  53559. }
  53560. }
  53561. else {
  53562. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53563. callback(-1);
  53564. }
  53565. };
  53566. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53567. var _this = this;
  53568. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53569. try {
  53570. // Open a transaction to the database
  53571. var transaction = this.db.transaction(["versions"], "readwrite");
  53572. // the transaction could abort because of a QuotaExceededError error
  53573. transaction.onabort = function (event) {
  53574. try {
  53575. var error = event.srcElement['error'];
  53576. if (error && error.name === "QuotaExceededError") {
  53577. _this.hasReachedQuota = true;
  53578. }
  53579. }
  53580. catch (ex) { }
  53581. callback(-1);
  53582. };
  53583. transaction.oncomplete = function (event) {
  53584. callback(_this.manifestVersionFound);
  53585. };
  53586. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53587. // Put the scene into the database
  53588. var addRequest = transaction.objectStore("versions").put(newVersion);
  53589. addRequest.onsuccess = function (event) {
  53590. };
  53591. addRequest.onerror = function (event) {
  53592. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53593. };
  53594. }
  53595. catch (ex) {
  53596. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53597. callback(-1);
  53598. }
  53599. }
  53600. else {
  53601. callback(-1);
  53602. }
  53603. };
  53604. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53605. var _this = this;
  53606. var completeUrl = Database.ReturnFullUrlLocation(url);
  53607. var saveAndLoadFile = function () {
  53608. // the scene is not yet in the DB, let's try to save it
  53609. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53610. };
  53611. this._checkVersionFromDB(completeUrl, function (version) {
  53612. if (version !== -1) {
  53613. if (!_this.mustUpdateRessources) {
  53614. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53615. }
  53616. else {
  53617. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53618. }
  53619. }
  53620. else {
  53621. if (errorCallback) {
  53622. errorCallback();
  53623. }
  53624. }
  53625. });
  53626. };
  53627. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53628. if (this.isSupported && this.db) {
  53629. var targetStore;
  53630. if (url.indexOf(".babylon") !== -1) {
  53631. targetStore = "scenes";
  53632. }
  53633. else {
  53634. targetStore = "textures";
  53635. }
  53636. var file;
  53637. var transaction = this.db.transaction([targetStore]);
  53638. transaction.oncomplete = function (event) {
  53639. if (file) {
  53640. callback(file.data);
  53641. }
  53642. else {
  53643. notInDBCallback();
  53644. }
  53645. };
  53646. transaction.onabort = function (event) {
  53647. notInDBCallback();
  53648. };
  53649. var getRequest = transaction.objectStore(targetStore).get(url);
  53650. getRequest.onsuccess = function (event) {
  53651. file = (event.target).result;
  53652. };
  53653. getRequest.onerror = function (event) {
  53654. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53655. notInDBCallback();
  53656. };
  53657. }
  53658. else {
  53659. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53660. callback();
  53661. }
  53662. };
  53663. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53664. var _this = this;
  53665. if (this.isSupported) {
  53666. var targetStore;
  53667. if (url.indexOf(".babylon") !== -1) {
  53668. targetStore = "scenes";
  53669. }
  53670. else {
  53671. targetStore = "textures";
  53672. }
  53673. // Create XHR
  53674. var xhr = new XMLHttpRequest();
  53675. var fileData;
  53676. xhr.open("GET", url, true);
  53677. if (useArrayBuffer) {
  53678. xhr.responseType = "arraybuffer";
  53679. }
  53680. if (progressCallback) {
  53681. xhr.onprogress = progressCallback;
  53682. }
  53683. xhr.addEventListener("load", function () {
  53684. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53685. // Blob as response (XHR2)
  53686. //fileData = xhr.responseText;
  53687. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53688. if (!_this.hasReachedQuota && _this.db) {
  53689. // Open a transaction to the database
  53690. var transaction = _this.db.transaction([targetStore], "readwrite");
  53691. // the transaction could abort because of a QuotaExceededError error
  53692. transaction.onabort = function (event) {
  53693. try {
  53694. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53695. var error = event.srcElement['error'];
  53696. if (error && error.name === "QuotaExceededError") {
  53697. _this.hasReachedQuota = true;
  53698. }
  53699. }
  53700. catch (ex) { }
  53701. callback(fileData);
  53702. };
  53703. transaction.oncomplete = function (event) {
  53704. callback(fileData);
  53705. };
  53706. var newFile;
  53707. if (targetStore === "scenes") {
  53708. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53709. }
  53710. else {
  53711. newFile = { textureUrl: url, data: fileData };
  53712. }
  53713. try {
  53714. // Put the scene into the database
  53715. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53716. addRequest.onsuccess = function (event) {
  53717. };
  53718. addRequest.onerror = function (event) {
  53719. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53720. };
  53721. }
  53722. catch (ex) {
  53723. callback(fileData);
  53724. }
  53725. }
  53726. else {
  53727. callback(fileData);
  53728. }
  53729. }
  53730. else {
  53731. callback();
  53732. }
  53733. }, false);
  53734. xhr.addEventListener("error", function (event) {
  53735. BABYLON.Tools.Error("error on XHR request.");
  53736. callback();
  53737. }, false);
  53738. xhr.send();
  53739. }
  53740. else {
  53741. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53742. callback();
  53743. }
  53744. };
  53745. Database.IsUASupportingBlobStorage = true;
  53746. Database.IDBStorageEnabled = true;
  53747. Database.parseURL = function (url) {
  53748. var a = document.createElement('a');
  53749. a.href = url;
  53750. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53751. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53752. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53753. return absLocation;
  53754. };
  53755. Database.ReturnFullUrlLocation = function (url) {
  53756. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53757. return (Database.parseURL(window.location.href) + url);
  53758. }
  53759. else {
  53760. return url;
  53761. }
  53762. };
  53763. return Database;
  53764. }());
  53765. BABYLON.Database = Database;
  53766. })(BABYLON || (BABYLON = {}));
  53767. //# sourceMappingURL=babylon.database.js.map
  53768. var BABYLON;
  53769. (function (BABYLON) {
  53770. var FresnelParameters = /** @class */ (function () {
  53771. function FresnelParameters() {
  53772. this._isEnabled = true;
  53773. this.leftColor = BABYLON.Color3.White();
  53774. this.rightColor = BABYLON.Color3.Black();
  53775. this.bias = 0;
  53776. this.power = 1;
  53777. }
  53778. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53779. get: function () {
  53780. return this._isEnabled;
  53781. },
  53782. set: function (value) {
  53783. if (this._isEnabled === value) {
  53784. return;
  53785. }
  53786. this._isEnabled = value;
  53787. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53788. },
  53789. enumerable: true,
  53790. configurable: true
  53791. });
  53792. FresnelParameters.prototype.clone = function () {
  53793. var newFresnelParameters = new FresnelParameters();
  53794. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53795. return newFresnelParameters;
  53796. };
  53797. FresnelParameters.prototype.serialize = function () {
  53798. var serializationObject = {};
  53799. serializationObject.isEnabled = this.isEnabled;
  53800. serializationObject.leftColor = this.leftColor;
  53801. serializationObject.rightColor = this.rightColor;
  53802. serializationObject.bias = this.bias;
  53803. serializationObject.power = this.power;
  53804. return serializationObject;
  53805. };
  53806. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53807. var fresnelParameters = new FresnelParameters();
  53808. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53809. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53810. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53811. fresnelParameters.bias = parsedFresnelParameters.bias;
  53812. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53813. return fresnelParameters;
  53814. };
  53815. return FresnelParameters;
  53816. }());
  53817. BABYLON.FresnelParameters = FresnelParameters;
  53818. })(BABYLON || (BABYLON = {}));
  53819. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53820. var BABYLON;
  53821. (function (BABYLON) {
  53822. var MultiMaterial = /** @class */ (function (_super) {
  53823. __extends(MultiMaterial, _super);
  53824. function MultiMaterial(name, scene) {
  53825. var _this = _super.call(this, name, scene, true) || this;
  53826. scene.multiMaterials.push(_this);
  53827. _this.subMaterials = new Array();
  53828. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53829. return _this;
  53830. }
  53831. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53832. get: function () {
  53833. return this._subMaterials;
  53834. },
  53835. set: function (value) {
  53836. this._subMaterials = value;
  53837. this._hookArray(value);
  53838. },
  53839. enumerable: true,
  53840. configurable: true
  53841. });
  53842. MultiMaterial.prototype._hookArray = function (array) {
  53843. var _this = this;
  53844. var oldPush = array.push;
  53845. array.push = function () {
  53846. var items = [];
  53847. for (var _i = 0; _i < arguments.length; _i++) {
  53848. items[_i] = arguments[_i];
  53849. }
  53850. var result = oldPush.apply(array, items);
  53851. _this._markAllSubMeshesAsTexturesDirty();
  53852. return result;
  53853. };
  53854. var oldSplice = array.splice;
  53855. array.splice = function (index, deleteCount) {
  53856. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53857. _this._markAllSubMeshesAsTexturesDirty();
  53858. return deleted;
  53859. };
  53860. };
  53861. // Properties
  53862. MultiMaterial.prototype.getSubMaterial = function (index) {
  53863. if (index < 0 || index >= this.subMaterials.length) {
  53864. return this.getScene().defaultMaterial;
  53865. }
  53866. return this.subMaterials[index];
  53867. };
  53868. MultiMaterial.prototype.getActiveTextures = function () {
  53869. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53870. if (subMaterial) {
  53871. return subMaterial.getActiveTextures();
  53872. }
  53873. else {
  53874. return [];
  53875. }
  53876. }));
  53877. var _a;
  53878. };
  53879. // Methods
  53880. MultiMaterial.prototype.getClassName = function () {
  53881. return "MultiMaterial";
  53882. };
  53883. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53884. for (var index = 0; index < this.subMaterials.length; index++) {
  53885. var subMaterial = this.subMaterials[index];
  53886. if (subMaterial) {
  53887. if (subMaterial.storeEffectOnSubMeshes) {
  53888. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53889. return false;
  53890. }
  53891. continue;
  53892. }
  53893. if (!subMaterial.isReady(mesh)) {
  53894. return false;
  53895. }
  53896. }
  53897. }
  53898. return true;
  53899. };
  53900. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53901. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53902. for (var index = 0; index < this.subMaterials.length; index++) {
  53903. var subMaterial = null;
  53904. var current = this.subMaterials[index];
  53905. if (cloneChildren && current) {
  53906. subMaterial = current.clone(name + "-" + current.name);
  53907. }
  53908. else {
  53909. subMaterial = this.subMaterials[index];
  53910. }
  53911. newMultiMaterial.subMaterials.push(subMaterial);
  53912. }
  53913. return newMultiMaterial;
  53914. };
  53915. MultiMaterial.prototype.serialize = function () {
  53916. var serializationObject = {};
  53917. serializationObject.name = this.name;
  53918. serializationObject.id = this.id;
  53919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53920. serializationObject.materials = [];
  53921. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53922. var subMat = this.subMaterials[matIndex];
  53923. if (subMat) {
  53924. serializationObject.materials.push(subMat.id);
  53925. }
  53926. else {
  53927. serializationObject.materials.push(null);
  53928. }
  53929. }
  53930. return serializationObject;
  53931. };
  53932. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53933. var scene = this.getScene();
  53934. if (!scene) {
  53935. return;
  53936. }
  53937. var index = scene.multiMaterials.indexOf(this);
  53938. if (index >= 0) {
  53939. scene.multiMaterials.splice(index, 1);
  53940. }
  53941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53942. };
  53943. return MultiMaterial;
  53944. }(BABYLON.Material));
  53945. BABYLON.MultiMaterial = MultiMaterial;
  53946. })(BABYLON || (BABYLON = {}));
  53947. //# sourceMappingURL=babylon.multiMaterial.js.map
  53948. var BABYLON;
  53949. (function (BABYLON) {
  53950. var FreeCameraTouchInput = /** @class */ (function () {
  53951. function FreeCameraTouchInput() {
  53952. this._offsetX = null;
  53953. this._offsetY = null;
  53954. this._pointerCount = 0;
  53955. this._pointerPressed = new Array();
  53956. this.touchAngularSensibility = 200000.0;
  53957. this.touchMoveSensibility = 250.0;
  53958. }
  53959. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53960. var _this = this;
  53961. var previousPosition = null;
  53962. if (this._pointerInput === undefined) {
  53963. this._onLostFocus = function (evt) {
  53964. _this._offsetX = null;
  53965. _this._offsetY = null;
  53966. };
  53967. this._pointerInput = function (p, s) {
  53968. var evt = p.event;
  53969. if (evt.pointerType === "mouse") {
  53970. return;
  53971. }
  53972. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53973. if (!noPreventDefault) {
  53974. evt.preventDefault();
  53975. }
  53976. _this._pointerPressed.push(evt.pointerId);
  53977. if (_this._pointerPressed.length !== 1) {
  53978. return;
  53979. }
  53980. previousPosition = {
  53981. x: evt.clientX,
  53982. y: evt.clientY
  53983. };
  53984. }
  53985. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53986. if (!noPreventDefault) {
  53987. evt.preventDefault();
  53988. }
  53989. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53990. if (index === -1) {
  53991. return;
  53992. }
  53993. _this._pointerPressed.splice(index, 1);
  53994. if (index != 0) {
  53995. return;
  53996. }
  53997. previousPosition = null;
  53998. _this._offsetX = null;
  53999. _this._offsetY = null;
  54000. }
  54001. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54002. if (!noPreventDefault) {
  54003. evt.preventDefault();
  54004. }
  54005. if (!previousPosition) {
  54006. return;
  54007. }
  54008. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54009. if (index != 0) {
  54010. return;
  54011. }
  54012. _this._offsetX = evt.clientX - previousPosition.x;
  54013. _this._offsetY = -(evt.clientY - previousPosition.y);
  54014. }
  54015. };
  54016. }
  54017. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54018. if (this._onLostFocus) {
  54019. element.addEventListener("blur", this._onLostFocus);
  54020. }
  54021. };
  54022. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54023. if (this._pointerInput && element) {
  54024. if (this._observer) {
  54025. this.camera.getScene().onPointerObservable.remove(this._observer);
  54026. this._observer = null;
  54027. }
  54028. if (this._onLostFocus) {
  54029. element.removeEventListener("blur", this._onLostFocus);
  54030. this._onLostFocus = null;
  54031. }
  54032. this._pointerPressed = [];
  54033. this._offsetX = null;
  54034. this._offsetY = null;
  54035. this._pointerCount = 0;
  54036. }
  54037. };
  54038. FreeCameraTouchInput.prototype.checkInputs = function () {
  54039. if (this._offsetX && this._offsetY) {
  54040. var camera = this.camera;
  54041. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54042. if (this._pointerPressed.length > 1) {
  54043. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54044. }
  54045. else {
  54046. var speed = camera._computeLocalCameraSpeed();
  54047. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54048. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54049. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54050. }
  54051. }
  54052. };
  54053. FreeCameraTouchInput.prototype.getClassName = function () {
  54054. return "FreeCameraTouchInput";
  54055. };
  54056. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54057. return "touch";
  54058. };
  54059. __decorate([
  54060. BABYLON.serialize()
  54061. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54062. __decorate([
  54063. BABYLON.serialize()
  54064. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54065. return FreeCameraTouchInput;
  54066. }());
  54067. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54068. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54069. })(BABYLON || (BABYLON = {}));
  54070. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54071. var BABYLON;
  54072. (function (BABYLON) {
  54073. // We're mainly based on the logic defined into the FreeCamera code
  54074. var TouchCamera = /** @class */ (function (_super) {
  54075. __extends(TouchCamera, _super);
  54076. //-- end properties for backward compatibility for inputs
  54077. function TouchCamera(name, position, scene) {
  54078. var _this = _super.call(this, name, position, scene) || this;
  54079. _this.inputs.addTouch();
  54080. _this._setupInputs();
  54081. return _this;
  54082. }
  54083. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54084. //-- Begin properties for backward compatibility for inputs
  54085. get: function () {
  54086. var touch = this.inputs.attached["touch"];
  54087. if (touch)
  54088. return touch.touchAngularSensibility;
  54089. return 0;
  54090. },
  54091. set: function (value) {
  54092. var touch = this.inputs.attached["touch"];
  54093. if (touch)
  54094. touch.touchAngularSensibility = value;
  54095. },
  54096. enumerable: true,
  54097. configurable: true
  54098. });
  54099. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54100. get: function () {
  54101. var touch = this.inputs.attached["touch"];
  54102. if (touch)
  54103. return touch.touchMoveSensibility;
  54104. return 0;
  54105. },
  54106. set: function (value) {
  54107. var touch = this.inputs.attached["touch"];
  54108. if (touch)
  54109. touch.touchMoveSensibility = value;
  54110. },
  54111. enumerable: true,
  54112. configurable: true
  54113. });
  54114. TouchCamera.prototype.getClassName = function () {
  54115. return "TouchCamera";
  54116. };
  54117. TouchCamera.prototype._setupInputs = function () {
  54118. var mouse = this.inputs.attached["mouse"];
  54119. if (mouse) {
  54120. mouse.touchEnabled = false;
  54121. }
  54122. };
  54123. return TouchCamera;
  54124. }(BABYLON.FreeCamera));
  54125. BABYLON.TouchCamera = TouchCamera;
  54126. })(BABYLON || (BABYLON = {}));
  54127. //# sourceMappingURL=babylon.touchCamera.js.map
  54128. var BABYLON;
  54129. (function (BABYLON) {
  54130. var ProceduralTexture = /** @class */ (function (_super) {
  54131. __extends(ProceduralTexture, _super);
  54132. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54133. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54134. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54135. if (isCube === void 0) { isCube = false; }
  54136. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54137. _this.isCube = isCube;
  54138. _this.isEnabled = true;
  54139. _this._currentRefreshId = -1;
  54140. _this._refreshRate = 1;
  54141. _this._vertexBuffers = {};
  54142. _this._uniforms = new Array();
  54143. _this._samplers = new Array();
  54144. _this._textures = {};
  54145. _this._floats = {};
  54146. _this._floatsArrays = {};
  54147. _this._colors3 = {};
  54148. _this._colors4 = {};
  54149. _this._vectors2 = {};
  54150. _this._vectors3 = {};
  54151. _this._matrices = {};
  54152. _this._fallbackTextureUsed = false;
  54153. scene._proceduralTextures.push(_this);
  54154. _this._engine = scene.getEngine();
  54155. _this.name = name;
  54156. _this.isRenderTarget = true;
  54157. _this._size = size;
  54158. _this._generateMipMaps = generateMipMaps;
  54159. _this.setFragment(fragment);
  54160. _this._fallbackTexture = fallbackTexture;
  54161. if (isCube) {
  54162. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54163. _this.setFloat("face", 0);
  54164. }
  54165. else {
  54166. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54167. }
  54168. // VBO
  54169. var vertices = [];
  54170. vertices.push(1, 1);
  54171. vertices.push(-1, 1);
  54172. vertices.push(-1, -1);
  54173. vertices.push(1, -1);
  54174. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54175. _this._createIndexBuffer();
  54176. return _this;
  54177. }
  54178. ProceduralTexture.prototype._createIndexBuffer = function () {
  54179. var engine = this._engine;
  54180. // Indices
  54181. var indices = [];
  54182. indices.push(0);
  54183. indices.push(1);
  54184. indices.push(2);
  54185. indices.push(0);
  54186. indices.push(2);
  54187. indices.push(3);
  54188. this._indexBuffer = engine.createIndexBuffer(indices);
  54189. };
  54190. ProceduralTexture.prototype._rebuild = function () {
  54191. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54192. if (vb) {
  54193. vb._rebuild();
  54194. }
  54195. this._createIndexBuffer();
  54196. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54197. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54198. }
  54199. };
  54200. ProceduralTexture.prototype.reset = function () {
  54201. if (this._effect === undefined) {
  54202. return;
  54203. }
  54204. var engine = this._engine;
  54205. engine._releaseEffect(this._effect);
  54206. };
  54207. ProceduralTexture.prototype.isReady = function () {
  54208. var _this = this;
  54209. var engine = this._engine;
  54210. var shaders;
  54211. if (!this._fragment) {
  54212. return false;
  54213. }
  54214. if (this._fallbackTextureUsed) {
  54215. return true;
  54216. }
  54217. if (this._fragment.fragmentElement !== undefined) {
  54218. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54219. }
  54220. else {
  54221. shaders = { vertex: "procedural", fragment: this._fragment };
  54222. }
  54223. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54224. _this.releaseInternalTexture();
  54225. if (_this._fallbackTexture) {
  54226. _this._texture = _this._fallbackTexture._texture;
  54227. if (_this._texture) {
  54228. _this._texture.incrementReferences();
  54229. }
  54230. }
  54231. _this._fallbackTextureUsed = true;
  54232. });
  54233. return this._effect.isReady();
  54234. };
  54235. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54236. this._currentRefreshId = -1;
  54237. };
  54238. ProceduralTexture.prototype.setFragment = function (fragment) {
  54239. this._fragment = fragment;
  54240. };
  54241. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54242. get: function () {
  54243. return this._refreshRate;
  54244. },
  54245. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54246. set: function (value) {
  54247. this._refreshRate = value;
  54248. this.resetRefreshCounter();
  54249. },
  54250. enumerable: true,
  54251. configurable: true
  54252. });
  54253. ProceduralTexture.prototype._shouldRender = function () {
  54254. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54255. return false;
  54256. }
  54257. if (this._fallbackTextureUsed) {
  54258. return false;
  54259. }
  54260. if (this._currentRefreshId === -1) {
  54261. this._currentRefreshId = 1;
  54262. return true;
  54263. }
  54264. if (this.refreshRate === this._currentRefreshId) {
  54265. this._currentRefreshId = 1;
  54266. return true;
  54267. }
  54268. this._currentRefreshId++;
  54269. return false;
  54270. };
  54271. ProceduralTexture.prototype.getRenderSize = function () {
  54272. return this._size;
  54273. };
  54274. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54275. if (this._fallbackTextureUsed) {
  54276. return;
  54277. }
  54278. this.releaseInternalTexture();
  54279. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54280. };
  54281. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54282. if (this._uniforms.indexOf(uniformName) === -1) {
  54283. this._uniforms.push(uniformName);
  54284. }
  54285. };
  54286. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54287. if (this._samplers.indexOf(name) === -1) {
  54288. this._samplers.push(name);
  54289. }
  54290. this._textures[name] = texture;
  54291. return this;
  54292. };
  54293. ProceduralTexture.prototype.setFloat = function (name, value) {
  54294. this._checkUniform(name);
  54295. this._floats[name] = value;
  54296. return this;
  54297. };
  54298. ProceduralTexture.prototype.setFloats = function (name, value) {
  54299. this._checkUniform(name);
  54300. this._floatsArrays[name] = value;
  54301. return this;
  54302. };
  54303. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54304. this._checkUniform(name);
  54305. this._colors3[name] = value;
  54306. return this;
  54307. };
  54308. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54309. this._checkUniform(name);
  54310. this._colors4[name] = value;
  54311. return this;
  54312. };
  54313. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54314. this._checkUniform(name);
  54315. this._vectors2[name] = value;
  54316. return this;
  54317. };
  54318. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54319. this._checkUniform(name);
  54320. this._vectors3[name] = value;
  54321. return this;
  54322. };
  54323. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54324. this._checkUniform(name);
  54325. this._matrices[name] = value;
  54326. return this;
  54327. };
  54328. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54329. var scene = this.getScene();
  54330. if (!scene) {
  54331. return;
  54332. }
  54333. var engine = this._engine;
  54334. // Render
  54335. engine.enableEffect(this._effect);
  54336. engine.setState(false);
  54337. // Texture
  54338. for (var name in this._textures) {
  54339. this._effect.setTexture(name, this._textures[name]);
  54340. }
  54341. // Float
  54342. for (name in this._floats) {
  54343. this._effect.setFloat(name, this._floats[name]);
  54344. }
  54345. // Floats
  54346. for (name in this._floatsArrays) {
  54347. this._effect.setArray(name, this._floatsArrays[name]);
  54348. }
  54349. // Color3
  54350. for (name in this._colors3) {
  54351. this._effect.setColor3(name, this._colors3[name]);
  54352. }
  54353. // Color4
  54354. for (name in this._colors4) {
  54355. var color = this._colors4[name];
  54356. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54357. }
  54358. // Vector2
  54359. for (name in this._vectors2) {
  54360. this._effect.setVector2(name, this._vectors2[name]);
  54361. }
  54362. // Vector3
  54363. for (name in this._vectors3) {
  54364. this._effect.setVector3(name, this._vectors3[name]);
  54365. }
  54366. // Matrix
  54367. for (name in this._matrices) {
  54368. this._effect.setMatrix(name, this._matrices[name]);
  54369. }
  54370. if (!this._texture) {
  54371. return;
  54372. }
  54373. if (this.isCube) {
  54374. for (var face = 0; face < 6; face++) {
  54375. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54376. // VBOs
  54377. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54378. this._effect.setFloat("face", face);
  54379. // Clear
  54380. engine.clear(scene.clearColor, true, true, true);
  54381. // Draw order
  54382. engine.draw(true, 0, 6);
  54383. // Mipmaps
  54384. if (face === 5) {
  54385. engine.generateMipMapsForCubemap(this._texture);
  54386. }
  54387. }
  54388. }
  54389. else {
  54390. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54391. // VBOs
  54392. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54393. // Clear
  54394. engine.clear(scene.clearColor, true, true, true);
  54395. // Draw order
  54396. engine.draw(true, 0, 6);
  54397. }
  54398. // Unbind
  54399. engine.unBindFramebuffer(this._texture, this.isCube);
  54400. if (this.onGenerated) {
  54401. this.onGenerated();
  54402. }
  54403. };
  54404. ProceduralTexture.prototype.clone = function () {
  54405. var textureSize = this.getSize();
  54406. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54407. // Base texture
  54408. newTexture.hasAlpha = this.hasAlpha;
  54409. newTexture.level = this.level;
  54410. // RenderTarget Texture
  54411. newTexture.coordinatesMode = this.coordinatesMode;
  54412. return newTexture;
  54413. };
  54414. ProceduralTexture.prototype.dispose = function () {
  54415. var scene = this.getScene();
  54416. if (!scene) {
  54417. return;
  54418. }
  54419. var index = scene._proceduralTextures.indexOf(this);
  54420. if (index >= 0) {
  54421. scene._proceduralTextures.splice(index, 1);
  54422. }
  54423. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54424. if (vertexBuffer) {
  54425. vertexBuffer.dispose();
  54426. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54427. }
  54428. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54429. this._indexBuffer = null;
  54430. }
  54431. _super.prototype.dispose.call(this);
  54432. };
  54433. return ProceduralTexture;
  54434. }(BABYLON.Texture));
  54435. BABYLON.ProceduralTexture = ProceduralTexture;
  54436. })(BABYLON || (BABYLON = {}));
  54437. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54438. var BABYLON;
  54439. (function (BABYLON) {
  54440. var CustomProceduralTexture = /** @class */ (function (_super) {
  54441. __extends(CustomProceduralTexture, _super);
  54442. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54443. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54444. _this._animate = true;
  54445. _this._time = 0;
  54446. _this._texturePath = texturePath;
  54447. //Try to load json
  54448. _this.loadJson(texturePath);
  54449. _this.refreshRate = 1;
  54450. return _this;
  54451. }
  54452. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54453. var _this = this;
  54454. var noConfigFile = function () {
  54455. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54456. try {
  54457. _this.setFragment(_this._texturePath);
  54458. }
  54459. catch (ex) {
  54460. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54461. }
  54462. };
  54463. var configFileUrl = jsonUrl + "/config.json";
  54464. var xhr = new XMLHttpRequest();
  54465. xhr.open("GET", configFileUrl, true);
  54466. xhr.addEventListener("load", function () {
  54467. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54468. try {
  54469. _this._config = JSON.parse(xhr.response);
  54470. _this.updateShaderUniforms();
  54471. _this.updateTextures();
  54472. _this.setFragment(_this._texturePath + "/custom");
  54473. _this._animate = _this._config.animate;
  54474. _this.refreshRate = _this._config.refreshrate;
  54475. }
  54476. catch (ex) {
  54477. noConfigFile();
  54478. }
  54479. }
  54480. else {
  54481. noConfigFile();
  54482. }
  54483. }, false);
  54484. xhr.addEventListener("error", function () {
  54485. noConfigFile();
  54486. }, false);
  54487. try {
  54488. xhr.send();
  54489. }
  54490. catch (ex) {
  54491. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54492. }
  54493. };
  54494. CustomProceduralTexture.prototype.isReady = function () {
  54495. if (!_super.prototype.isReady.call(this)) {
  54496. return false;
  54497. }
  54498. for (var name in this._textures) {
  54499. var texture = this._textures[name];
  54500. if (!texture.isReady()) {
  54501. return false;
  54502. }
  54503. }
  54504. return true;
  54505. };
  54506. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54507. var scene = this.getScene();
  54508. if (this._animate && scene) {
  54509. this._time += scene.getAnimationRatio() * 0.03;
  54510. this.updateShaderUniforms();
  54511. }
  54512. _super.prototype.render.call(this, useCameraPostProcess);
  54513. };
  54514. CustomProceduralTexture.prototype.updateTextures = function () {
  54515. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54516. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54517. }
  54518. };
  54519. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54520. if (this._config) {
  54521. for (var j = 0; j < this._config.uniforms.length; j++) {
  54522. var uniform = this._config.uniforms[j];
  54523. switch (uniform.type) {
  54524. case "float":
  54525. this.setFloat(uniform.name, uniform.value);
  54526. break;
  54527. case "color3":
  54528. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54529. break;
  54530. case "color4":
  54531. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54532. break;
  54533. case "vector2":
  54534. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54535. break;
  54536. case "vector3":
  54537. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54538. break;
  54539. }
  54540. }
  54541. }
  54542. this.setFloat("time", this._time);
  54543. };
  54544. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54545. get: function () {
  54546. return this._animate;
  54547. },
  54548. set: function (value) {
  54549. this._animate = value;
  54550. },
  54551. enumerable: true,
  54552. configurable: true
  54553. });
  54554. return CustomProceduralTexture;
  54555. }(BABYLON.ProceduralTexture));
  54556. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54557. })(BABYLON || (BABYLON = {}));
  54558. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54559. var BABYLON;
  54560. (function (BABYLON) {
  54561. var FreeCameraGamepadInput = /** @class */ (function () {
  54562. function FreeCameraGamepadInput() {
  54563. this.gamepadAngularSensibility = 200;
  54564. this.gamepadMoveSensibility = 40;
  54565. // private members
  54566. this._cameraTransform = BABYLON.Matrix.Identity();
  54567. this._deltaTransform = BABYLON.Vector3.Zero();
  54568. this._vector3 = BABYLON.Vector3.Zero();
  54569. this._vector2 = BABYLON.Vector2.Zero();
  54570. }
  54571. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54572. var _this = this;
  54573. var manager = this.camera.getScene().gamepadManager;
  54574. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54575. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54576. // prioritize XBOX gamepads.
  54577. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54578. _this.gamepad = gamepad;
  54579. }
  54580. }
  54581. });
  54582. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54583. if (_this.gamepad === gamepad) {
  54584. _this.gamepad = null;
  54585. }
  54586. });
  54587. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54588. };
  54589. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54590. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54591. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54592. this.gamepad = null;
  54593. };
  54594. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54595. if (this.gamepad && this.gamepad.leftStick) {
  54596. var camera = this.camera;
  54597. var LSValues = this.gamepad.leftStick;
  54598. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54599. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54600. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54601. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54602. var RSValues = this.gamepad.rightStick;
  54603. if (RSValues) {
  54604. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54605. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54606. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54607. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54608. }
  54609. else {
  54610. RSValues = { x: 0, y: 0 };
  54611. }
  54612. if (!camera.rotationQuaternion) {
  54613. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54614. }
  54615. else {
  54616. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54617. }
  54618. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54619. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54620. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54621. camera.cameraDirection.addInPlace(this._deltaTransform);
  54622. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54623. camera.cameraRotation.addInPlace(this._vector2);
  54624. }
  54625. };
  54626. FreeCameraGamepadInput.prototype.getClassName = function () {
  54627. return "FreeCameraGamepadInput";
  54628. };
  54629. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54630. return "gamepad";
  54631. };
  54632. __decorate([
  54633. BABYLON.serialize()
  54634. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54635. __decorate([
  54636. BABYLON.serialize()
  54637. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54638. return FreeCameraGamepadInput;
  54639. }());
  54640. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54641. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54642. })(BABYLON || (BABYLON = {}));
  54643. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54644. var BABYLON;
  54645. (function (BABYLON) {
  54646. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54647. function ArcRotateCameraGamepadInput() {
  54648. this.gamepadRotationSensibility = 80;
  54649. this.gamepadMoveSensibility = 40;
  54650. }
  54651. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54652. var _this = this;
  54653. var manager = this.camera.getScene().gamepadManager;
  54654. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54655. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54656. // prioritize XBOX gamepads.
  54657. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54658. _this.gamepad = gamepad;
  54659. }
  54660. }
  54661. });
  54662. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54663. if (_this.gamepad === gamepad) {
  54664. _this.gamepad = null;
  54665. }
  54666. });
  54667. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54668. };
  54669. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54670. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54671. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54672. this.gamepad = null;
  54673. };
  54674. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54675. if (this.gamepad) {
  54676. var camera = this.camera;
  54677. var RSValues = this.gamepad.rightStick;
  54678. if (RSValues) {
  54679. if (RSValues.x != 0) {
  54680. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54681. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54682. camera.inertialAlphaOffset += normalizedRX;
  54683. }
  54684. }
  54685. if (RSValues.y != 0) {
  54686. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54687. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54688. camera.inertialBetaOffset += normalizedRY;
  54689. }
  54690. }
  54691. }
  54692. var LSValues = this.gamepad.leftStick;
  54693. if (LSValues && LSValues.y != 0) {
  54694. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54695. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54696. this.camera.inertialRadiusOffset -= normalizedLY;
  54697. }
  54698. }
  54699. }
  54700. };
  54701. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54702. return "ArcRotateCameraGamepadInput";
  54703. };
  54704. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54705. return "gamepad";
  54706. };
  54707. __decorate([
  54708. BABYLON.serialize()
  54709. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54710. __decorate([
  54711. BABYLON.serialize()
  54712. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54713. return ArcRotateCameraGamepadInput;
  54714. }());
  54715. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54716. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54717. })(BABYLON || (BABYLON = {}));
  54718. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54719. var BABYLON;
  54720. (function (BABYLON) {
  54721. var GamepadManager = /** @class */ (function () {
  54722. function GamepadManager() {
  54723. var _this = this;
  54724. this._babylonGamepads = [];
  54725. this._oneGamepadConnected = false;
  54726. this._isMonitoring = false;
  54727. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54728. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54729. this._gamepadEventSupported = false;
  54730. }
  54731. else {
  54732. this._gamepadEventSupported = 'GamepadEvent' in window;
  54733. this._gamepadSupport = (navigator.getGamepads ||
  54734. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54735. }
  54736. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54737. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54738. for (var i in _this._babylonGamepads) {
  54739. var gamepad = _this._babylonGamepads[i];
  54740. if (gamepad && gamepad._isConnected) {
  54741. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54742. }
  54743. }
  54744. });
  54745. this._onGamepadConnectedEvent = function (evt) {
  54746. var gamepad = evt.gamepad;
  54747. if (gamepad.index in _this._babylonGamepads) {
  54748. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54749. return;
  54750. }
  54751. }
  54752. var newGamepad;
  54753. if (_this._babylonGamepads[gamepad.index]) {
  54754. newGamepad = _this._babylonGamepads[gamepad.index];
  54755. newGamepad.browserGamepad = gamepad;
  54756. newGamepad._isConnected = true;
  54757. }
  54758. else {
  54759. newGamepad = _this._addNewGamepad(gamepad);
  54760. }
  54761. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54762. _this._startMonitoringGamepads();
  54763. };
  54764. this._onGamepadDisconnectedEvent = function (evt) {
  54765. var gamepad = evt.gamepad;
  54766. // Remove the gamepad from the list of gamepads to monitor.
  54767. for (var i in _this._babylonGamepads) {
  54768. if (_this._babylonGamepads[i].index === gamepad.index) {
  54769. var disconnectedGamepad = _this._babylonGamepads[i];
  54770. disconnectedGamepad._isConnected = false;
  54771. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54772. break;
  54773. }
  54774. }
  54775. };
  54776. if (this._gamepadSupport) {
  54777. //first add already-connected gamepads
  54778. this._updateGamepadObjects();
  54779. if (this._babylonGamepads.length) {
  54780. this._startMonitoringGamepads();
  54781. }
  54782. // Checking if the gamepad connected event is supported (like in Firefox)
  54783. if (this._gamepadEventSupported) {
  54784. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54785. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54786. }
  54787. else {
  54788. this._startMonitoringGamepads();
  54789. }
  54790. }
  54791. }
  54792. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54793. get: function () {
  54794. return this._babylonGamepads;
  54795. },
  54796. enumerable: true,
  54797. configurable: true
  54798. });
  54799. GamepadManager.prototype.getGamepadByType = function (type) {
  54800. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54801. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54802. var gamepad = _a[_i];
  54803. if (gamepad && gamepad.type === type) {
  54804. return gamepad;
  54805. }
  54806. }
  54807. return null;
  54808. };
  54809. GamepadManager.prototype.dispose = function () {
  54810. if (this._gamepadEventSupported) {
  54811. if (this._onGamepadConnectedEvent) {
  54812. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54813. }
  54814. if (this._onGamepadDisconnectedEvent) {
  54815. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54816. }
  54817. this._onGamepadConnectedEvent = null;
  54818. this._onGamepadDisconnectedEvent = null;
  54819. }
  54820. this._babylonGamepads.forEach(function (gamepad) {
  54821. gamepad.dispose();
  54822. });
  54823. this.onGamepadConnectedObservable.clear();
  54824. this.onGamepadDisconnectedObservable.clear();
  54825. this._oneGamepadConnected = false;
  54826. this._stopMonitoringGamepads();
  54827. this._babylonGamepads = [];
  54828. };
  54829. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54830. if (!this._oneGamepadConnected) {
  54831. this._oneGamepadConnected = true;
  54832. }
  54833. var newGamepad;
  54834. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54835. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54836. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54837. }
  54838. else if (gamepad.pose) {
  54839. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54840. }
  54841. else {
  54842. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54843. }
  54844. this._babylonGamepads[newGamepad.index] = newGamepad;
  54845. return newGamepad;
  54846. };
  54847. GamepadManager.prototype._startMonitoringGamepads = function () {
  54848. if (!this._isMonitoring) {
  54849. this._isMonitoring = true;
  54850. this._checkGamepadsStatus();
  54851. }
  54852. };
  54853. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54854. this._isMonitoring = false;
  54855. };
  54856. GamepadManager.prototype._checkGamepadsStatus = function () {
  54857. var _this = this;
  54858. // Hack to be compatible Chrome
  54859. this._updateGamepadObjects();
  54860. for (var i in this._babylonGamepads) {
  54861. var gamepad = this._babylonGamepads[i];
  54862. if (!gamepad || !gamepad.isConnected) {
  54863. continue;
  54864. }
  54865. gamepad.update();
  54866. }
  54867. if (this._isMonitoring) {
  54868. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54869. }
  54870. };
  54871. // This function is called only on Chrome, which does not properly support
  54872. // connection/disconnection events and forces you to recopy again the gamepad object
  54873. GamepadManager.prototype._updateGamepadObjects = function () {
  54874. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54875. for (var i = 0; i < gamepads.length; i++) {
  54876. if (gamepads[i]) {
  54877. if (!this._babylonGamepads[gamepads[i].index]) {
  54878. var newGamepad = this._addNewGamepad(gamepads[i]);
  54879. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54880. }
  54881. else {
  54882. // Forced to copy again this object for Chrome for unknown reason
  54883. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54884. if (!this._babylonGamepads[i].isConnected) {
  54885. this._babylonGamepads[i]._isConnected = true;
  54886. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54887. }
  54888. }
  54889. }
  54890. }
  54891. };
  54892. return GamepadManager;
  54893. }());
  54894. BABYLON.GamepadManager = GamepadManager;
  54895. })(BABYLON || (BABYLON = {}));
  54896. //# sourceMappingURL=babylon.gamepadManager.js.map
  54897. var BABYLON;
  54898. (function (BABYLON) {
  54899. var StickValues = /** @class */ (function () {
  54900. function StickValues(x, y) {
  54901. this.x = x;
  54902. this.y = y;
  54903. }
  54904. return StickValues;
  54905. }());
  54906. BABYLON.StickValues = StickValues;
  54907. var Gamepad = /** @class */ (function () {
  54908. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54909. if (leftStickX === void 0) { leftStickX = 0; }
  54910. if (leftStickY === void 0) { leftStickY = 1; }
  54911. if (rightStickX === void 0) { rightStickX = 2; }
  54912. if (rightStickY === void 0) { rightStickY = 3; }
  54913. this.id = id;
  54914. this.index = index;
  54915. this.browserGamepad = browserGamepad;
  54916. this._isConnected = true;
  54917. this.type = Gamepad.GAMEPAD;
  54918. this._leftStickAxisX = leftStickX;
  54919. this._leftStickAxisY = leftStickY;
  54920. this._rightStickAxisX = rightStickX;
  54921. this._rightStickAxisY = rightStickY;
  54922. if (this.browserGamepad.axes.length >= 2) {
  54923. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54924. }
  54925. if (this.browserGamepad.axes.length >= 4) {
  54926. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54927. }
  54928. }
  54929. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54930. get: function () {
  54931. return this._isConnected;
  54932. },
  54933. enumerable: true,
  54934. configurable: true
  54935. });
  54936. Gamepad.prototype.onleftstickchanged = function (callback) {
  54937. this._onleftstickchanged = callback;
  54938. };
  54939. Gamepad.prototype.onrightstickchanged = function (callback) {
  54940. this._onrightstickchanged = callback;
  54941. };
  54942. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54943. get: function () {
  54944. return this._leftStick;
  54945. },
  54946. set: function (newValues) {
  54947. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54948. this._onleftstickchanged(newValues);
  54949. }
  54950. this._leftStick = newValues;
  54951. },
  54952. enumerable: true,
  54953. configurable: true
  54954. });
  54955. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54956. get: function () {
  54957. return this._rightStick;
  54958. },
  54959. set: function (newValues) {
  54960. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54961. this._onrightstickchanged(newValues);
  54962. }
  54963. this._rightStick = newValues;
  54964. },
  54965. enumerable: true,
  54966. configurable: true
  54967. });
  54968. Gamepad.prototype.update = function () {
  54969. if (this._leftStick) {
  54970. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54971. }
  54972. if (this._rightStick) {
  54973. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54974. }
  54975. };
  54976. Gamepad.prototype.dispose = function () {
  54977. };
  54978. Gamepad.GAMEPAD = 0;
  54979. Gamepad.GENERIC = 1;
  54980. Gamepad.XBOX = 2;
  54981. Gamepad.POSE_ENABLED = 3;
  54982. return Gamepad;
  54983. }());
  54984. BABYLON.Gamepad = Gamepad;
  54985. var GenericPad = /** @class */ (function (_super) {
  54986. __extends(GenericPad, _super);
  54987. function GenericPad(id, index, browserGamepad) {
  54988. var _this = _super.call(this, id, index, browserGamepad) || this;
  54989. _this.onButtonDownObservable = new BABYLON.Observable();
  54990. _this.onButtonUpObservable = new BABYLON.Observable();
  54991. _this.type = Gamepad.GENERIC;
  54992. _this._buttons = new Array(browserGamepad.buttons.length);
  54993. return _this;
  54994. }
  54995. GenericPad.prototype.onbuttondown = function (callback) {
  54996. this._onbuttondown = callback;
  54997. };
  54998. GenericPad.prototype.onbuttonup = function (callback) {
  54999. this._onbuttonup = callback;
  55000. };
  55001. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55002. if (newValue !== currentValue) {
  55003. if (newValue === 1) {
  55004. if (this._onbuttondown) {
  55005. this._onbuttondown(buttonIndex);
  55006. }
  55007. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55008. }
  55009. if (newValue === 0) {
  55010. if (this._onbuttonup) {
  55011. this._onbuttonup(buttonIndex);
  55012. }
  55013. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55014. }
  55015. }
  55016. return newValue;
  55017. };
  55018. GenericPad.prototype.update = function () {
  55019. _super.prototype.update.call(this);
  55020. for (var index = 0; index < this._buttons.length; index++) {
  55021. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55022. }
  55023. };
  55024. return GenericPad;
  55025. }(Gamepad));
  55026. BABYLON.GenericPad = GenericPad;
  55027. })(BABYLON || (BABYLON = {}));
  55028. //# sourceMappingURL=babylon.gamepad.js.map
  55029. var BABYLON;
  55030. (function (BABYLON) {
  55031. var Xbox360Button;
  55032. (function (Xbox360Button) {
  55033. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55034. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55035. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55036. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55037. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55038. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55039. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55040. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55041. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55042. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55043. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55044. var Xbox360Dpad;
  55045. (function (Xbox360Dpad) {
  55046. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55047. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55048. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55049. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55050. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55051. var Xbox360Pad = /** @class */ (function (_super) {
  55052. __extends(Xbox360Pad, _super);
  55053. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55054. if (xboxOne === void 0) { xboxOne = false; }
  55055. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55056. _this._leftTrigger = 0;
  55057. _this._rightTrigger = 0;
  55058. _this.onButtonDownObservable = new BABYLON.Observable();
  55059. _this.onButtonUpObservable = new BABYLON.Observable();
  55060. _this.onPadDownObservable = new BABYLON.Observable();
  55061. _this.onPadUpObservable = new BABYLON.Observable();
  55062. _this._buttonA = 0;
  55063. _this._buttonB = 0;
  55064. _this._buttonX = 0;
  55065. _this._buttonY = 0;
  55066. _this._buttonBack = 0;
  55067. _this._buttonStart = 0;
  55068. _this._buttonLB = 0;
  55069. _this._buttonRB = 0;
  55070. _this._buttonLeftStick = 0;
  55071. _this._buttonRightStick = 0;
  55072. _this._dPadUp = 0;
  55073. _this._dPadDown = 0;
  55074. _this._dPadLeft = 0;
  55075. _this._dPadRight = 0;
  55076. _this._isXboxOnePad = false;
  55077. _this.type = BABYLON.Gamepad.XBOX;
  55078. _this._isXboxOnePad = xboxOne;
  55079. return _this;
  55080. }
  55081. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55082. this._onlefttriggerchanged = callback;
  55083. };
  55084. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55085. this._onrighttriggerchanged = callback;
  55086. };
  55087. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55088. get: function () {
  55089. return this._leftTrigger;
  55090. },
  55091. set: function (newValue) {
  55092. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55093. this._onlefttriggerchanged(newValue);
  55094. }
  55095. this._leftTrigger = newValue;
  55096. },
  55097. enumerable: true,
  55098. configurable: true
  55099. });
  55100. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55101. get: function () {
  55102. return this._rightTrigger;
  55103. },
  55104. set: function (newValue) {
  55105. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55106. this._onrighttriggerchanged(newValue);
  55107. }
  55108. this._rightTrigger = newValue;
  55109. },
  55110. enumerable: true,
  55111. configurable: true
  55112. });
  55113. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55114. this._onbuttondown = callback;
  55115. };
  55116. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55117. this._onbuttonup = callback;
  55118. };
  55119. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55120. this._ondpaddown = callback;
  55121. };
  55122. Xbox360Pad.prototype.ondpadup = function (callback) {
  55123. this._ondpadup = callback;
  55124. };
  55125. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55126. if (newValue !== currentValue) {
  55127. if (newValue === 1) {
  55128. if (this._onbuttondown) {
  55129. this._onbuttondown(buttonType);
  55130. }
  55131. this.onButtonDownObservable.notifyObservers(buttonType);
  55132. }
  55133. if (newValue === 0) {
  55134. if (this._onbuttonup) {
  55135. this._onbuttonup(buttonType);
  55136. }
  55137. this.onButtonUpObservable.notifyObservers(buttonType);
  55138. }
  55139. }
  55140. return newValue;
  55141. };
  55142. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55143. if (newValue !== currentValue) {
  55144. if (newValue === 1) {
  55145. if (this._ondpaddown) {
  55146. this._ondpaddown(buttonType);
  55147. }
  55148. this.onPadDownObservable.notifyObservers(buttonType);
  55149. }
  55150. if (newValue === 0) {
  55151. if (this._ondpadup) {
  55152. this._ondpadup(buttonType);
  55153. }
  55154. this.onPadUpObservable.notifyObservers(buttonType);
  55155. }
  55156. }
  55157. return newValue;
  55158. };
  55159. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55160. get: function () {
  55161. return this._buttonA;
  55162. },
  55163. set: function (value) {
  55164. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55165. },
  55166. enumerable: true,
  55167. configurable: true
  55168. });
  55169. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55170. get: function () {
  55171. return this._buttonB;
  55172. },
  55173. set: function (value) {
  55174. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55175. },
  55176. enumerable: true,
  55177. configurable: true
  55178. });
  55179. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55180. get: function () {
  55181. return this._buttonX;
  55182. },
  55183. set: function (value) {
  55184. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55185. },
  55186. enumerable: true,
  55187. configurable: true
  55188. });
  55189. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55190. get: function () {
  55191. return this._buttonY;
  55192. },
  55193. set: function (value) {
  55194. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55200. get: function () {
  55201. return this._buttonStart;
  55202. },
  55203. set: function (value) {
  55204. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55205. },
  55206. enumerable: true,
  55207. configurable: true
  55208. });
  55209. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55210. get: function () {
  55211. return this._buttonBack;
  55212. },
  55213. set: function (value) {
  55214. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55215. },
  55216. enumerable: true,
  55217. configurable: true
  55218. });
  55219. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55220. get: function () {
  55221. return this._buttonLB;
  55222. },
  55223. set: function (value) {
  55224. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55225. },
  55226. enumerable: true,
  55227. configurable: true
  55228. });
  55229. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55230. get: function () {
  55231. return this._buttonRB;
  55232. },
  55233. set: function (value) {
  55234. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55235. },
  55236. enumerable: true,
  55237. configurable: true
  55238. });
  55239. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55240. get: function () {
  55241. return this._buttonLeftStick;
  55242. },
  55243. set: function (value) {
  55244. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55245. },
  55246. enumerable: true,
  55247. configurable: true
  55248. });
  55249. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55250. get: function () {
  55251. return this._buttonRightStick;
  55252. },
  55253. set: function (value) {
  55254. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55255. },
  55256. enumerable: true,
  55257. configurable: true
  55258. });
  55259. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55260. get: function () {
  55261. return this._dPadUp;
  55262. },
  55263. set: function (value) {
  55264. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55265. },
  55266. enumerable: true,
  55267. configurable: true
  55268. });
  55269. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55270. get: function () {
  55271. return this._dPadDown;
  55272. },
  55273. set: function (value) {
  55274. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55275. },
  55276. enumerable: true,
  55277. configurable: true
  55278. });
  55279. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55280. get: function () {
  55281. return this._dPadLeft;
  55282. },
  55283. set: function (value) {
  55284. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55285. },
  55286. enumerable: true,
  55287. configurable: true
  55288. });
  55289. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55290. get: function () {
  55291. return this._dPadRight;
  55292. },
  55293. set: function (value) {
  55294. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55295. },
  55296. enumerable: true,
  55297. configurable: true
  55298. });
  55299. Xbox360Pad.prototype.update = function () {
  55300. _super.prototype.update.call(this);
  55301. if (this._isXboxOnePad) {
  55302. this.buttonA = this.browserGamepad.buttons[0].value;
  55303. this.buttonB = this.browserGamepad.buttons[1].value;
  55304. this.buttonX = this.browserGamepad.buttons[2].value;
  55305. this.buttonY = this.browserGamepad.buttons[3].value;
  55306. this.buttonLB = this.browserGamepad.buttons[4].value;
  55307. this.buttonRB = this.browserGamepad.buttons[5].value;
  55308. this.leftTrigger = this.browserGamepad.axes[2];
  55309. this.rightTrigger = this.browserGamepad.axes[5];
  55310. this.buttonBack = this.browserGamepad.buttons[9].value;
  55311. this.buttonStart = this.browserGamepad.buttons[8].value;
  55312. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55313. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55314. this.dPadUp = this.browserGamepad.buttons[11].value;
  55315. this.dPadDown = this.browserGamepad.buttons[12].value;
  55316. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55317. this.dPadRight = this.browserGamepad.buttons[14].value;
  55318. }
  55319. else {
  55320. this.buttonA = this.browserGamepad.buttons[0].value;
  55321. this.buttonB = this.browserGamepad.buttons[1].value;
  55322. this.buttonX = this.browserGamepad.buttons[2].value;
  55323. this.buttonY = this.browserGamepad.buttons[3].value;
  55324. this.buttonLB = this.browserGamepad.buttons[4].value;
  55325. this.buttonRB = this.browserGamepad.buttons[5].value;
  55326. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55327. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55328. this.buttonBack = this.browserGamepad.buttons[8].value;
  55329. this.buttonStart = this.browserGamepad.buttons[9].value;
  55330. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55331. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55332. this.dPadUp = this.browserGamepad.buttons[12].value;
  55333. this.dPadDown = this.browserGamepad.buttons[13].value;
  55334. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55335. this.dPadRight = this.browserGamepad.buttons[15].value;
  55336. }
  55337. };
  55338. return Xbox360Pad;
  55339. }(BABYLON.Gamepad));
  55340. BABYLON.Xbox360Pad = Xbox360Pad;
  55341. })(BABYLON || (BABYLON = {}));
  55342. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55343. var BABYLON;
  55344. (function (BABYLON) {
  55345. var PoseEnabledControllerType;
  55346. (function (PoseEnabledControllerType) {
  55347. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55348. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55349. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55350. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55351. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55352. var PoseEnabledControllerHelper = /** @class */ (function () {
  55353. function PoseEnabledControllerHelper() {
  55354. }
  55355. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55356. // Oculus Touch
  55357. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55358. return new BABYLON.OculusTouchController(vrGamepad);
  55359. }
  55360. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55361. return new BABYLON.WindowsMotionController(vrGamepad);
  55362. }
  55363. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55364. return new BABYLON.ViveController(vrGamepad);
  55365. }
  55366. else {
  55367. return new BABYLON.GenericController(vrGamepad);
  55368. }
  55369. };
  55370. return PoseEnabledControllerHelper;
  55371. }());
  55372. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55373. var PoseEnabledController = /** @class */ (function (_super) {
  55374. __extends(PoseEnabledController, _super);
  55375. function PoseEnabledController(browserGamepad) {
  55376. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55377. _this.deviceScaleFactor = 1;
  55378. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55379. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55380. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55381. _this.position = BABYLON.Vector3.Zero();
  55382. _this.rotationQuaternion = new BABYLON.Quaternion();
  55383. _this.devicePosition = BABYLON.Vector3.Zero();
  55384. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55385. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55386. _this._calculatedRotation = new BABYLON.Quaternion();
  55387. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55388. return _this;
  55389. }
  55390. PoseEnabledController.prototype.update = function () {
  55391. _super.prototype.update.call(this);
  55392. var pose = this.browserGamepad.pose;
  55393. this.updateFromDevice(pose);
  55394. if (this._mesh) {
  55395. this._mesh.position.copyFrom(this._calculatedPosition);
  55396. if (this._mesh.rotationQuaternion) {
  55397. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55398. }
  55399. }
  55400. };
  55401. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55402. if (poseData) {
  55403. this.rawPose = poseData;
  55404. if (poseData.position) {
  55405. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55406. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55407. this.devicePosition.z *= -1;
  55408. }
  55409. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55410. this._calculatedPosition.addInPlace(this.position);
  55411. }
  55412. var pose = this.rawPose;
  55413. if (poseData.orientation && pose.orientation) {
  55414. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55415. if (this._mesh) {
  55416. if (this._mesh.getScene().useRightHandedSystem) {
  55417. this.deviceRotationQuaternion.z *= -1;
  55418. this.deviceRotationQuaternion.w *= -1;
  55419. }
  55420. else {
  55421. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55422. }
  55423. }
  55424. // if the camera is set, rotate to the camera's rotation
  55425. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55426. }
  55427. }
  55428. };
  55429. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55430. if (this._mesh) {
  55431. this._mesh.parent = null;
  55432. }
  55433. this._mesh = mesh;
  55434. if (this._poseControlledCamera) {
  55435. this._mesh.parent = this._poseControlledCamera;
  55436. }
  55437. if (!this._mesh.rotationQuaternion) {
  55438. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55439. }
  55440. };
  55441. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55442. this._poseControlledCamera = camera;
  55443. if (this._mesh) {
  55444. this._mesh.parent = this._poseControlledCamera;
  55445. }
  55446. };
  55447. PoseEnabledController.prototype.dispose = function () {
  55448. if (this._mesh) {
  55449. this._mesh.dispose();
  55450. }
  55451. this._mesh = null;
  55452. _super.prototype.dispose.call(this);
  55453. };
  55454. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55455. get: function () {
  55456. return this._mesh;
  55457. },
  55458. enumerable: true,
  55459. configurable: true
  55460. });
  55461. PoseEnabledController.prototype.getForwardRay = function (length) {
  55462. if (length === void 0) { length = 100; }
  55463. if (!this.mesh) {
  55464. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55465. }
  55466. var m = this.mesh.getWorldMatrix();
  55467. var origin = m.getTranslation();
  55468. var forward = new BABYLON.Vector3(0, 0, -1);
  55469. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55470. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55471. return new BABYLON.Ray(origin, direction, length);
  55472. };
  55473. return PoseEnabledController;
  55474. }(BABYLON.Gamepad));
  55475. BABYLON.PoseEnabledController = PoseEnabledController;
  55476. })(BABYLON || (BABYLON = {}));
  55477. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55478. var BABYLON;
  55479. (function (BABYLON) {
  55480. var WebVRController = /** @class */ (function (_super) {
  55481. __extends(WebVRController, _super);
  55482. function WebVRController(vrGamepad) {
  55483. var _this = _super.call(this, vrGamepad) || this;
  55484. // Observables
  55485. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55486. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55487. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55488. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55489. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55490. _this.pad = { x: 0, y: 0 };
  55491. // avoid GC, store state in a tmp object
  55492. _this._changes = {
  55493. pressChanged: false,
  55494. touchChanged: false,
  55495. valueChanged: false,
  55496. changed: false
  55497. };
  55498. _this._buttons = new Array(vrGamepad.buttons.length);
  55499. _this.hand = vrGamepad.hand;
  55500. return _this;
  55501. }
  55502. WebVRController.prototype.onButtonStateChange = function (callback) {
  55503. this._onButtonStateChange = callback;
  55504. };
  55505. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55506. get: function () {
  55507. return this._defaultModel;
  55508. },
  55509. enumerable: true,
  55510. configurable: true
  55511. });
  55512. WebVRController.prototype.update = function () {
  55513. _super.prototype.update.call(this);
  55514. for (var index = 0; index < this._buttons.length; index++) {
  55515. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55516. }
  55517. ;
  55518. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55519. this.pad.x = this.leftStick.x;
  55520. this.pad.y = this.leftStick.y;
  55521. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55522. }
  55523. };
  55524. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55525. if (!newState) {
  55526. newState = {
  55527. pressed: false,
  55528. touched: false,
  55529. value: 0
  55530. };
  55531. }
  55532. if (!currentState) {
  55533. this._buttons[buttonIndex] = {
  55534. pressed: newState.pressed,
  55535. touched: newState.touched,
  55536. value: newState.value
  55537. };
  55538. return;
  55539. }
  55540. this._checkChanges(newState, currentState);
  55541. if (this._changes.changed) {
  55542. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55543. this.handleButtonChange(buttonIndex, newState, this._changes);
  55544. }
  55545. this._buttons[buttonIndex].pressed = newState.pressed;
  55546. this._buttons[buttonIndex].touched = newState.touched;
  55547. // oculus triggers are never 0, thou not touched.
  55548. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55549. };
  55550. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55551. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55552. this._changes.touchChanged = newState.touched !== currentState.touched;
  55553. this._changes.valueChanged = newState.value !== currentState.value;
  55554. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55555. return this._changes;
  55556. };
  55557. WebVRController.prototype.dispose = function () {
  55558. _super.prototype.dispose.call(this);
  55559. this.onTriggerStateChangedObservable.clear();
  55560. this.onMainButtonStateChangedObservable.clear();
  55561. this.onSecondaryButtonStateChangedObservable.clear();
  55562. this.onPadStateChangedObservable.clear();
  55563. this.onPadValuesChangedObservable.clear();
  55564. };
  55565. return WebVRController;
  55566. }(BABYLON.PoseEnabledController));
  55567. BABYLON.WebVRController = WebVRController;
  55568. })(BABYLON || (BABYLON = {}));
  55569. //# sourceMappingURL=babylon.webVRController.js.map
  55570. var BABYLON;
  55571. (function (BABYLON) {
  55572. var OculusTouchController = /** @class */ (function (_super) {
  55573. __extends(OculusTouchController, _super);
  55574. function OculusTouchController(vrGamepad) {
  55575. var _this = _super.call(this, vrGamepad) || this;
  55576. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55577. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55578. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55579. return _this;
  55580. }
  55581. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55582. var _this = this;
  55583. var meshName;
  55584. // Hand
  55585. if (this.hand === 'left') {
  55586. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55587. }
  55588. else {
  55589. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55590. }
  55591. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55592. /*
  55593. Parent Mesh name: oculus_touch_left
  55594. - body
  55595. - trigger
  55596. - thumbstick
  55597. - grip
  55598. - button_y
  55599. - button_x
  55600. - button_enter
  55601. */
  55602. _this._defaultModel = newMeshes[1];
  55603. _this.attachToMesh(_this._defaultModel);
  55604. if (meshLoaded) {
  55605. meshLoaded(_this._defaultModel);
  55606. }
  55607. });
  55608. };
  55609. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55610. // helper getters for left and right hand.
  55611. get: function () {
  55612. if (this.hand === 'right') {
  55613. return this.onMainButtonStateChangedObservable;
  55614. }
  55615. else {
  55616. throw new Error('No A button on left hand');
  55617. }
  55618. },
  55619. enumerable: true,
  55620. configurable: true
  55621. });
  55622. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55623. get: function () {
  55624. if (this.hand === 'right') {
  55625. return this.onSecondaryButtonStateChangedObservable;
  55626. }
  55627. else {
  55628. throw new Error('No B button on left hand');
  55629. }
  55630. },
  55631. enumerable: true,
  55632. configurable: true
  55633. });
  55634. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55635. get: function () {
  55636. if (this.hand === 'left') {
  55637. return this.onMainButtonStateChangedObservable;
  55638. }
  55639. else {
  55640. throw new Error('No X button on right hand');
  55641. }
  55642. },
  55643. enumerable: true,
  55644. configurable: true
  55645. });
  55646. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55647. get: function () {
  55648. if (this.hand === 'left') {
  55649. return this.onSecondaryButtonStateChangedObservable;
  55650. }
  55651. else {
  55652. throw new Error('No Y button on right hand');
  55653. }
  55654. },
  55655. enumerable: true,
  55656. configurable: true
  55657. });
  55658. /*
  55659. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55660. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55661. 2) secondary trigger (same)
  55662. 3) A (right) X (left), touch, pressed = value
  55663. 4) B / Y
  55664. 5) thumb rest
  55665. */
  55666. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55667. var notifyObject = state; //{ state: state, changes: changes };
  55668. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55669. switch (buttonIdx) {
  55670. case 0:
  55671. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55672. return;
  55673. case 1:// index trigger
  55674. if (this._defaultModel) {
  55675. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55676. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55677. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55678. }
  55679. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55680. return;
  55681. case 2:// secondary trigger
  55682. if (this._defaultModel) {
  55683. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55684. }
  55685. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55686. return;
  55687. case 3:
  55688. if (this._defaultModel) {
  55689. if (notifyObject.pressed) {
  55690. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55691. }
  55692. else {
  55693. (this._defaultModel.getChildren()[1]).position.y = 0;
  55694. }
  55695. }
  55696. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55697. return;
  55698. case 4:
  55699. if (this._defaultModel) {
  55700. if (notifyObject.pressed) {
  55701. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55702. }
  55703. else {
  55704. (this._defaultModel.getChildren()[2]).position.y = 0;
  55705. }
  55706. }
  55707. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55708. return;
  55709. case 5:
  55710. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55711. return;
  55712. }
  55713. };
  55714. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55715. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55716. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55717. return OculusTouchController;
  55718. }(BABYLON.WebVRController));
  55719. BABYLON.OculusTouchController = OculusTouchController;
  55720. })(BABYLON || (BABYLON = {}));
  55721. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55722. var BABYLON;
  55723. (function (BABYLON) {
  55724. var ViveController = /** @class */ (function (_super) {
  55725. __extends(ViveController, _super);
  55726. function ViveController(vrGamepad) {
  55727. var _this = _super.call(this, vrGamepad) || this;
  55728. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55729. return _this;
  55730. }
  55731. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55732. var _this = this;
  55733. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55734. /*
  55735. Parent Mesh name: ViveWand
  55736. - body
  55737. - r_gripper
  55738. - l_gripper
  55739. - menu_button
  55740. - system_button
  55741. - trackpad
  55742. - trigger
  55743. - LED
  55744. */
  55745. _this._defaultModel = newMeshes[1];
  55746. _this.attachToMesh(_this._defaultModel);
  55747. if (meshLoaded) {
  55748. meshLoaded(_this._defaultModel);
  55749. }
  55750. });
  55751. };
  55752. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55753. get: function () {
  55754. return this.onMainButtonStateChangedObservable;
  55755. },
  55756. enumerable: true,
  55757. configurable: true
  55758. });
  55759. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55760. get: function () {
  55761. return this.onMainButtonStateChangedObservable;
  55762. },
  55763. enumerable: true,
  55764. configurable: true
  55765. });
  55766. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55767. get: function () {
  55768. return this.onSecondaryButtonStateChangedObservable;
  55769. },
  55770. enumerable: true,
  55771. configurable: true
  55772. });
  55773. /**
  55774. * Vive mapping:
  55775. * 0: touchpad
  55776. * 1: trigger
  55777. * 2: left AND right buttons
  55778. * 3: menu button
  55779. */
  55780. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55781. var notifyObject = state; //{ state: state, changes: changes };
  55782. switch (buttonIdx) {
  55783. case 0:
  55784. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55785. return;
  55786. case 1:// index trigger
  55787. if (this._defaultModel) {
  55788. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55789. }
  55790. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55791. return;
  55792. case 2:// left AND right button
  55793. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55794. return;
  55795. case 3:
  55796. if (this._defaultModel) {
  55797. if (notifyObject.pressed) {
  55798. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55799. }
  55800. else {
  55801. (this._defaultModel.getChildren()[2]).position.y = 0;
  55802. }
  55803. }
  55804. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55805. return;
  55806. }
  55807. };
  55808. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55809. ViveController.MODEL_FILENAME = 'wand.babylon';
  55810. return ViveController;
  55811. }(BABYLON.WebVRController));
  55812. BABYLON.ViveController = ViveController;
  55813. })(BABYLON || (BABYLON = {}));
  55814. //# sourceMappingURL=babylon.viveController.js.map
  55815. var BABYLON;
  55816. (function (BABYLON) {
  55817. var GenericController = /** @class */ (function (_super) {
  55818. __extends(GenericController, _super);
  55819. function GenericController(vrGamepad) {
  55820. return _super.call(this, vrGamepad) || this;
  55821. }
  55822. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55823. var _this = this;
  55824. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55825. _this._defaultModel = newMeshes[1];
  55826. _this.attachToMesh(_this._defaultModel);
  55827. if (meshLoaded) {
  55828. meshLoaded(_this._defaultModel);
  55829. }
  55830. });
  55831. };
  55832. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55833. console.log("Button id: " + buttonIdx + "state: ");
  55834. console.dir(state);
  55835. };
  55836. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55837. GenericController.MODEL_FILENAME = 'generic.babylon';
  55838. return GenericController;
  55839. }(BABYLON.WebVRController));
  55840. BABYLON.GenericController = GenericController;
  55841. })(BABYLON || (BABYLON = {}));
  55842. //# sourceMappingURL=babylon.genericController.js.map
  55843. var BABYLON;
  55844. (function (BABYLON) {
  55845. var LoadedMeshInfo = /** @class */ (function () {
  55846. function LoadedMeshInfo() {
  55847. this.buttonMeshes = {};
  55848. this.axisMeshes = {};
  55849. }
  55850. return LoadedMeshInfo;
  55851. }());
  55852. var WindowsMotionController = /** @class */ (function (_super) {
  55853. __extends(WindowsMotionController, _super);
  55854. function WindowsMotionController(vrGamepad) {
  55855. var _this = _super.call(this, vrGamepad) || this;
  55856. _this._mapping = {
  55857. // Semantic button names
  55858. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55859. // A mapping of the button name to glTF model node name
  55860. // that should be transformed by button value.
  55861. buttonMeshNames: {
  55862. 'trigger': 'SELECT',
  55863. 'menu': 'MENU',
  55864. 'grip': 'GRASP',
  55865. 'thumbstick': 'THUMBSTICK_PRESS',
  55866. 'trackpad': 'TOUCHPAD_PRESS'
  55867. },
  55868. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55869. buttonObservableNames: {
  55870. 'trigger': 'onTriggerStateChangedObservable',
  55871. 'menu': 'onSecondaryButtonStateChangedObservable',
  55872. 'grip': 'onMainButtonStateChangedObservable',
  55873. 'thumbstick': 'onPadStateChangedObservable',
  55874. 'trackpad': 'onTrackpadChangedObservable'
  55875. },
  55876. // A mapping of the axis name to glTF model node name
  55877. // that should be transformed by axis value.
  55878. // This array mirrors the browserGamepad.axes array, such that
  55879. // the mesh corresponding to axis 0 is in this array index 0.
  55880. axisMeshNames: [
  55881. 'THUMBSTICK_X',
  55882. 'THUMBSTICK_Y',
  55883. 'TOUCHPAD_TOUCH_X',
  55884. 'TOUCHPAD_TOUCH_Y'
  55885. ],
  55886. pointingPoseMeshName: 'POINTING_POSE'
  55887. };
  55888. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55889. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55890. _this._loadedMeshInfo = null;
  55891. return _this;
  55892. }
  55893. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55894. get: function () {
  55895. return this.onTriggerStateChangedObservable;
  55896. },
  55897. enumerable: true,
  55898. configurable: true
  55899. });
  55900. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55901. get: function () {
  55902. return this.onSecondaryButtonStateChangedObservable;
  55903. },
  55904. enumerable: true,
  55905. configurable: true
  55906. });
  55907. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55908. get: function () {
  55909. return this.onMainButtonStateChangedObservable;
  55910. },
  55911. enumerable: true,
  55912. configurable: true
  55913. });
  55914. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55915. get: function () {
  55916. return this.onPadStateChangedObservable;
  55917. },
  55918. enumerable: true,
  55919. configurable: true
  55920. });
  55921. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55922. get: function () {
  55923. return this.onTrackpadChangedObservable;
  55924. },
  55925. enumerable: true,
  55926. configurable: true
  55927. });
  55928. /**
  55929. * Called once per frame by the engine.
  55930. */
  55931. WindowsMotionController.prototype.update = function () {
  55932. _super.prototype.update.call(this);
  55933. // Only need to animate axes if there is a loaded mesh
  55934. if (this._loadedMeshInfo) {
  55935. if (this.browserGamepad.axes) {
  55936. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55937. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55938. }
  55939. }
  55940. }
  55941. };
  55942. /**
  55943. * Called once for each button that changed state since the last frame
  55944. * @param buttonIdx Which button index changed
  55945. * @param state New state of the button
  55946. * @param changes Which properties on the state changed since last frame
  55947. */
  55948. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55949. var buttonName = this._mapping.buttons[buttonIdx];
  55950. if (!buttonName) {
  55951. return;
  55952. }
  55953. // Only emit events for buttons that we know how to map from index to name
  55954. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55955. if (observable) {
  55956. observable.notifyObservers(state);
  55957. }
  55958. this.lerpButtonTransform(buttonName, state.value);
  55959. };
  55960. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55961. // If there is no loaded mesh, there is nothing to transform.
  55962. if (!this._loadedMeshInfo) {
  55963. return;
  55964. }
  55965. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55966. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55967. return;
  55968. }
  55969. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55970. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55971. };
  55972. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55973. if (!this._loadedMeshInfo) {
  55974. return;
  55975. }
  55976. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55977. if (!meshInfo) {
  55978. return;
  55979. }
  55980. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55981. return;
  55982. }
  55983. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55984. var lerpValue = axisValue * 0.5 + 0.5;
  55985. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55986. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55987. };
  55988. /**
  55989. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55990. * @param scene scene in which to add meshes
  55991. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55992. */
  55993. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55994. var _this = this;
  55995. if (forceDefault === void 0) { forceDefault = false; }
  55996. var path;
  55997. var filename;
  55998. // Checking if GLB loader is present
  55999. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56000. // Determine the device specific folder based on the ID suffix
  56001. var device = 'default';
  56002. if (this.id && !forceDefault) {
  56003. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56004. device = ((match && match[0]) || device);
  56005. }
  56006. // Hand
  56007. if (this.hand === 'left') {
  56008. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56009. }
  56010. else {
  56011. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56012. }
  56013. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56014. }
  56015. else {
  56016. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56017. path = BABYLON.GenericController.MODEL_BASE_URL;
  56018. filename = BABYLON.GenericController.MODEL_FILENAME;
  56019. }
  56020. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56021. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56022. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56023. if (!_this._loadedMeshInfo) {
  56024. return;
  56025. }
  56026. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56027. _this.attachToMesh(_this._defaultModel);
  56028. if (meshLoaded) {
  56029. meshLoaded(_this._defaultModel);
  56030. }
  56031. }, null, function (scene, message) {
  56032. BABYLON.Tools.Log(message);
  56033. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56034. if (!forceDefault) {
  56035. _this.initControllerMesh(scene, meshLoaded, true);
  56036. }
  56037. });
  56038. };
  56039. /**
  56040. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56041. * can be transformed by button presses and axes values, based on this._mapping.
  56042. *
  56043. * @param scene scene in which the meshes exist
  56044. * @param meshes list of meshes that make up the controller model to process
  56045. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56046. */
  56047. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56048. var loadedMeshInfo = null;
  56049. // Create a new mesh to contain the glTF hierarchy
  56050. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56051. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56052. var childMesh = null;
  56053. for (var i = 0; i < meshes.length; i++) {
  56054. var mesh = meshes[i];
  56055. if (!mesh.parent) {
  56056. // Exclude controller meshes from picking results
  56057. mesh.isPickable = false;
  56058. // Handle root node, attach to the new parentMesh
  56059. childMesh = mesh;
  56060. break;
  56061. }
  56062. }
  56063. if (childMesh) {
  56064. childMesh.setParent(parentMesh);
  56065. // Create our mesh info. Note that this method will always return non-null.
  56066. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56067. }
  56068. else {
  56069. BABYLON.Tools.Warn('Could not find root node in model file.');
  56070. }
  56071. return loadedMeshInfo;
  56072. };
  56073. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56074. var loadedMeshInfo = new LoadedMeshInfo();
  56075. var i;
  56076. loadedMeshInfo.rootNode = rootNode;
  56077. // Reset the caches
  56078. loadedMeshInfo.buttonMeshes = {};
  56079. loadedMeshInfo.axisMeshes = {};
  56080. // Button Meshes
  56081. for (i = 0; i < this._mapping.buttons.length; i++) {
  56082. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56083. if (!buttonMeshName) {
  56084. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56085. continue;
  56086. }
  56087. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56088. if (!buttonMesh) {
  56089. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56090. continue;
  56091. }
  56092. var buttonMeshInfo = {
  56093. index: i,
  56094. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56095. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56096. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56097. };
  56098. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56099. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56100. }
  56101. else {
  56102. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56103. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56104. '(VALUE: ' + !!buttonMeshInfo.value +
  56105. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56106. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56107. ')');
  56108. }
  56109. }
  56110. // Axis Meshes
  56111. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56112. var axisMeshName = this._mapping.axisMeshNames[i];
  56113. if (!axisMeshName) {
  56114. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56115. continue;
  56116. }
  56117. var axisMesh = getChildByName(rootNode, axisMeshName);
  56118. if (!axisMesh) {
  56119. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56120. continue;
  56121. }
  56122. var axisMeshInfo = {
  56123. index: i,
  56124. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56125. min: getImmediateChildByName(axisMesh, 'MIN'),
  56126. max: getImmediateChildByName(axisMesh, 'MAX')
  56127. };
  56128. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56129. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56130. }
  56131. else {
  56132. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56133. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56134. '(VALUE: ' + !!axisMeshInfo.value +
  56135. ', MIN: ' + !!axisMeshInfo.min +
  56136. ', MAX:' + !!axisMeshInfo.max +
  56137. ')');
  56138. }
  56139. }
  56140. // Pointing Ray
  56141. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56142. if (!loadedMeshInfo.pointingPoseNode) {
  56143. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56144. }
  56145. return loadedMeshInfo;
  56146. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56147. function getChildByName(node, name) {
  56148. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56149. }
  56150. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56151. function getImmediateChildByName(node, name) {
  56152. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56153. }
  56154. };
  56155. WindowsMotionController.prototype.getForwardRay = function (length) {
  56156. if (length === void 0) { length = 100; }
  56157. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56158. return _super.prototype.getForwardRay.call(this, length);
  56159. }
  56160. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56161. var origin = m.getTranslation();
  56162. var forward = new BABYLON.Vector3(0, 0, -1);
  56163. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56164. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56165. return new BABYLON.Ray(origin, direction, length);
  56166. };
  56167. WindowsMotionController.prototype.dispose = function () {
  56168. _super.prototype.dispose.call(this);
  56169. this.onTrackpadChangedObservable.clear();
  56170. };
  56171. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56172. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56173. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56174. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56175. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56176. return WindowsMotionController;
  56177. }(BABYLON.WebVRController));
  56178. BABYLON.WindowsMotionController = WindowsMotionController;
  56179. })(BABYLON || (BABYLON = {}));
  56180. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56181. var BABYLON;
  56182. (function (BABYLON) {
  56183. var FollowCamera = /** @class */ (function (_super) {
  56184. __extends(FollowCamera, _super);
  56185. function FollowCamera(name, position, scene, lockedTarget) {
  56186. if (lockedTarget === void 0) { lockedTarget = null; }
  56187. var _this = _super.call(this, name, position, scene) || this;
  56188. _this.radius = 12;
  56189. _this.rotationOffset = 0;
  56190. _this.heightOffset = 4;
  56191. _this.cameraAcceleration = 0.05;
  56192. _this.maxCameraSpeed = 20;
  56193. _this.lockedTarget = lockedTarget;
  56194. return _this;
  56195. }
  56196. FollowCamera.prototype.getRadians = function (degrees) {
  56197. return degrees * Math.PI / 180;
  56198. };
  56199. FollowCamera.prototype.follow = function (cameraTarget) {
  56200. if (!cameraTarget)
  56201. return;
  56202. var yRotation;
  56203. if (cameraTarget.rotationQuaternion) {
  56204. var rotMatrix = new BABYLON.Matrix();
  56205. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56206. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56207. }
  56208. else {
  56209. yRotation = cameraTarget.rotation.y;
  56210. }
  56211. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56212. var targetPosition = cameraTarget.getAbsolutePosition();
  56213. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56214. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56215. var dx = targetX - this.position.x;
  56216. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56217. var dz = (targetZ) - this.position.z;
  56218. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56219. var vy = dy * this.cameraAcceleration;
  56220. var vz = dz * this.cameraAcceleration * 2;
  56221. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56222. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56223. }
  56224. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56225. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56226. }
  56227. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56228. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56229. }
  56230. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56231. this.setTarget(targetPosition);
  56232. };
  56233. FollowCamera.prototype._checkInputs = function () {
  56234. _super.prototype._checkInputs.call(this);
  56235. if (this.lockedTarget) {
  56236. this.follow(this.lockedTarget);
  56237. }
  56238. };
  56239. FollowCamera.prototype.getClassName = function () {
  56240. return "FollowCamera";
  56241. };
  56242. __decorate([
  56243. BABYLON.serialize()
  56244. ], FollowCamera.prototype, "radius", void 0);
  56245. __decorate([
  56246. BABYLON.serialize()
  56247. ], FollowCamera.prototype, "rotationOffset", void 0);
  56248. __decorate([
  56249. BABYLON.serialize()
  56250. ], FollowCamera.prototype, "heightOffset", void 0);
  56251. __decorate([
  56252. BABYLON.serialize()
  56253. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56254. __decorate([
  56255. BABYLON.serialize()
  56256. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56257. __decorate([
  56258. BABYLON.serializeAsMeshReference("lockedTargetId")
  56259. ], FollowCamera.prototype, "lockedTarget", void 0);
  56260. return FollowCamera;
  56261. }(BABYLON.TargetCamera));
  56262. BABYLON.FollowCamera = FollowCamera;
  56263. var ArcFollowCamera = /** @class */ (function (_super) {
  56264. __extends(ArcFollowCamera, _super);
  56265. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56266. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56267. _this.alpha = alpha;
  56268. _this.beta = beta;
  56269. _this.radius = radius;
  56270. _this.target = target;
  56271. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56272. _this.follow();
  56273. return _this;
  56274. }
  56275. ArcFollowCamera.prototype.follow = function () {
  56276. if (!this.target) {
  56277. return;
  56278. }
  56279. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56280. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56281. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56282. var targetPosition = this.target.getAbsolutePosition();
  56283. this.position = targetPosition.add(this._cartesianCoordinates);
  56284. this.setTarget(targetPosition);
  56285. };
  56286. ArcFollowCamera.prototype._checkInputs = function () {
  56287. _super.prototype._checkInputs.call(this);
  56288. this.follow();
  56289. };
  56290. ArcFollowCamera.prototype.getClassName = function () {
  56291. return "ArcFollowCamera";
  56292. };
  56293. return ArcFollowCamera;
  56294. }(BABYLON.TargetCamera));
  56295. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56296. })(BABYLON || (BABYLON = {}));
  56297. //# sourceMappingURL=babylon.followCamera.js.map
  56298. var BABYLON;
  56299. (function (BABYLON) {
  56300. // We're mainly based on the logic defined into the FreeCamera code
  56301. var UniversalCamera = /** @class */ (function (_super) {
  56302. __extends(UniversalCamera, _super);
  56303. //-- end properties for backward compatibility for inputs
  56304. function UniversalCamera(name, position, scene) {
  56305. var _this = _super.call(this, name, position, scene) || this;
  56306. _this.inputs.addGamepad();
  56307. return _this;
  56308. }
  56309. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56310. //-- Begin properties for backward compatibility for inputs
  56311. get: function () {
  56312. var gamepad = this.inputs.attached["gamepad"];
  56313. if (gamepad)
  56314. return gamepad.gamepadAngularSensibility;
  56315. return 0;
  56316. },
  56317. set: function (value) {
  56318. var gamepad = this.inputs.attached["gamepad"];
  56319. if (gamepad)
  56320. gamepad.gamepadAngularSensibility = value;
  56321. },
  56322. enumerable: true,
  56323. configurable: true
  56324. });
  56325. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56326. get: function () {
  56327. var gamepad = this.inputs.attached["gamepad"];
  56328. if (gamepad)
  56329. return gamepad.gamepadMoveSensibility;
  56330. return 0;
  56331. },
  56332. set: function (value) {
  56333. var gamepad = this.inputs.attached["gamepad"];
  56334. if (gamepad)
  56335. gamepad.gamepadMoveSensibility = value;
  56336. },
  56337. enumerable: true,
  56338. configurable: true
  56339. });
  56340. UniversalCamera.prototype.getClassName = function () {
  56341. return "UniversalCamera";
  56342. };
  56343. return UniversalCamera;
  56344. }(BABYLON.TouchCamera));
  56345. BABYLON.UniversalCamera = UniversalCamera;
  56346. })(BABYLON || (BABYLON = {}));
  56347. //# sourceMappingURL=babylon.universalCamera.js.map
  56348. var BABYLON;
  56349. (function (BABYLON) {
  56350. // We're mainly based on the logic defined into the FreeCamera code
  56351. var GamepadCamera = /** @class */ (function (_super) {
  56352. __extends(GamepadCamera, _super);
  56353. //-- end properties for backward compatibility for inputs
  56354. function GamepadCamera(name, position, scene) {
  56355. return _super.call(this, name, position, scene) || this;
  56356. }
  56357. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56358. //-- Begin properties for backward compatibility for inputs
  56359. get: function () {
  56360. var gamepad = this.inputs.attached["gamepad"];
  56361. if (gamepad)
  56362. return gamepad.gamepadAngularSensibility;
  56363. return 0;
  56364. },
  56365. set: function (value) {
  56366. var gamepad = this.inputs.attached["gamepad"];
  56367. if (gamepad)
  56368. gamepad.gamepadAngularSensibility = value;
  56369. },
  56370. enumerable: true,
  56371. configurable: true
  56372. });
  56373. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56374. get: function () {
  56375. var gamepad = this.inputs.attached["gamepad"];
  56376. if (gamepad)
  56377. return gamepad.gamepadMoveSensibility;
  56378. return 0;
  56379. },
  56380. set: function (value) {
  56381. var gamepad = this.inputs.attached["gamepad"];
  56382. if (gamepad)
  56383. gamepad.gamepadMoveSensibility = value;
  56384. },
  56385. enumerable: true,
  56386. configurable: true
  56387. });
  56388. GamepadCamera.prototype.getClassName = function () {
  56389. return "GamepadCamera";
  56390. };
  56391. return GamepadCamera;
  56392. }(BABYLON.UniversalCamera));
  56393. BABYLON.GamepadCamera = GamepadCamera;
  56394. })(BABYLON || (BABYLON = {}));
  56395. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56396. var BABYLON;
  56397. (function (BABYLON) {
  56398. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56399. function PostProcessRenderPipelineManager() {
  56400. this._renderPipelines = {};
  56401. }
  56402. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56403. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56404. };
  56405. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56406. if (unique === void 0) { unique = false; }
  56407. var renderPipeline = this._renderPipelines[renderPipelineName];
  56408. if (!renderPipeline) {
  56409. return;
  56410. }
  56411. renderPipeline._attachCameras(cameras, unique);
  56412. };
  56413. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56414. var renderPipeline = this._renderPipelines[renderPipelineName];
  56415. if (!renderPipeline) {
  56416. return;
  56417. }
  56418. renderPipeline._detachCameras(cameras);
  56419. };
  56420. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56421. var renderPipeline = this._renderPipelines[renderPipelineName];
  56422. if (!renderPipeline) {
  56423. return;
  56424. }
  56425. renderPipeline._enableEffect(renderEffectName, cameras);
  56426. };
  56427. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56428. var renderPipeline = this._renderPipelines[renderPipelineName];
  56429. if (!renderPipeline) {
  56430. return;
  56431. }
  56432. renderPipeline._disableEffect(renderEffectName, cameras);
  56433. };
  56434. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56435. var renderPipeline = this._renderPipelines[renderPipelineName];
  56436. if (!renderPipeline) {
  56437. return;
  56438. }
  56439. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56440. };
  56441. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56442. var renderPipeline = this._renderPipelines[renderPipelineName];
  56443. if (!renderPipeline) {
  56444. return;
  56445. }
  56446. renderPipeline._disableDisplayOnlyPass(cameras);
  56447. };
  56448. PostProcessRenderPipelineManager.prototype.update = function () {
  56449. for (var renderPipelineName in this._renderPipelines) {
  56450. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56451. var pipeline = this._renderPipelines[renderPipelineName];
  56452. if (!pipeline.isSupported) {
  56453. pipeline.dispose();
  56454. delete this._renderPipelines[renderPipelineName];
  56455. }
  56456. else {
  56457. pipeline._update();
  56458. }
  56459. }
  56460. }
  56461. };
  56462. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56463. for (var renderPipelineName in this._renderPipelines) {
  56464. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56465. var pipeline = this._renderPipelines[renderPipelineName];
  56466. pipeline._rebuild();
  56467. }
  56468. }
  56469. };
  56470. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56471. for (var renderPipelineName in this._renderPipelines) {
  56472. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56473. var pipeline = this._renderPipelines[renderPipelineName];
  56474. pipeline.dispose();
  56475. }
  56476. }
  56477. };
  56478. return PostProcessRenderPipelineManager;
  56479. }());
  56480. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56481. })(BABYLON || (BABYLON = {}));
  56482. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56483. var BABYLON;
  56484. (function (BABYLON) {
  56485. var PostProcessRenderPass = /** @class */ (function () {
  56486. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56487. this._refCount = 0;
  56488. this._name = name;
  56489. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56490. this.setRenderList(renderList);
  56491. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56492. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56493. this._scene = scene;
  56494. this._renderList = renderList;
  56495. }
  56496. // private
  56497. PostProcessRenderPass.prototype._incRefCount = function () {
  56498. if (this._refCount === 0) {
  56499. this._scene.customRenderTargets.push(this._renderTexture);
  56500. }
  56501. return ++this._refCount;
  56502. };
  56503. PostProcessRenderPass.prototype._decRefCount = function () {
  56504. this._refCount--;
  56505. if (this._refCount <= 0) {
  56506. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56507. }
  56508. return this._refCount;
  56509. };
  56510. PostProcessRenderPass.prototype._update = function () {
  56511. this.setRenderList(this._renderList);
  56512. };
  56513. // public
  56514. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56515. this._renderTexture.renderList = renderList;
  56516. };
  56517. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56518. return this._renderTexture;
  56519. };
  56520. return PostProcessRenderPass;
  56521. }());
  56522. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56523. })(BABYLON || (BABYLON = {}));
  56524. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56525. var BABYLON;
  56526. (function (BABYLON) {
  56527. var PostProcessRenderEffect = /** @class */ (function () {
  56528. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56529. this._engine = engine;
  56530. this._name = name;
  56531. this._singleInstance = singleInstance || true;
  56532. this._getPostProcess = getPostProcess;
  56533. this._cameras = {};
  56534. this._indicesForCamera = {};
  56535. this._postProcesses = {};
  56536. this._renderPasses = {};
  56537. this._renderEffectAsPasses = {};
  56538. }
  56539. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56540. get: function () {
  56541. for (var index in this._postProcesses) {
  56542. if (!this._postProcesses[index].isSupported) {
  56543. return false;
  56544. }
  56545. }
  56546. return true;
  56547. },
  56548. enumerable: true,
  56549. configurable: true
  56550. });
  56551. PostProcessRenderEffect.prototype._update = function () {
  56552. for (var renderPassName in this._renderPasses) {
  56553. this._renderPasses[renderPassName]._update();
  56554. }
  56555. };
  56556. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56557. this._renderPasses[renderPass._name] = renderPass;
  56558. this._linkParameters();
  56559. };
  56560. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56561. delete this._renderPasses[renderPass._name];
  56562. this._linkParameters();
  56563. };
  56564. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56565. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56566. this._linkParameters();
  56567. };
  56568. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56569. for (var renderPassName in this._renderPasses) {
  56570. if (renderPassName === passName) {
  56571. return this._renderPasses[passName];
  56572. }
  56573. }
  56574. return null;
  56575. };
  56576. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56577. this._renderPasses = {};
  56578. this._linkParameters();
  56579. };
  56580. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56581. var cameraKey;
  56582. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56583. if (!cams) {
  56584. return;
  56585. }
  56586. for (var i = 0; i < cams.length; i++) {
  56587. var camera = cams[i];
  56588. var cameraName = camera.name;
  56589. if (this._singleInstance) {
  56590. cameraKey = 0;
  56591. }
  56592. else {
  56593. cameraKey = cameraName;
  56594. }
  56595. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56596. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56597. if (!this._indicesForCamera[cameraName]) {
  56598. this._indicesForCamera[cameraName] = [];
  56599. }
  56600. this._indicesForCamera[cameraName].push(index);
  56601. if (!this._cameras[cameraName]) {
  56602. this._cameras[cameraName] = camera;
  56603. }
  56604. for (var passName in this._renderPasses) {
  56605. this._renderPasses[passName]._incRefCount();
  56606. }
  56607. }
  56608. this._linkParameters();
  56609. };
  56610. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56611. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56612. if (!cams) {
  56613. return;
  56614. }
  56615. for (var i = 0; i < cams.length; i++) {
  56616. var camera = cams[i];
  56617. var cameraName = camera.name;
  56618. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56619. if (this._cameras[cameraName]) {
  56620. //this._indicesForCamera.splice(index, 1);
  56621. this._cameras[cameraName] = null;
  56622. }
  56623. for (var passName in this._renderPasses) {
  56624. this._renderPasses[passName]._decRefCount();
  56625. }
  56626. }
  56627. };
  56628. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56629. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56630. if (!cams) {
  56631. return;
  56632. }
  56633. for (var i = 0; i < cams.length; i++) {
  56634. var camera = cams[i];
  56635. var cameraName = camera.name;
  56636. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56637. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56638. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56639. }
  56640. }
  56641. for (var passName in this._renderPasses) {
  56642. this._renderPasses[passName]._incRefCount();
  56643. }
  56644. }
  56645. };
  56646. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56647. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56648. if (!cams) {
  56649. return;
  56650. }
  56651. for (var i = 0; i < cams.length; i++) {
  56652. var camera = cams[i];
  56653. var cameraName = camera.Name;
  56654. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56655. for (var passName in this._renderPasses) {
  56656. this._renderPasses[passName]._decRefCount();
  56657. }
  56658. }
  56659. };
  56660. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56661. if (this._singleInstance) {
  56662. return this._postProcesses[0];
  56663. }
  56664. else {
  56665. if (!camera) {
  56666. return null;
  56667. }
  56668. return this._postProcesses[camera.name];
  56669. }
  56670. };
  56671. PostProcessRenderEffect.prototype._linkParameters = function () {
  56672. var _this = this;
  56673. for (var index in this._postProcesses) {
  56674. if (this.applyParameters) {
  56675. this.applyParameters(this._postProcesses[index]);
  56676. }
  56677. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56678. _this._linkTextures(effect);
  56679. });
  56680. }
  56681. };
  56682. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56683. for (var renderPassName in this._renderPasses) {
  56684. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56685. }
  56686. for (var renderEffectName in this._renderEffectAsPasses) {
  56687. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56688. }
  56689. };
  56690. return PostProcessRenderEffect;
  56691. }());
  56692. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56693. })(BABYLON || (BABYLON = {}));
  56694. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56695. var BABYLON;
  56696. (function (BABYLON) {
  56697. var PostProcessRenderPipeline = /** @class */ (function () {
  56698. function PostProcessRenderPipeline(engine, name) {
  56699. this._engine = engine;
  56700. this._name = name;
  56701. this._renderEffects = {};
  56702. this._renderEffectsForIsolatedPass = new Array();
  56703. this._cameras = [];
  56704. }
  56705. PostProcessRenderPipeline.prototype.getClassName = function () {
  56706. return "PostProcessRenderPipeline";
  56707. };
  56708. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56709. get: function () {
  56710. for (var renderEffectName in this._renderEffects) {
  56711. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56712. if (!this._renderEffects[renderEffectName].isSupported) {
  56713. return false;
  56714. }
  56715. }
  56716. }
  56717. return true;
  56718. },
  56719. enumerable: true,
  56720. configurable: true
  56721. });
  56722. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56723. this._renderEffects[renderEffect._name] = renderEffect;
  56724. };
  56725. // private
  56726. PostProcessRenderPipeline.prototype._rebuild = function () {
  56727. };
  56728. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56729. var renderEffects = this._renderEffects[renderEffectName];
  56730. if (!renderEffects) {
  56731. return;
  56732. }
  56733. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56734. };
  56735. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56736. var renderEffects = this._renderEffects[renderEffectName];
  56737. if (!renderEffects) {
  56738. return;
  56739. }
  56740. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56741. };
  56742. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56743. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56744. if (!cams) {
  56745. return;
  56746. }
  56747. var indicesToDelete = [];
  56748. var i;
  56749. for (i = 0; i < cams.length; i++) {
  56750. var camera = cams[i];
  56751. var cameraName = camera.name;
  56752. if (this._cameras.indexOf(camera) === -1) {
  56753. this._cameras[cameraName] = camera;
  56754. }
  56755. else if (unique) {
  56756. indicesToDelete.push(i);
  56757. }
  56758. }
  56759. for (i = 0; i < indicesToDelete.length; i++) {
  56760. cameras.splice(indicesToDelete[i], 1);
  56761. }
  56762. for (var renderEffectName in this._renderEffects) {
  56763. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56764. this._renderEffects[renderEffectName]._attachCameras(cams);
  56765. }
  56766. }
  56767. };
  56768. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56769. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56770. if (!cams) {
  56771. return;
  56772. }
  56773. for (var renderEffectName in this._renderEffects) {
  56774. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56775. this._renderEffects[renderEffectName]._detachCameras(cams);
  56776. }
  56777. }
  56778. for (var i = 0; i < cams.length; i++) {
  56779. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56780. }
  56781. };
  56782. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56783. var _this = this;
  56784. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56785. if (!cams) {
  56786. return;
  56787. }
  56788. var pass = null;
  56789. var renderEffectName;
  56790. for (renderEffectName in this._renderEffects) {
  56791. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56792. pass = this._renderEffects[renderEffectName].getPass(passName);
  56793. if (pass != null) {
  56794. break;
  56795. }
  56796. }
  56797. }
  56798. if (pass === null) {
  56799. return;
  56800. }
  56801. for (renderEffectName in this._renderEffects) {
  56802. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56803. this._renderEffects[renderEffectName]._disable(cams);
  56804. }
  56805. }
  56806. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56807. for (var i = 0; i < cams.length; i++) {
  56808. var camera = cams[i];
  56809. var cameraName = camera.name;
  56810. 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); });
  56811. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56812. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56813. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56814. }
  56815. };
  56816. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56817. var _this = this;
  56818. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56819. if (!cams) {
  56820. return;
  56821. }
  56822. for (var i = 0; i < cams.length; i++) {
  56823. var camera = cams[i];
  56824. var cameraName = camera.name;
  56825. 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); });
  56826. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56827. }
  56828. for (var renderEffectName in this._renderEffects) {
  56829. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56830. this._renderEffects[renderEffectName]._enable(cams);
  56831. }
  56832. }
  56833. };
  56834. PostProcessRenderPipeline.prototype._update = function () {
  56835. for (var renderEffectName in this._renderEffects) {
  56836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56837. this._renderEffects[renderEffectName]._update();
  56838. }
  56839. }
  56840. for (var i = 0; i < this._cameras.length; i++) {
  56841. var cameraName = this._cameras[i].name;
  56842. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56843. this._renderEffectsForIsolatedPass[cameraName]._update();
  56844. }
  56845. }
  56846. };
  56847. PostProcessRenderPipeline.prototype._reset = function () {
  56848. this._renderEffects = {};
  56849. this._renderEffectsForIsolatedPass = new Array();
  56850. };
  56851. PostProcessRenderPipeline.prototype.dispose = function () {
  56852. // Must be implemented by children
  56853. };
  56854. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56855. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56856. __decorate([
  56857. BABYLON.serialize()
  56858. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56859. return PostProcessRenderPipeline;
  56860. }());
  56861. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56862. })(BABYLON || (BABYLON = {}));
  56863. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56864. var BABYLON;
  56865. (function (BABYLON) {
  56866. var DepthRenderer = /** @class */ (function () {
  56867. function DepthRenderer(scene, type) {
  56868. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56869. var _this = this;
  56870. this._scene = scene;
  56871. var engine = scene.getEngine();
  56872. // Render target
  56873. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56874. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56875. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56876. this._depthMap.refreshRate = 1;
  56877. this._depthMap.renderParticles = false;
  56878. this._depthMap.renderList = null;
  56879. // set default depth value to 1.0 (far away)
  56880. this._depthMap.onClearObservable.add(function (engine) {
  56881. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56882. });
  56883. // Custom render function
  56884. var renderSubMesh = function (subMesh) {
  56885. var mesh = subMesh.getRenderingMesh();
  56886. var scene = _this._scene;
  56887. var engine = scene.getEngine();
  56888. var material = subMesh.getMaterial();
  56889. if (!material) {
  56890. return;
  56891. }
  56892. // Culling
  56893. engine.setState(material.backFaceCulling);
  56894. // Managing instances
  56895. var batch = mesh._getInstancesRenderList(subMesh._id);
  56896. if (batch.mustReturn) {
  56897. return;
  56898. }
  56899. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56900. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56901. engine.enableEffect(_this._effect);
  56902. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56903. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56904. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56905. // Alpha test
  56906. if (material && material.needAlphaTesting()) {
  56907. var alphaTexture = material.getAlphaTestTexture();
  56908. if (alphaTexture) {
  56909. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56910. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56911. }
  56912. }
  56913. // Bones
  56914. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56915. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56916. }
  56917. // Draw
  56918. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56919. }
  56920. };
  56921. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56922. var index;
  56923. if (depthOnlySubMeshes.length) {
  56924. engine.setColorWrite(false);
  56925. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56926. renderSubMesh(depthOnlySubMeshes.data[index]);
  56927. }
  56928. engine.setColorWrite(true);
  56929. }
  56930. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56931. renderSubMesh(opaqueSubMeshes.data[index]);
  56932. }
  56933. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56934. renderSubMesh(alphaTestSubMeshes.data[index]);
  56935. }
  56936. };
  56937. }
  56938. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56939. var material = subMesh.getMaterial();
  56940. if (material.disableDepthWrite) {
  56941. return false;
  56942. }
  56943. var defines = [];
  56944. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56945. var mesh = subMesh.getMesh();
  56946. // Alpha test
  56947. if (material && material.needAlphaTesting()) {
  56948. defines.push("#define ALPHATEST");
  56949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56950. attribs.push(BABYLON.VertexBuffer.UVKind);
  56951. defines.push("#define UV1");
  56952. }
  56953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56954. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56955. defines.push("#define UV2");
  56956. }
  56957. }
  56958. // Bones
  56959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56962. if (mesh.numBoneInfluencers > 4) {
  56963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56965. }
  56966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56967. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  56968. }
  56969. else {
  56970. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56971. }
  56972. // Instances
  56973. if (useInstances) {
  56974. defines.push("#define INSTANCES");
  56975. attribs.push("world0");
  56976. attribs.push("world1");
  56977. attribs.push("world2");
  56978. attribs.push("world3");
  56979. }
  56980. // Get correct effect
  56981. var join = defines.join("\n");
  56982. if (this._cachedDefines !== join) {
  56983. this._cachedDefines = join;
  56984. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56985. }
  56986. return this._effect.isReady();
  56987. };
  56988. DepthRenderer.prototype.getDepthMap = function () {
  56989. return this._depthMap;
  56990. };
  56991. // Methods
  56992. DepthRenderer.prototype.dispose = function () {
  56993. this._depthMap.dispose();
  56994. };
  56995. return DepthRenderer;
  56996. }());
  56997. BABYLON.DepthRenderer = DepthRenderer;
  56998. })(BABYLON || (BABYLON = {}));
  56999. //# sourceMappingURL=babylon.depthRenderer.js.map
  57000. var BABYLON;
  57001. (function (BABYLON) {
  57002. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57003. __extends(SSAORenderingPipeline, _super);
  57004. /**
  57005. * @constructor
  57006. * @param {string} name - The rendering pipeline name
  57007. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57008. * @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 }
  57009. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57010. */
  57011. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57012. var _this = _super.call(this, scene.getEngine(), name) || this;
  57013. // Members
  57014. /**
  57015. * The PassPostProcess id in the pipeline that contains the original scene color
  57016. * @type {string}
  57017. */
  57018. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57019. /**
  57020. * The SSAO PostProcess id in the pipeline
  57021. * @type {string}
  57022. */
  57023. _this.SSAORenderEffect = "SSAORenderEffect";
  57024. /**
  57025. * The horizontal blur PostProcess id in the pipeline
  57026. * @type {string}
  57027. */
  57028. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57029. /**
  57030. * The vertical blur PostProcess id in the pipeline
  57031. * @type {string}
  57032. */
  57033. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57034. /**
  57035. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57036. * @type {string}
  57037. */
  57038. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57039. /**
  57040. * The output strength of the SSAO post-process. Default value is 1.0.
  57041. * @type {number}
  57042. */
  57043. _this.totalStrength = 1.0;
  57044. /**
  57045. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57046. * @type {number}
  57047. */
  57048. _this.radius = 0.0001;
  57049. /**
  57050. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57051. * Must not be equal to fallOff and superior to fallOff.
  57052. * Default value is 0.975
  57053. * @type {number}
  57054. */
  57055. _this.area = 0.0075;
  57056. /**
  57057. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57058. * Must not be equal to area and inferior to area.
  57059. * Default value is 0.0
  57060. * @type {number}
  57061. */
  57062. _this.fallOff = 0.000001;
  57063. /**
  57064. * The base color of the SSAO post-process
  57065. * The final result is "base + ssao" between [0, 1]
  57066. * @type {number}
  57067. */
  57068. _this.base = 0.5;
  57069. _this._firstUpdate = true;
  57070. _this._scene = scene;
  57071. // Set up assets
  57072. _this._createRandomTexture();
  57073. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57074. var ssaoRatio = ratio.ssaoRatio || ratio;
  57075. var combineRatio = ratio.combineRatio || ratio;
  57076. _this._ratio = {
  57077. ssaoRatio: ssaoRatio,
  57078. combineRatio: combineRatio
  57079. };
  57080. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57081. _this._createSSAOPostProcess(ssaoRatio);
  57082. _this._createBlurPostProcess(ssaoRatio);
  57083. _this._createSSAOCombinePostProcess(combineRatio);
  57084. // Set up pipeline
  57085. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57086. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57087. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57088. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57089. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57090. // Finish
  57091. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57092. if (cameras)
  57093. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57094. return _this;
  57095. }
  57096. // Public Methods
  57097. /**
  57098. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57099. */
  57100. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57101. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57102. for (var i = 0; i < this._scene.cameras.length; i++) {
  57103. var camera = this._scene.cameras[i];
  57104. this._originalColorPostProcess.dispose(camera);
  57105. this._ssaoPostProcess.dispose(camera);
  57106. this._blurHPostProcess.dispose(camera);
  57107. this._blurVPostProcess.dispose(camera);
  57108. this._ssaoCombinePostProcess.dispose(camera);
  57109. }
  57110. this._randomTexture.dispose();
  57111. if (disableDepthRender)
  57112. this._scene.disableDepthRenderer();
  57113. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57114. _super.prototype.dispose.call(this);
  57115. };
  57116. // Private Methods
  57117. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57118. var _this = this;
  57119. /*
  57120. var samplerOffsets = [
  57121. -8.0, -6.0, -4.0, -2.0,
  57122. 0.0,
  57123. 2.0, 4.0, 6.0, 8.0
  57124. ];
  57125. */
  57126. var samplerOffsets = new Array();
  57127. for (var i = -8; i < 8; i++) {
  57128. samplerOffsets.push(i * 2);
  57129. }
  57130. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57131. this._blurHPostProcess.onApply = function (effect) {
  57132. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57133. effect.setTexture("depthSampler", _this._depthTexture);
  57134. if (_this._firstUpdate) {
  57135. effect.setArray("samplerOffsets", samplerOffsets);
  57136. }
  57137. };
  57138. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57139. this._blurVPostProcess.onApply = function (effect) {
  57140. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57141. effect.setTexture("depthSampler", _this._depthTexture);
  57142. if (_this._firstUpdate) {
  57143. effect.setArray("samplerOffsets", samplerOffsets);
  57144. _this._firstUpdate = false;
  57145. }
  57146. };
  57147. };
  57148. SSAORenderingPipeline.prototype._rebuild = function () {
  57149. this._firstUpdate = true;
  57150. _super.prototype._rebuild.call(this);
  57151. };
  57152. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57153. var _this = this;
  57154. var numSamples = 16;
  57155. var sampleSphere = [
  57156. 0.5381, 0.1856, -0.4319,
  57157. 0.1379, 0.2486, 0.4430,
  57158. 0.3371, 0.5679, -0.0057,
  57159. -0.6999, -0.0451, -0.0019,
  57160. 0.0689, -0.1598, -0.8547,
  57161. 0.0560, 0.0069, -0.1843,
  57162. -0.0146, 0.1402, 0.0762,
  57163. 0.0100, -0.1924, -0.0344,
  57164. -0.3577, -0.5301, -0.4358,
  57165. -0.3169, 0.1063, 0.0158,
  57166. 0.0103, -0.5869, 0.0046,
  57167. -0.0897, -0.4940, 0.3287,
  57168. 0.7119, -0.0154, -0.0918,
  57169. -0.0533, 0.0596, -0.5411,
  57170. 0.0352, -0.0631, 0.5460,
  57171. -0.4776, 0.2847, -0.0271
  57172. ];
  57173. var samplesFactor = 1.0 / numSamples;
  57174. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57175. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57176. "area", "fallOff", "base", "range", "viewport"
  57177. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57178. this._ssaoPostProcess.onApply = function (effect) {
  57179. if (_this._firstUpdate) {
  57180. effect.setArray3("sampleSphere", sampleSphere);
  57181. effect.setFloat("samplesFactor", samplesFactor);
  57182. effect.setFloat("randTextureTiles", 4.0);
  57183. }
  57184. effect.setFloat("totalStrength", _this.totalStrength);
  57185. effect.setFloat("radius", _this.radius);
  57186. effect.setFloat("area", _this.area);
  57187. effect.setFloat("fallOff", _this.fallOff);
  57188. effect.setFloat("base", _this.base);
  57189. effect.setTexture("textureSampler", _this._depthTexture);
  57190. effect.setTexture("randomSampler", _this._randomTexture);
  57191. };
  57192. };
  57193. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57194. var _this = this;
  57195. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57196. this._ssaoCombinePostProcess.onApply = function (effect) {
  57197. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57198. };
  57199. };
  57200. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57201. var size = 512;
  57202. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57203. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57204. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57205. var context = this._randomTexture.getContext();
  57206. var rand = function (min, max) {
  57207. return Math.random() * (max - min) + min;
  57208. };
  57209. var randVector = BABYLON.Vector3.Zero();
  57210. for (var x = 0; x < size; x++) {
  57211. for (var y = 0; y < size; y++) {
  57212. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57213. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57214. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57215. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57216. context.fillRect(x, y, 1, 1);
  57217. }
  57218. }
  57219. this._randomTexture.update(false);
  57220. };
  57221. __decorate([
  57222. BABYLON.serialize()
  57223. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57224. __decorate([
  57225. BABYLON.serialize()
  57226. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57227. __decorate([
  57228. BABYLON.serialize()
  57229. ], SSAORenderingPipeline.prototype, "area", void 0);
  57230. __decorate([
  57231. BABYLON.serialize()
  57232. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57233. __decorate([
  57234. BABYLON.serialize()
  57235. ], SSAORenderingPipeline.prototype, "base", void 0);
  57236. __decorate([
  57237. BABYLON.serialize()
  57238. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57239. return SSAORenderingPipeline;
  57240. }(BABYLON.PostProcessRenderPipeline));
  57241. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57242. })(BABYLON || (BABYLON = {}));
  57243. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57244. var BABYLON;
  57245. (function (BABYLON) {
  57246. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57247. __extends(SSAO2RenderingPipeline, _super);
  57248. /**
  57249. * @constructor
  57250. * @param {string} name - The rendering pipeline name
  57251. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57252. * @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 }
  57253. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57254. */
  57255. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57256. var _this = _super.call(this, scene.getEngine(), name) || this;
  57257. // Members
  57258. /**
  57259. * The PassPostProcess id in the pipeline that contains the original scene color
  57260. * @type {string}
  57261. */
  57262. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57263. /**
  57264. * The SSAO PostProcess id in the pipeline
  57265. * @type {string}
  57266. */
  57267. _this.SSAORenderEffect = "SSAORenderEffect";
  57268. /**
  57269. * The horizontal blur PostProcess id in the pipeline
  57270. * @type {string}
  57271. */
  57272. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57273. /**
  57274. * The vertical blur PostProcess id in the pipeline
  57275. * @type {string}
  57276. */
  57277. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57278. /**
  57279. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57280. * @type {string}
  57281. */
  57282. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57283. /**
  57284. * The output strength of the SSAO post-process. Default value is 1.0.
  57285. * @type {number}
  57286. */
  57287. _this.totalStrength = 1.0;
  57288. /**
  57289. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57290. * @type {number}
  57291. */
  57292. _this.maxZ = 100.0;
  57293. /**
  57294. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57295. * @type {number}
  57296. */
  57297. _this.minZAspect = 0.2;
  57298. /**
  57299. * Number of samples used for the SSAO calculations. Default value is 8
  57300. * @type {number}
  57301. */
  57302. _this._samples = 8;
  57303. /**
  57304. * Are we using bilateral blur ?
  57305. * @type {boolean}
  57306. */
  57307. _this._expensiveBlur = true;
  57308. /**
  57309. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57310. * @type {number}
  57311. */
  57312. _this.radius = 2.0;
  57313. /**
  57314. * The base color of the SSAO post-process
  57315. * The final result is "base + ssao" between [0, 1]
  57316. * @type {number}
  57317. */
  57318. _this.base = 0.1;
  57319. _this._firstUpdate = true;
  57320. _this._scene = scene;
  57321. if (!_this.isSupported) {
  57322. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57323. return _this;
  57324. }
  57325. var ssaoRatio = ratio.ssaoRatio || ratio;
  57326. var blurRatio = ratio.blurRatio || ratio;
  57327. _this._ratio = {
  57328. ssaoRatio: ssaoRatio,
  57329. blurRatio: blurRatio
  57330. };
  57331. // Set up assets
  57332. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57333. _this._createRandomTexture();
  57334. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57335. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57336. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57337. _this._createSSAOPostProcess(1.0);
  57338. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57339. _this._createSSAOCombinePostProcess(blurRatio);
  57340. // Set up pipeline
  57341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57346. // Finish
  57347. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57348. if (cameras)
  57349. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57350. return _this;
  57351. }
  57352. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57353. get: function () {
  57354. return this._samples;
  57355. },
  57356. set: function (n) {
  57357. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57358. this._samples = n;
  57359. this._sampleSphere = this._generateHemisphere();
  57360. this._firstUpdate = true;
  57361. },
  57362. enumerable: true,
  57363. configurable: true
  57364. });
  57365. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57366. get: function () {
  57367. return this._expensiveBlur;
  57368. },
  57369. set: function (b) {
  57370. 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"]);
  57371. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57372. this._expensiveBlur = b;
  57373. this._firstUpdate = true;
  57374. },
  57375. enumerable: true,
  57376. configurable: true
  57377. });
  57378. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57379. /**
  57380. * Support test.
  57381. * @type {boolean}
  57382. */
  57383. get: function () {
  57384. var engine = BABYLON.Engine.LastCreatedEngine;
  57385. if (!engine) {
  57386. return false;
  57387. }
  57388. return engine.getCaps().drawBuffersExtension;
  57389. },
  57390. enumerable: true,
  57391. configurable: true
  57392. });
  57393. // Public Methods
  57394. /**
  57395. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57396. */
  57397. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57398. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57399. for (var i = 0; i < this._scene.cameras.length; i++) {
  57400. var camera = this._scene.cameras[i];
  57401. this._originalColorPostProcess.dispose(camera);
  57402. this._ssaoPostProcess.dispose(camera);
  57403. this._blurHPostProcess.dispose(camera);
  57404. this._blurVPostProcess.dispose(camera);
  57405. this._ssaoCombinePostProcess.dispose(camera);
  57406. }
  57407. this._randomTexture.dispose();
  57408. if (disableGeometryBufferRenderer)
  57409. this._scene.disableGeometryBufferRenderer();
  57410. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57411. _super.prototype.dispose.call(this);
  57412. };
  57413. // Private Methods
  57414. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57415. var _this = this;
  57416. this._samplerOffsets = [];
  57417. var expensive = this.expensiveBlur;
  57418. for (var i = -8; i < 8; i++) {
  57419. this._samplerOffsets.push(i * 2 + 0.5);
  57420. }
  57421. 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");
  57422. this._blurHPostProcess.onApply = function (effect) {
  57423. if (!_this._scene.activeCamera) {
  57424. return;
  57425. }
  57426. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57427. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57428. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57429. effect.setFloat("radius", _this.radius);
  57430. effect.setTexture("depthSampler", _this._depthTexture);
  57431. if (_this._firstUpdate) {
  57432. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57433. }
  57434. };
  57435. 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");
  57436. this._blurVPostProcess.onApply = function (effect) {
  57437. if (!_this._scene.activeCamera) {
  57438. return;
  57439. }
  57440. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57441. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57442. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57443. effect.setFloat("radius", _this.radius);
  57444. effect.setTexture("depthSampler", _this._depthTexture);
  57445. if (_this._firstUpdate) {
  57446. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57447. _this._firstUpdate = false;
  57448. }
  57449. };
  57450. };
  57451. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57452. this._firstUpdate = true;
  57453. _super.prototype._rebuild.call(this);
  57454. };
  57455. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57456. var numSamples = this.samples;
  57457. var result = [];
  57458. var vector, scale;
  57459. var rand = function (min, max) {
  57460. return Math.random() * (max - min) + min;
  57461. };
  57462. var i = 0;
  57463. while (i < numSamples) {
  57464. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57465. vector.normalize();
  57466. scale = i / numSamples;
  57467. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57468. vector.scaleInPlace(scale);
  57469. result.push(vector.x, vector.y, vector.z);
  57470. i++;
  57471. }
  57472. return result;
  57473. };
  57474. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57475. var _this = this;
  57476. var numSamples = this.samples;
  57477. this._sampleSphere = this._generateHemisphere();
  57478. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57479. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57480. "base", "range", "projection", "near", "far", "texelSize",
  57481. "xViewport", "yViewport", "maxZ", "minZAspect"
  57482. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57483. this._ssaoPostProcess.onApply = function (effect) {
  57484. if (_this._firstUpdate) {
  57485. effect.setArray3("sampleSphere", _this._sampleSphere);
  57486. effect.setFloat("randTextureTiles", 4.0);
  57487. }
  57488. if (!_this._scene.activeCamera) {
  57489. return;
  57490. }
  57491. effect.setFloat("samplesFactor", 1 / _this.samples);
  57492. effect.setFloat("totalStrength", _this.totalStrength);
  57493. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57494. effect.setFloat("radius", _this.radius);
  57495. effect.setFloat("maxZ", _this.maxZ);
  57496. effect.setFloat("minZAspect", _this.minZAspect);
  57497. effect.setFloat("base", _this.base);
  57498. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57499. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57500. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57501. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57502. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57503. effect.setTexture("textureSampler", _this._depthTexture);
  57504. effect.setTexture("normalSampler", _this._normalTexture);
  57505. effect.setTexture("randomSampler", _this._randomTexture);
  57506. };
  57507. };
  57508. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57509. var _this = this;
  57510. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57511. this._ssaoCombinePostProcess.onApply = function (effect) {
  57512. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57513. };
  57514. };
  57515. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57516. var size = 512;
  57517. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57518. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57519. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57520. var context = this._randomTexture.getContext();
  57521. var rand = function (min, max) {
  57522. return Math.random() * (max - min) + min;
  57523. };
  57524. var randVector = BABYLON.Vector3.Zero();
  57525. for (var x = 0; x < size; x++) {
  57526. for (var y = 0; y < size; y++) {
  57527. randVector.x = rand(0.0, 1.0);
  57528. randVector.y = rand(0.0, 1.0);
  57529. randVector.z = 0.0;
  57530. randVector.normalize();
  57531. randVector.scaleInPlace(255);
  57532. randVector.x = Math.floor(randVector.x);
  57533. randVector.y = Math.floor(randVector.y);
  57534. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57535. context.fillRect(x, y, 1, 1);
  57536. }
  57537. }
  57538. this._randomTexture.update(false);
  57539. };
  57540. __decorate([
  57541. BABYLON.serialize()
  57542. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57543. __decorate([
  57544. BABYLON.serialize()
  57545. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57546. __decorate([
  57547. BABYLON.serialize()
  57548. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57549. __decorate([
  57550. BABYLON.serialize("samples")
  57551. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57552. __decorate([
  57553. BABYLON.serialize("expensiveBlur")
  57554. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57555. __decorate([
  57556. BABYLON.serialize()
  57557. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57558. __decorate([
  57559. BABYLON.serialize()
  57560. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57561. __decorate([
  57562. BABYLON.serialize()
  57563. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57564. return SSAO2RenderingPipeline;
  57565. }(BABYLON.PostProcessRenderPipeline));
  57566. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57567. })(BABYLON || (BABYLON = {}));
  57568. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57569. // BABYLON.JS Chromatic Aberration GLSL Shader
  57570. // Author: Olivier Guyot
  57571. // Separates very slightly R, G and B colors on the edges of the screen
  57572. // Inspired by Francois Tarlier & Martins Upitis
  57573. var BABYLON;
  57574. (function (BABYLON) {
  57575. var LensRenderingPipeline = /** @class */ (function (_super) {
  57576. __extends(LensRenderingPipeline, _super);
  57577. /**
  57578. * @constructor
  57579. *
  57580. * Effect parameters are as follow:
  57581. * {
  57582. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57583. * edge_blur: number; // from 0 to x (1 for realism)
  57584. * distortion: number; // from 0 to x (1 for realism)
  57585. * grain_amount: number; // from 0 to 1
  57586. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57587. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57588. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57589. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57590. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57591. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57592. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57593. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57594. * }
  57595. * Note: if an effect parameter is unset, effect is disabled
  57596. *
  57597. * @param {string} name - The rendering pipeline name
  57598. * @param {object} parameters - An object containing all parameters (see above)
  57599. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57600. * @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)
  57601. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57602. */
  57603. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57604. if (ratio === void 0) { ratio = 1.0; }
  57605. var _this = _super.call(this, scene.getEngine(), name) || this;
  57606. // Lens effects can be of the following:
  57607. // - chromatic aberration (slight shift of RGB colors)
  57608. // - blur on the edge of the lens
  57609. // - lens distortion
  57610. // - depth-of-field blur & highlights enhancing
  57611. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57612. // - grain effect (noise or custom texture)
  57613. // Two additional texture samplers are needed:
  57614. // - depth map (for depth-of-field)
  57615. // - grain texture
  57616. /**
  57617. * The chromatic aberration PostProcess id in the pipeline
  57618. * @type {string}
  57619. */
  57620. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57621. /**
  57622. * The highlights enhancing PostProcess id in the pipeline
  57623. * @type {string}
  57624. */
  57625. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57626. /**
  57627. * The depth-of-field PostProcess id in the pipeline
  57628. * @type {string}
  57629. */
  57630. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57631. _this._scene = scene;
  57632. // Fetch texture samplers
  57633. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57634. if (parameters.grain_texture) {
  57635. _this._grainTexture = parameters.grain_texture;
  57636. }
  57637. else {
  57638. _this._createGrainTexture();
  57639. }
  57640. // save parameters
  57641. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57642. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57643. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57644. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57645. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57646. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57647. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57648. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57649. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57650. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57651. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57652. // Create effects
  57653. _this._createChromaticAberrationPostProcess(ratio);
  57654. _this._createHighlightsPostProcess(ratio);
  57655. _this._createDepthOfFieldPostProcess(ratio / 4);
  57656. // Set up pipeline
  57657. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57658. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57659. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57660. if (_this._highlightsGain === -1) {
  57661. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57662. }
  57663. // Finish
  57664. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57665. if (cameras) {
  57666. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57667. }
  57668. return _this;
  57669. }
  57670. // public methods (self explanatory)
  57671. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57672. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57673. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57674. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57675. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57676. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57677. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57678. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57679. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57680. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57681. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57682. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57683. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57684. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57685. };
  57686. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57687. this._highlightsPostProcess.updateEffect();
  57688. };
  57689. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57690. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57691. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57692. this._highlightsGain = amount;
  57693. };
  57694. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57695. if (this._highlightsGain === -1) {
  57696. this._highlightsGain = 1.0;
  57697. }
  57698. this._highlightsThreshold = amount;
  57699. };
  57700. LensRenderingPipeline.prototype.disableHighlights = function () {
  57701. this._highlightsGain = -1;
  57702. };
  57703. /**
  57704. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57705. */
  57706. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57707. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57709. this._chromaticAberrationPostProcess = null;
  57710. this._highlightsPostProcess = null;
  57711. this._depthOfFieldPostProcess = null;
  57712. this._grainTexture.dispose();
  57713. if (disableDepthRender)
  57714. this._scene.disableDepthRenderer();
  57715. };
  57716. // colors shifting and distortion
  57717. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57718. var _this = this;
  57719. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57720. [], // samplers
  57721. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57722. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57723. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57724. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57725. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57726. };
  57727. };
  57728. // highlights enhancing
  57729. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57730. var _this = this;
  57731. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57732. [], // samplers
  57733. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57734. this._highlightsPostProcess.onApply = function (effect) {
  57735. effect.setFloat('gain', _this._highlightsGain);
  57736. effect.setFloat('threshold', _this._highlightsThreshold);
  57737. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57738. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57739. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57740. };
  57741. };
  57742. // colors shifting and distortion
  57743. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57744. var _this = this;
  57745. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57746. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57747. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57748. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57749. this._depthOfFieldPostProcess.onApply = function (effect) {
  57750. effect.setTexture("depthSampler", _this._depthTexture);
  57751. effect.setTexture("grainSampler", _this._grainTexture);
  57752. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57753. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57754. effect.setFloat('grain_amount', _this._grainAmount);
  57755. effect.setBool('blur_noise', _this._blurNoise);
  57756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57758. effect.setFloat('distortion', _this._distortion);
  57759. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57760. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57761. effect.setFloat('aperture', _this._dofAperture);
  57762. effect.setFloat('darken', _this._dofDarken);
  57763. effect.setFloat('edge_blur', _this._edgeBlur);
  57764. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57765. if (_this._scene.activeCamera) {
  57766. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57767. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57768. }
  57769. };
  57770. };
  57771. // creates a black and white random noise texture, 512x512
  57772. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57773. var size = 512;
  57774. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57775. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57776. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57777. var context = this._grainTexture.getContext();
  57778. var rand = function (min, max) {
  57779. return Math.random() * (max - min) + min;
  57780. };
  57781. var value;
  57782. for (var x = 0; x < size; x++) {
  57783. for (var y = 0; y < size; y++) {
  57784. value = Math.floor(rand(0.42, 0.58) * 255);
  57785. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57786. context.fillRect(x, y, 1, 1);
  57787. }
  57788. }
  57789. this._grainTexture.update(false);
  57790. };
  57791. return LensRenderingPipeline;
  57792. }(BABYLON.PostProcessRenderPipeline));
  57793. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57794. })(BABYLON || (BABYLON = {}));
  57795. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57796. var BABYLON;
  57797. (function (BABYLON) {
  57798. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57799. __extends(StandardRenderingPipeline, _super);
  57800. /**
  57801. * @constructor
  57802. * @param {string} name - The rendering pipeline name
  57803. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57804. * @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)
  57805. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57806. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57807. */
  57808. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57809. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57810. var _this = _super.call(this, scene.getEngine(), name) || this;
  57811. _this.downSampleX4PostProcess = null;
  57812. _this.brightPassPostProcess = null;
  57813. _this.blurHPostProcesses = [];
  57814. _this.blurVPostProcesses = [];
  57815. _this.textureAdderPostProcess = null;
  57816. _this.volumetricLightPostProcess = null;
  57817. _this.volumetricLightSmoothXPostProcess = null;
  57818. _this.volumetricLightSmoothYPostProcess = null;
  57819. _this.volumetricLightMergePostProces = null;
  57820. _this.volumetricLightFinalPostProcess = null;
  57821. _this.luminancePostProcess = null;
  57822. _this.luminanceDownSamplePostProcesses = [];
  57823. _this.hdrPostProcess = null;
  57824. _this.textureAdderFinalPostProcess = null;
  57825. _this.lensFlareFinalPostProcess = null;
  57826. _this.hdrFinalPostProcess = null;
  57827. _this.lensFlarePostProcess = null;
  57828. _this.lensFlareComposePostProcess = null;
  57829. _this.motionBlurPostProcess = null;
  57830. _this.depthOfFieldPostProcess = null;
  57831. // Values
  57832. _this.brightThreshold = 1.0;
  57833. _this.blurWidth = 512.0;
  57834. _this.horizontalBlur = false;
  57835. _this.exposure = 1.0;
  57836. _this.lensTexture = null;
  57837. _this.volumetricLightCoefficient = 0.2;
  57838. _this.volumetricLightPower = 4.0;
  57839. _this.volumetricLightBlurScale = 64.0;
  57840. _this.sourceLight = null;
  57841. _this.hdrMinimumLuminance = 1.0;
  57842. _this.hdrDecreaseRate = 0.5;
  57843. _this.hdrIncreaseRate = 0.5;
  57844. _this.lensColorTexture = null;
  57845. _this.lensFlareStrength = 20.0;
  57846. _this.lensFlareGhostDispersal = 1.4;
  57847. _this.lensFlareHaloWidth = 0.7;
  57848. _this.lensFlareDistortionStrength = 16.0;
  57849. _this.lensStarTexture = null;
  57850. _this.lensFlareDirtTexture = null;
  57851. _this.depthOfFieldDistance = 10.0;
  57852. _this.depthOfFieldBlurWidth = 64.0;
  57853. _this.motionStrength = 1.0;
  57854. // IAnimatable
  57855. _this.animations = [];
  57856. _this._currentDepthOfFieldSource = null;
  57857. _this._hdrCurrentLuminance = 1.0;
  57858. // Getters and setters
  57859. _this._bloomEnabled = true;
  57860. _this._depthOfFieldEnabled = false;
  57861. _this._vlsEnabled = false;
  57862. _this._lensFlareEnabled = false;
  57863. _this._hdrEnabled = false;
  57864. _this._motionBlurEnabled = false;
  57865. _this._motionBlurSamples = 64.0;
  57866. _this._volumetricLightStepsCount = 50.0;
  57867. _this._cameras = cameras || [];
  57868. // Initialize
  57869. _this._scene = scene;
  57870. _this._basePostProcess = originalPostProcess;
  57871. _this._ratio = ratio;
  57872. // Misc
  57873. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57874. // Finish
  57875. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57876. _this._buildPipeline();
  57877. return _this;
  57878. }
  57879. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57880. get: function () {
  57881. return this._bloomEnabled;
  57882. },
  57883. set: function (enabled) {
  57884. if (this._bloomEnabled === enabled) {
  57885. return;
  57886. }
  57887. this._bloomEnabled = enabled;
  57888. this._buildPipeline();
  57889. },
  57890. enumerable: true,
  57891. configurable: true
  57892. });
  57893. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57894. get: function () {
  57895. return this._depthOfFieldEnabled;
  57896. },
  57897. set: function (enabled) {
  57898. if (this._depthOfFieldEnabled === enabled) {
  57899. return;
  57900. }
  57901. this._depthOfFieldEnabled = enabled;
  57902. this._buildPipeline();
  57903. },
  57904. enumerable: true,
  57905. configurable: true
  57906. });
  57907. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57908. get: function () {
  57909. return this._lensFlareEnabled;
  57910. },
  57911. set: function (enabled) {
  57912. if (this._lensFlareEnabled === enabled) {
  57913. return;
  57914. }
  57915. this._lensFlareEnabled = enabled;
  57916. this._buildPipeline();
  57917. },
  57918. enumerable: true,
  57919. configurable: true
  57920. });
  57921. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57922. get: function () {
  57923. return this._hdrEnabled;
  57924. },
  57925. set: function (enabled) {
  57926. if (this._hdrEnabled === enabled) {
  57927. return;
  57928. }
  57929. this._hdrEnabled = enabled;
  57930. this._buildPipeline();
  57931. },
  57932. enumerable: true,
  57933. configurable: true
  57934. });
  57935. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57936. get: function () {
  57937. return this._vlsEnabled;
  57938. },
  57939. set: function (enabled) {
  57940. if (this._vlsEnabled === enabled) {
  57941. return;
  57942. }
  57943. if (enabled) {
  57944. var geometry = this._scene.enableGeometryBufferRenderer();
  57945. if (!geometry) {
  57946. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57947. return;
  57948. }
  57949. }
  57950. this._vlsEnabled = enabled;
  57951. this._buildPipeline();
  57952. },
  57953. enumerable: true,
  57954. configurable: true
  57955. });
  57956. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57957. get: function () {
  57958. return this._motionBlurEnabled;
  57959. },
  57960. set: function (enabled) {
  57961. if (this._motionBlurEnabled === enabled) {
  57962. return;
  57963. }
  57964. this._motionBlurEnabled = enabled;
  57965. this._buildPipeline();
  57966. },
  57967. enumerable: true,
  57968. configurable: true
  57969. });
  57970. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57971. get: function () {
  57972. return this._volumetricLightStepsCount;
  57973. },
  57974. set: function (count) {
  57975. if (this.volumetricLightPostProcess) {
  57976. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57977. }
  57978. this._volumetricLightStepsCount = count;
  57979. },
  57980. enumerable: true,
  57981. configurable: true
  57982. });
  57983. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57984. get: function () {
  57985. return this._motionBlurSamples;
  57986. },
  57987. set: function (samples) {
  57988. if (this.motionBlurPostProcess) {
  57989. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57990. }
  57991. this._motionBlurSamples = samples;
  57992. },
  57993. enumerable: true,
  57994. configurable: true
  57995. });
  57996. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57997. var _this = this;
  57998. var ratio = this._ratio;
  57999. var scene = this._scene;
  58000. this._disposePostProcesses();
  58001. this._reset();
  58002. // Create pass post-process
  58003. if (!this._basePostProcess) {
  58004. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58005. this.originalPostProcess.onApply = function (effect) {
  58006. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58007. };
  58008. }
  58009. else {
  58010. this.originalPostProcess = this._basePostProcess;
  58011. }
  58012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58013. this._currentDepthOfFieldSource = this.originalPostProcess;
  58014. if (this._vlsEnabled) {
  58015. // Create volumetric light
  58016. this._createVolumetricLightPostProcess(scene, ratio);
  58017. // Create volumetric light final post-process
  58018. 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);
  58019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58020. }
  58021. if (this._bloomEnabled) {
  58022. // Create down sample X4 post-process
  58023. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58024. // Create bright pass post-process
  58025. this._createBrightPassPostProcess(scene, ratio / 2);
  58026. // Create gaussian blur post-processes (down sampling blurs)
  58027. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58028. // Create texture adder post-process
  58029. this._createTextureAdderPostProcess(scene, ratio);
  58030. // Create depth-of-field source post-process
  58031. 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);
  58032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58033. }
  58034. if (this._lensFlareEnabled) {
  58035. // Create lens flare post-process
  58036. this._createLensFlarePostProcess(scene, ratio);
  58037. // Create depth-of-field source post-process post lens-flare and disable it now
  58038. 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);
  58039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58040. }
  58041. if (this._hdrEnabled) {
  58042. // Create luminance
  58043. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58044. // Create HDR
  58045. this._createHdrPostProcess(scene, ratio);
  58046. // Create depth-of-field source post-process post hdr and disable it now
  58047. 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);
  58048. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58049. }
  58050. if (this._depthOfFieldEnabled) {
  58051. // Create gaussian blur used by depth-of-field
  58052. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58053. // Create depth-of-field post-process
  58054. this._createDepthOfFieldPostProcess(scene, ratio);
  58055. }
  58056. if (this._motionBlurEnabled) {
  58057. // Create motion blur post-process
  58058. this._createMotionBlurPostProcess(scene, ratio);
  58059. }
  58060. if (this._cameras !== null) {
  58061. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58062. }
  58063. };
  58064. // Down Sample X4 Post-Processs
  58065. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58066. var _this = this;
  58067. var downSampleX4Offsets = new Array(32);
  58068. 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);
  58069. this.downSampleX4PostProcess.onApply = function (effect) {
  58070. var id = 0;
  58071. var width = _this.downSampleX4PostProcess.width;
  58072. var height = _this.downSampleX4PostProcess.height;
  58073. for (var i = -2; i < 2; i++) {
  58074. for (var j = -2; j < 2; j++) {
  58075. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58076. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58077. id += 2;
  58078. }
  58079. }
  58080. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58081. };
  58082. // Add to pipeline
  58083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58084. };
  58085. // Brightpass Post-Process
  58086. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58087. var _this = this;
  58088. var brightOffsets = new Array(8);
  58089. 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);
  58090. this.brightPassPostProcess.onApply = function (effect) {
  58091. var sU = (1.0 / _this.brightPassPostProcess.width);
  58092. var sV = (1.0 / _this.brightPassPostProcess.height);
  58093. brightOffsets[0] = -0.5 * sU;
  58094. brightOffsets[1] = 0.5 * sV;
  58095. brightOffsets[2] = 0.5 * sU;
  58096. brightOffsets[3] = 0.5 * sV;
  58097. brightOffsets[4] = -0.5 * sU;
  58098. brightOffsets[5] = -0.5 * sV;
  58099. brightOffsets[6] = 0.5 * sU;
  58100. brightOffsets[7] = -0.5 * sV;
  58101. effect.setArray2("dsOffsets", brightOffsets);
  58102. effect.setFloat("brightThreshold", _this.brightThreshold);
  58103. };
  58104. // Add to pipeline
  58105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58106. };
  58107. // Create blur H&V post-processes
  58108. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58109. var _this = this;
  58110. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58111. var engine = scene.getEngine();
  58112. 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);
  58113. 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);
  58114. blurX.onActivateObservable.add(function () {
  58115. var dw = blurX.width / engine.getRenderWidth();
  58116. blurX.kernel = _this[blurWidthKey] * dw;
  58117. });
  58118. blurY.onActivateObservable.add(function () {
  58119. var dw = blurY.height / engine.getRenderHeight();
  58120. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58121. });
  58122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58124. this.blurHPostProcesses.push(blurX);
  58125. this.blurVPostProcesses.push(blurY);
  58126. };
  58127. // Create texture adder post-process
  58128. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58129. var _this = this;
  58130. 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);
  58131. this.textureAdderPostProcess.onApply = function (effect) {
  58132. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58133. effect.setTexture("lensSampler", _this.lensTexture);
  58134. effect.setFloat("exposure", _this.exposure);
  58135. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58136. };
  58137. // Add to pipeline
  58138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58139. };
  58140. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58141. var _this = this;
  58142. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58143. geometryRenderer.enablePosition = true;
  58144. var geometry = geometryRenderer.getGBuffer();
  58145. // Base post-process
  58146. 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));
  58147. var depthValues = BABYLON.Vector2.Zero();
  58148. this.volumetricLightPostProcess.onApply = function (effect) {
  58149. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58150. var generator = _this.sourceLight.getShadowGenerator();
  58151. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58152. effect.setTexture("positionSampler", geometry.textures[2]);
  58153. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58154. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58155. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58156. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58157. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58158. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58159. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58160. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58161. effect.setVector2("depthValues", depthValues);
  58162. }
  58163. };
  58164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58165. // Smooth
  58166. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58167. // Merge
  58168. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58169. this.volumetricLightMergePostProces.onApply = function (effect) {
  58170. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58171. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58172. };
  58173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58174. };
  58175. // Create luminance
  58176. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58177. var _this = this;
  58178. // Create luminance
  58179. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58180. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58181. var offsets = [];
  58182. this.luminancePostProcess.onApply = function (effect) {
  58183. var sU = (1.0 / _this.luminancePostProcess.width);
  58184. var sV = (1.0 / _this.luminancePostProcess.height);
  58185. offsets[0] = -0.5 * sU;
  58186. offsets[1] = 0.5 * sV;
  58187. offsets[2] = 0.5 * sU;
  58188. offsets[3] = 0.5 * sV;
  58189. offsets[4] = -0.5 * sU;
  58190. offsets[5] = -0.5 * sV;
  58191. offsets[6] = 0.5 * sU;
  58192. offsets[7] = -0.5 * sV;
  58193. effect.setArray2("lumOffsets", offsets);
  58194. };
  58195. // Add to pipeline
  58196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58197. // Create down sample luminance
  58198. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58199. var size = Math.pow(3, i);
  58200. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58201. if (i === 0) {
  58202. defines += "#define FINAL_DOWN_SAMPLER";
  58203. }
  58204. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58205. this.luminanceDownSamplePostProcesses.push(postProcess);
  58206. }
  58207. // Create callbacks and add effects
  58208. var lastLuminance = this.luminancePostProcess;
  58209. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58210. var downSampleOffsets = new Array(18);
  58211. pp.onApply = function (effect) {
  58212. if (!lastLuminance) {
  58213. return;
  58214. }
  58215. var id = 0;
  58216. for (var x = -1; x < 2; x++) {
  58217. for (var y = -1; y < 2; y++) {
  58218. downSampleOffsets[id] = x / lastLuminance.width;
  58219. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58220. id += 2;
  58221. }
  58222. }
  58223. effect.setArray2("dsOffsets", downSampleOffsets);
  58224. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58225. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58226. lastLuminance = _this.luminancePostProcess;
  58227. }
  58228. else {
  58229. lastLuminance = pp;
  58230. }
  58231. };
  58232. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58233. pp.onAfterRender = function (effect) {
  58234. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58235. 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);
  58236. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58237. };
  58238. }
  58239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58240. });
  58241. };
  58242. // Create HDR post-process
  58243. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58244. var _this = this;
  58245. 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);
  58246. var outputLiminance = 1;
  58247. var time = 0;
  58248. var lastTime = 0;
  58249. this.hdrPostProcess.onApply = function (effect) {
  58250. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58251. time += scene.getEngine().getDeltaTime();
  58252. if (outputLiminance < 0) {
  58253. outputLiminance = _this._hdrCurrentLuminance;
  58254. }
  58255. else {
  58256. var dt = (lastTime - time) / 1000.0;
  58257. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58258. outputLiminance += _this.hdrDecreaseRate * dt;
  58259. }
  58260. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58261. outputLiminance -= _this.hdrIncreaseRate * dt;
  58262. }
  58263. else {
  58264. outputLiminance = _this._hdrCurrentLuminance;
  58265. }
  58266. }
  58267. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58268. effect.setFloat("averageLuminance", outputLiminance);
  58269. lastTime = time;
  58270. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58271. };
  58272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58273. };
  58274. // Create lens flare post-process
  58275. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58276. var _this = this;
  58277. 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);
  58278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58279. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58280. 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);
  58281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58282. var resolution = new BABYLON.Vector2(0, 0);
  58283. // Lens flare
  58284. this.lensFlarePostProcess.onApply = function (effect) {
  58285. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58286. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58287. effect.setFloat("strength", _this.lensFlareStrength);
  58288. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58289. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58290. // Shift
  58291. resolution.x = _this.lensFlarePostProcess.width;
  58292. resolution.y = _this.lensFlarePostProcess.height;
  58293. effect.setVector2("resolution", resolution);
  58294. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58295. };
  58296. // Compose
  58297. 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);
  58298. 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);
  58299. this.lensFlareComposePostProcess.onApply = function (effect) {
  58300. if (!_this._scene.activeCamera) {
  58301. return;
  58302. }
  58303. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58304. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58305. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58306. // Lens start rotation matrix
  58307. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58308. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58309. 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));
  58310. camRot *= 4.0;
  58311. 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);
  58312. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58313. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58314. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58315. };
  58316. };
  58317. // Create depth-of-field post-process
  58318. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58319. var _this = this;
  58320. 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);
  58321. this.depthOfFieldPostProcess.onApply = function (effect) {
  58322. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58323. effect.setTexture("depthSampler", _this._getDepthTexture());
  58324. effect.setFloat("distance", _this.depthOfFieldDistance);
  58325. };
  58326. // Add to pipeline
  58327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58328. };
  58329. // Create motion blur post-process
  58330. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58331. var _this = this;
  58332. 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);
  58333. var motionScale = 0;
  58334. var prevViewProjection = BABYLON.Matrix.Identity();
  58335. var invViewProjection = BABYLON.Matrix.Identity();
  58336. var viewProjection = BABYLON.Matrix.Identity();
  58337. var screenSize = BABYLON.Vector2.Zero();
  58338. this.motionBlurPostProcess.onApply = function (effect) {
  58339. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58340. viewProjection.invertToRef(invViewProjection);
  58341. effect.setMatrix("inverseViewProjection", invViewProjection);
  58342. effect.setMatrix("prevViewProjection", prevViewProjection);
  58343. prevViewProjection = viewProjection;
  58344. screenSize.x = _this.motionBlurPostProcess.width;
  58345. screenSize.y = _this.motionBlurPostProcess.height;
  58346. effect.setVector2("screenSize", screenSize);
  58347. motionScale = scene.getEngine().getFps() / 60.0;
  58348. effect.setFloat("motionScale", motionScale);
  58349. effect.setFloat("motionStrength", _this.motionStrength);
  58350. effect.setTexture("depthSampler", _this._getDepthTexture());
  58351. };
  58352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58353. };
  58354. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58355. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58356. var renderer = this._scene.enableGeometryBufferRenderer();
  58357. return renderer.getGBuffer().textures[0];
  58358. }
  58359. return this._scene.enableDepthRenderer().getDepthMap();
  58360. };
  58361. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58362. for (var i = 0; i < this._cameras.length; i++) {
  58363. var camera = this._cameras[i];
  58364. if (this.originalPostProcess) {
  58365. this.originalPostProcess.dispose(camera);
  58366. }
  58367. if (this.downSampleX4PostProcess) {
  58368. this.downSampleX4PostProcess.dispose(camera);
  58369. }
  58370. if (this.brightPassPostProcess) {
  58371. this.brightPassPostProcess.dispose(camera);
  58372. }
  58373. if (this.textureAdderPostProcess) {
  58374. this.textureAdderPostProcess.dispose(camera);
  58375. }
  58376. if (this.textureAdderFinalPostProcess) {
  58377. this.textureAdderFinalPostProcess.dispose(camera);
  58378. }
  58379. if (this.volumetricLightPostProcess) {
  58380. this.volumetricLightPostProcess.dispose(camera);
  58381. }
  58382. if (this.volumetricLightSmoothXPostProcess) {
  58383. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58384. }
  58385. if (this.volumetricLightSmoothYPostProcess) {
  58386. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58387. }
  58388. if (this.volumetricLightMergePostProces) {
  58389. this.volumetricLightMergePostProces.dispose(camera);
  58390. }
  58391. if (this.volumetricLightFinalPostProcess) {
  58392. this.volumetricLightFinalPostProcess.dispose(camera);
  58393. }
  58394. if (this.lensFlarePostProcess) {
  58395. this.lensFlarePostProcess.dispose(camera);
  58396. }
  58397. if (this.lensFlareComposePostProcess) {
  58398. this.lensFlareComposePostProcess.dispose(camera);
  58399. }
  58400. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58401. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58402. }
  58403. if (this.luminancePostProcess) {
  58404. this.luminancePostProcess.dispose(camera);
  58405. }
  58406. if (this.hdrPostProcess) {
  58407. this.hdrPostProcess.dispose(camera);
  58408. }
  58409. if (this.hdrFinalPostProcess) {
  58410. this.hdrFinalPostProcess.dispose(camera);
  58411. }
  58412. if (this.depthOfFieldPostProcess) {
  58413. this.depthOfFieldPostProcess.dispose(camera);
  58414. }
  58415. if (this.motionBlurPostProcess) {
  58416. this.motionBlurPostProcess.dispose(camera);
  58417. }
  58418. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58419. this.blurHPostProcesses[j].dispose(camera);
  58420. }
  58421. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58422. this.blurVPostProcesses[j].dispose(camera);
  58423. }
  58424. }
  58425. this.originalPostProcess = null;
  58426. this.downSampleX4PostProcess = null;
  58427. this.brightPassPostProcess = null;
  58428. this.textureAdderPostProcess = null;
  58429. this.textureAdderFinalPostProcess = null;
  58430. this.volumetricLightPostProcess = null;
  58431. this.volumetricLightSmoothXPostProcess = null;
  58432. this.volumetricLightSmoothYPostProcess = null;
  58433. this.volumetricLightMergePostProces = null;
  58434. this.volumetricLightFinalPostProcess = null;
  58435. this.lensFlarePostProcess = null;
  58436. this.lensFlareComposePostProcess = null;
  58437. this.luminancePostProcess = null;
  58438. this.hdrPostProcess = null;
  58439. this.hdrFinalPostProcess = null;
  58440. this.depthOfFieldPostProcess = null;
  58441. this.motionBlurPostProcess = null;
  58442. this.luminanceDownSamplePostProcesses = [];
  58443. this.blurHPostProcesses = [];
  58444. this.blurVPostProcesses = [];
  58445. };
  58446. // Dispose
  58447. StandardRenderingPipeline.prototype.dispose = function () {
  58448. this._disposePostProcesses();
  58449. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58450. _super.prototype.dispose.call(this);
  58451. };
  58452. // Serialize rendering pipeline
  58453. StandardRenderingPipeline.prototype.serialize = function () {
  58454. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58455. serializationObject.customType = "StandardRenderingPipeline";
  58456. return serializationObject;
  58457. };
  58458. /**
  58459. * Static members
  58460. */
  58461. // Parse serialized pipeline
  58462. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58463. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58464. };
  58465. // Luminance steps
  58466. StandardRenderingPipeline.LuminanceSteps = 6;
  58467. __decorate([
  58468. BABYLON.serialize()
  58469. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58470. __decorate([
  58471. BABYLON.serialize()
  58472. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58473. __decorate([
  58474. BABYLON.serialize()
  58475. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58476. __decorate([
  58477. BABYLON.serialize()
  58478. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58479. __decorate([
  58480. BABYLON.serializeAsTexture("lensTexture")
  58481. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58482. __decorate([
  58483. BABYLON.serialize()
  58484. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58485. __decorate([
  58486. BABYLON.serialize()
  58487. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58488. __decorate([
  58489. BABYLON.serialize()
  58490. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58491. __decorate([
  58492. BABYLON.serialize()
  58493. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58494. __decorate([
  58495. BABYLON.serialize()
  58496. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58497. __decorate([
  58498. BABYLON.serialize()
  58499. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58500. __decorate([
  58501. BABYLON.serializeAsTexture("lensColorTexture")
  58502. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58503. __decorate([
  58504. BABYLON.serialize()
  58505. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58506. __decorate([
  58507. BABYLON.serialize()
  58508. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58509. __decorate([
  58510. BABYLON.serialize()
  58511. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58512. __decorate([
  58513. BABYLON.serialize()
  58514. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58515. __decorate([
  58516. BABYLON.serializeAsTexture("lensStarTexture")
  58517. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58518. __decorate([
  58519. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58520. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58521. __decorate([
  58522. BABYLON.serialize()
  58523. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58524. __decorate([
  58525. BABYLON.serialize()
  58526. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58527. __decorate([
  58528. BABYLON.serialize()
  58529. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58530. __decorate([
  58531. BABYLON.serialize()
  58532. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58533. __decorate([
  58534. BABYLON.serialize()
  58535. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58536. __decorate([
  58537. BABYLON.serialize()
  58538. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58539. __decorate([
  58540. BABYLON.serialize()
  58541. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58542. __decorate([
  58543. BABYLON.serialize()
  58544. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58545. __decorate([
  58546. BABYLON.serialize()
  58547. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58548. __decorate([
  58549. BABYLON.serialize()
  58550. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58551. __decorate([
  58552. BABYLON.serialize()
  58553. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58554. return StandardRenderingPipeline;
  58555. }(BABYLON.PostProcessRenderPipeline));
  58556. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58557. })(BABYLON || (BABYLON = {}));
  58558. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58559. var BABYLON;
  58560. (function (BABYLON) {
  58561. var FxaaPostProcess = /** @class */ (function (_super) {
  58562. __extends(FxaaPostProcess, _super);
  58563. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58564. if (camera === void 0) { camera = null; }
  58565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58566. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58567. _this.onApplyObservable.add(function (effect) {
  58568. var texelSize = _this.texelSize;
  58569. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58570. });
  58571. return _this;
  58572. }
  58573. return FxaaPostProcess;
  58574. }(BABYLON.PostProcess));
  58575. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58576. })(BABYLON || (BABYLON = {}));
  58577. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58578. var BABYLON;
  58579. (function (BABYLON) {
  58580. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58581. __extends(DefaultRenderingPipeline, _super);
  58582. /**
  58583. * @constructor
  58584. * @param {string} name - The rendering pipeline name
  58585. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58586. * @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)
  58587. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58588. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58589. */
  58590. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58591. if (automaticBuild === void 0) { automaticBuild = true; }
  58592. var _this = _super.call(this, scene.getEngine(), name) || this;
  58593. _this.PassPostProcessId = "PassPostProcessEffect";
  58594. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58595. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58596. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58597. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58598. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58599. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58600. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58601. // IAnimatable
  58602. _this.animations = [];
  58603. // Values
  58604. _this._bloomEnabled = false;
  58605. _this._fxaaEnabled = false;
  58606. _this._imageProcessingEnabled = true;
  58607. _this._bloomScale = 0.6;
  58608. _this._buildAllowed = true;
  58609. /**
  58610. * Specifies the size of the bloom blur kernel, relative to the final output size
  58611. */
  58612. _this.bloomKernel = 64;
  58613. /**
  58614. * Specifies the weight of the bloom in the final rendering
  58615. */
  58616. _this._bloomWeight = 0.15;
  58617. _this._cameras = cameras || [];
  58618. _this._buildAllowed = automaticBuild;
  58619. // Initialize
  58620. _this._scene = scene;
  58621. var caps = _this._scene.getEngine().getCaps();
  58622. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58623. // Misc
  58624. if (_this._hdr) {
  58625. if (caps.textureHalfFloatRender) {
  58626. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58627. }
  58628. else if (caps.textureFloatRender) {
  58629. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58630. }
  58631. }
  58632. else {
  58633. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58634. }
  58635. // Attach
  58636. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58637. _this._buildPipeline();
  58638. return _this;
  58639. }
  58640. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58641. get: function () {
  58642. return this._bloomWeight;
  58643. },
  58644. set: function (value) {
  58645. if (this._bloomWeight === value) {
  58646. return;
  58647. }
  58648. this._bloomWeight = value;
  58649. if (this._hdr && this.copyBack) {
  58650. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58651. }
  58652. },
  58653. enumerable: true,
  58654. configurable: true
  58655. });
  58656. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58657. get: function () {
  58658. return this._bloomScale;
  58659. },
  58660. set: function (value) {
  58661. if (this._bloomScale === value) {
  58662. return;
  58663. }
  58664. this._bloomScale = value;
  58665. this._buildPipeline();
  58666. },
  58667. enumerable: true,
  58668. configurable: true
  58669. });
  58670. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58671. get: function () {
  58672. return this._bloomEnabled;
  58673. },
  58674. set: function (enabled) {
  58675. if (this._bloomEnabled === enabled) {
  58676. return;
  58677. }
  58678. this._bloomEnabled = enabled;
  58679. this._buildPipeline();
  58680. },
  58681. enumerable: true,
  58682. configurable: true
  58683. });
  58684. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58685. get: function () {
  58686. return this._fxaaEnabled;
  58687. },
  58688. set: function (enabled) {
  58689. if (this._fxaaEnabled === enabled) {
  58690. return;
  58691. }
  58692. this._fxaaEnabled = enabled;
  58693. this._buildPipeline();
  58694. },
  58695. enumerable: true,
  58696. configurable: true
  58697. });
  58698. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58699. get: function () {
  58700. return this._imageProcessingEnabled;
  58701. },
  58702. set: function (enabled) {
  58703. if (this._imageProcessingEnabled === enabled) {
  58704. return;
  58705. }
  58706. this._imageProcessingEnabled = enabled;
  58707. this._buildPipeline();
  58708. },
  58709. enumerable: true,
  58710. configurable: true
  58711. });
  58712. /**
  58713. * Force the compilation of the entire pipeline.
  58714. */
  58715. DefaultRenderingPipeline.prototype.prepare = function () {
  58716. var previousState = this._buildAllowed;
  58717. this._buildAllowed = true;
  58718. this._buildPipeline();
  58719. this._buildAllowed = previousState;
  58720. };
  58721. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58722. var _this = this;
  58723. if (!this._buildAllowed) {
  58724. return;
  58725. }
  58726. var engine = this._scene.getEngine();
  58727. this._disposePostProcesses();
  58728. this._reset();
  58729. if (this.bloomEnabled) {
  58730. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58731. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58732. if (!this._hdr) {
  58733. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58734. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58735. this.highlights.autoClear = false;
  58736. this.highlights.alwaysForcePOT = true;
  58737. }
  58738. 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);
  58739. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58740. this.blurX.alwaysForcePOT = true;
  58741. this.blurX.autoClear = false;
  58742. this.blurX.onActivateObservable.add(function () {
  58743. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58744. _this.blurX.kernel = _this.bloomKernel * dw;
  58745. });
  58746. 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);
  58747. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58748. this.blurY.alwaysForcePOT = true;
  58749. this.blurY.autoClear = false;
  58750. this.blurY.onActivateObservable.add(function () {
  58751. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58752. _this.blurY.kernel = _this.bloomKernel * dh;
  58753. });
  58754. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58755. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58756. this.copyBack.alwaysForcePOT = true;
  58757. if (this._hdr) {
  58758. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58759. var w = this.bloomWeight;
  58760. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58761. }
  58762. else {
  58763. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58764. }
  58765. this.copyBack.autoClear = false;
  58766. }
  58767. if (this._imageProcessingEnabled) {
  58768. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58769. if (this._hdr) {
  58770. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58771. }
  58772. else {
  58773. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58774. }
  58775. }
  58776. if (this.fxaaEnabled) {
  58777. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58778. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58779. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58780. }
  58781. else {
  58782. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58783. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58784. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58785. }
  58786. if (this.bloomEnabled) {
  58787. if (this._hdr) {
  58788. this.copyBack.shareOutputWith(this.blurX);
  58789. if (this.imageProcessing) {
  58790. this.imageProcessing.shareOutputWith(this.pass);
  58791. this.imageProcessing.autoClear = false;
  58792. }
  58793. else if (this.fxaa) {
  58794. this.fxaa.shareOutputWith(this.pass);
  58795. }
  58796. else {
  58797. this.finalMerge.shareOutputWith(this.pass);
  58798. }
  58799. }
  58800. else {
  58801. if (this.fxaa) {
  58802. this.fxaa.shareOutputWith(this.pass);
  58803. }
  58804. else {
  58805. this.finalMerge.shareOutputWith(this.pass);
  58806. }
  58807. }
  58808. }
  58809. if (this._cameras !== null) {
  58810. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58811. }
  58812. };
  58813. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58814. for (var i = 0; i < this._cameras.length; i++) {
  58815. var camera = this._cameras[i];
  58816. if (this.pass) {
  58817. this.pass.dispose(camera);
  58818. }
  58819. if (this.highlights) {
  58820. this.highlights.dispose(camera);
  58821. }
  58822. if (this.blurX) {
  58823. this.blurX.dispose(camera);
  58824. }
  58825. if (this.blurY) {
  58826. this.blurY.dispose(camera);
  58827. }
  58828. if (this.copyBack) {
  58829. this.copyBack.dispose(camera);
  58830. }
  58831. if (this.imageProcessing) {
  58832. this.imageProcessing.dispose(camera);
  58833. }
  58834. if (this.fxaa) {
  58835. this.fxaa.dispose(camera);
  58836. }
  58837. if (this.finalMerge) {
  58838. this.finalMerge.dispose(camera);
  58839. }
  58840. }
  58841. this.pass = null;
  58842. this.highlights = null;
  58843. this.blurX = null;
  58844. this.blurY = null;
  58845. this.copyBack = null;
  58846. this.imageProcessing = null;
  58847. this.fxaa = null;
  58848. this.finalMerge = null;
  58849. };
  58850. // Dispose
  58851. DefaultRenderingPipeline.prototype.dispose = function () {
  58852. this._disposePostProcesses();
  58853. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58854. _super.prototype.dispose.call(this);
  58855. };
  58856. // Serialize rendering pipeline
  58857. DefaultRenderingPipeline.prototype.serialize = function () {
  58858. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58859. serializationObject.customType = "DefaultRenderingPipeline";
  58860. return serializationObject;
  58861. };
  58862. // Parse serialized pipeline
  58863. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58864. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58865. };
  58866. __decorate([
  58867. BABYLON.serialize()
  58868. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58869. __decorate([
  58870. BABYLON.serialize()
  58871. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58872. __decorate([
  58873. BABYLON.serialize()
  58874. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58875. __decorate([
  58876. BABYLON.serialize()
  58877. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58878. __decorate([
  58879. BABYLON.serialize()
  58880. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58881. __decorate([
  58882. BABYLON.serialize()
  58883. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58884. __decorate([
  58885. BABYLON.serialize()
  58886. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58887. __decorate([
  58888. BABYLON.serialize()
  58889. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58890. return DefaultRenderingPipeline;
  58891. }(BABYLON.PostProcessRenderPipeline));
  58892. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58893. })(BABYLON || (BABYLON = {}));
  58894. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58895. var BABYLON;
  58896. (function (BABYLON) {
  58897. var GeometryBufferRenderer = /** @class */ (function () {
  58898. function GeometryBufferRenderer(scene, ratio) {
  58899. if (ratio === void 0) { ratio = 1; }
  58900. this._enablePosition = false;
  58901. this._scene = scene;
  58902. this._ratio = ratio;
  58903. // Render target
  58904. this._createRenderTargets();
  58905. }
  58906. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58907. set: function (meshes) {
  58908. this._multiRenderTarget.renderList = meshes;
  58909. },
  58910. enumerable: true,
  58911. configurable: true
  58912. });
  58913. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58914. get: function () {
  58915. return this._multiRenderTarget.isSupported;
  58916. },
  58917. enumerable: true,
  58918. configurable: true
  58919. });
  58920. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58921. get: function () {
  58922. return this._enablePosition;
  58923. },
  58924. set: function (enable) {
  58925. this._enablePosition = enable;
  58926. this.dispose();
  58927. this._createRenderTargets();
  58928. },
  58929. enumerable: true,
  58930. configurable: true
  58931. });
  58932. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58933. var material = subMesh.getMaterial();
  58934. if (material && material.disableDepthWrite) {
  58935. return false;
  58936. }
  58937. var defines = [];
  58938. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58939. var mesh = subMesh.getMesh();
  58940. // Alpha test
  58941. if (material && material.needAlphaTesting()) {
  58942. defines.push("#define ALPHATEST");
  58943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58944. attribs.push(BABYLON.VertexBuffer.UVKind);
  58945. defines.push("#define UV1");
  58946. }
  58947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58949. defines.push("#define UV2");
  58950. }
  58951. }
  58952. // Buffers
  58953. if (this._enablePosition) {
  58954. defines.push("#define POSITION");
  58955. }
  58956. // Bones
  58957. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58960. if (mesh.numBoneInfluencers > 4) {
  58961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58963. }
  58964. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58965. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58966. }
  58967. else {
  58968. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58969. }
  58970. // Instances
  58971. if (useInstances) {
  58972. defines.push("#define INSTANCES");
  58973. attribs.push("world0");
  58974. attribs.push("world1");
  58975. attribs.push("world2");
  58976. attribs.push("world3");
  58977. }
  58978. // Get correct effect
  58979. var join = defines.join("\n");
  58980. if (this._cachedDefines !== join) {
  58981. this._cachedDefines = join;
  58982. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  58983. }
  58984. return this._effect.isReady();
  58985. };
  58986. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58987. return this._multiRenderTarget;
  58988. };
  58989. // Methods
  58990. GeometryBufferRenderer.prototype.dispose = function () {
  58991. this.getGBuffer().dispose();
  58992. };
  58993. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58994. var _this = this;
  58995. var engine = this._scene.getEngine();
  58996. var count = this._enablePosition ? 3 : 2;
  58997. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58998. if (!this.isSupported) {
  58999. return;
  59000. }
  59001. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59002. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59003. this._multiRenderTarget.refreshRate = 1;
  59004. this._multiRenderTarget.renderParticles = false;
  59005. this._multiRenderTarget.renderList = null;
  59006. // set default depth value to 1.0 (far away)
  59007. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59008. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59009. });
  59010. // Custom render function
  59011. var renderSubMesh = function (subMesh) {
  59012. var mesh = subMesh.getRenderingMesh();
  59013. var scene = _this._scene;
  59014. var engine = scene.getEngine();
  59015. var material = subMesh.getMaterial();
  59016. if (!material) {
  59017. return;
  59018. }
  59019. // Culling
  59020. engine.setState(material.backFaceCulling);
  59021. // Managing instances
  59022. var batch = mesh._getInstancesRenderList(subMesh._id);
  59023. if (batch.mustReturn) {
  59024. return;
  59025. }
  59026. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59027. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59028. engine.enableEffect(_this._effect);
  59029. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59030. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59031. _this._effect.setMatrix("view", scene.getViewMatrix());
  59032. // Alpha test
  59033. if (material && material.needAlphaTesting()) {
  59034. var alphaTexture = material.getAlphaTestTexture();
  59035. if (alphaTexture) {
  59036. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59037. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59038. }
  59039. }
  59040. // Bones
  59041. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59042. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59043. }
  59044. // Draw
  59045. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59046. }
  59047. };
  59048. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59049. var index;
  59050. if (depthOnlySubMeshes.length) {
  59051. engine.setColorWrite(false);
  59052. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59053. renderSubMesh(depthOnlySubMeshes.data[index]);
  59054. }
  59055. engine.setColorWrite(true);
  59056. }
  59057. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59058. renderSubMesh(opaqueSubMeshes.data[index]);
  59059. }
  59060. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59061. renderSubMesh(alphaTestSubMeshes.data[index]);
  59062. }
  59063. };
  59064. };
  59065. return GeometryBufferRenderer;
  59066. }());
  59067. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59068. })(BABYLON || (BABYLON = {}));
  59069. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59070. var BABYLON;
  59071. (function (BABYLON) {
  59072. var RefractionPostProcess = /** @class */ (function (_super) {
  59073. __extends(RefractionPostProcess, _super);
  59074. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59075. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59076. _this.color = color;
  59077. _this.depth = depth;
  59078. _this.colorLevel = colorLevel;
  59079. _this.onActivateObservable.add(function (cam) {
  59080. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59081. });
  59082. _this.onApplyObservable.add(function (effect) {
  59083. effect.setColor3("baseColor", _this.color);
  59084. effect.setFloat("depth", _this.depth);
  59085. effect.setFloat("colorLevel", _this.colorLevel);
  59086. effect.setTexture("refractionSampler", _this._refRexture);
  59087. });
  59088. return _this;
  59089. }
  59090. // Methods
  59091. RefractionPostProcess.prototype.dispose = function (camera) {
  59092. if (this._refRexture) {
  59093. this._refRexture.dispose();
  59094. }
  59095. _super.prototype.dispose.call(this, camera);
  59096. };
  59097. return RefractionPostProcess;
  59098. }(BABYLON.PostProcess));
  59099. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59100. })(BABYLON || (BABYLON = {}));
  59101. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59102. var BABYLON;
  59103. (function (BABYLON) {
  59104. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59105. __extends(BlackAndWhitePostProcess, _super);
  59106. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59107. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59108. _this.degree = 1;
  59109. _this.onApplyObservable.add(function (effect) {
  59110. effect.setFloat("degree", _this.degree);
  59111. });
  59112. return _this;
  59113. }
  59114. return BlackAndWhitePostProcess;
  59115. }(BABYLON.PostProcess));
  59116. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59117. })(BABYLON || (BABYLON = {}));
  59118. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59119. var BABYLON;
  59120. (function (BABYLON) {
  59121. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59122. __extends(ConvolutionPostProcess, _super);
  59123. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59124. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59125. _this.kernel = kernel;
  59126. _this.onApply = function (effect) {
  59127. effect.setFloat2("screenSize", _this.width, _this.height);
  59128. effect.setArray("kernel", _this.kernel);
  59129. };
  59130. return _this;
  59131. }
  59132. // Statics
  59133. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59134. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59135. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59136. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59137. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59138. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59139. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59140. return ConvolutionPostProcess;
  59141. }(BABYLON.PostProcess));
  59142. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59143. })(BABYLON || (BABYLON = {}));
  59144. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59145. var BABYLON;
  59146. (function (BABYLON) {
  59147. var FilterPostProcess = /** @class */ (function (_super) {
  59148. __extends(FilterPostProcess, _super);
  59149. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59150. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59151. _this.kernelMatrix = kernelMatrix;
  59152. _this.onApply = function (effect) {
  59153. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59154. };
  59155. return _this;
  59156. }
  59157. return FilterPostProcess;
  59158. }(BABYLON.PostProcess));
  59159. BABYLON.FilterPostProcess = FilterPostProcess;
  59160. })(BABYLON || (BABYLON = {}));
  59161. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59162. var BABYLON;
  59163. (function (BABYLON) {
  59164. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59165. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59166. __extends(VolumetricLightScatteringPostProcess, _super);
  59167. /**
  59168. * @constructor
  59169. * @param {string} name - The post-process name
  59170. * @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)
  59171. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59172. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59173. * @param {number} samples - The post-process quality, default 100
  59174. * @param {number} samplingMode - The post-process filtering mode
  59175. * @param {BABYLON.Engine} engine - The babylon engine
  59176. * @param {boolean} reusable - If the post-process is reusable
  59177. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59178. */
  59179. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59180. if (samples === void 0) { samples = 100; }
  59181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59182. 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;
  59183. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59184. /**
  59185. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59186. * @type {Vector3}
  59187. */
  59188. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59189. /**
  59190. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59191. * @type {boolean}
  59192. */
  59193. _this.useCustomMeshPosition = false;
  59194. /**
  59195. * If the post-process should inverse the light scattering direction
  59196. * @type {boolean}
  59197. */
  59198. _this.invert = true;
  59199. /**
  59200. * Array containing the excluded meshes not rendered in the internal pass
  59201. */
  59202. _this.excludedMeshes = new Array();
  59203. /**
  59204. * Controls the overall intensity of the post-process
  59205. * @type {number}
  59206. */
  59207. _this.exposure = 0.3;
  59208. /**
  59209. * Dissipates each sample's contribution in range [0, 1]
  59210. * @type {number}
  59211. */
  59212. _this.decay = 0.96815;
  59213. /**
  59214. * Controls the overall intensity of each sample
  59215. * @type {number}
  59216. */
  59217. _this.weight = 0.58767;
  59218. /**
  59219. * Controls the density of each sample
  59220. * @type {number}
  59221. */
  59222. _this.density = 0.926;
  59223. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59224. engine = scene.getEngine();
  59225. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59226. // Configure mesh
  59227. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59228. // Configure
  59229. _this._createPass(scene, ratio.passRatio || ratio);
  59230. _this.onActivate = function (camera) {
  59231. if (!_this.isSupported) {
  59232. _this.dispose(camera);
  59233. }
  59234. _this.onActivate = null;
  59235. };
  59236. _this.onApplyObservable.add(function (effect) {
  59237. _this._updateMeshScreenCoordinates(scene);
  59238. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59239. effect.setFloat("exposure", _this.exposure);
  59240. effect.setFloat("decay", _this.decay);
  59241. effect.setFloat("weight", _this.weight);
  59242. effect.setFloat("density", _this.density);
  59243. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59244. });
  59245. return _this;
  59246. }
  59247. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59248. get: function () {
  59249. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59250. return false;
  59251. },
  59252. set: function (useDiffuseColor) {
  59253. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59254. },
  59255. enumerable: true,
  59256. configurable: true
  59257. });
  59258. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59259. return "VolumetricLightScatteringPostProcess";
  59260. };
  59261. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59262. var mesh = subMesh.getMesh();
  59263. // Render this.mesh as default
  59264. if (mesh === this.mesh && mesh.material) {
  59265. return mesh.material.isReady(mesh);
  59266. }
  59267. var defines = [];
  59268. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59269. var material = subMesh.getMaterial();
  59270. // Alpha test
  59271. if (material) {
  59272. if (material.needAlphaTesting()) {
  59273. defines.push("#define ALPHATEST");
  59274. }
  59275. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59276. attribs.push(BABYLON.VertexBuffer.UVKind);
  59277. defines.push("#define UV1");
  59278. }
  59279. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59280. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59281. defines.push("#define UV2");
  59282. }
  59283. }
  59284. // Bones
  59285. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59286. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59287. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59288. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59289. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59290. }
  59291. else {
  59292. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59293. }
  59294. // Instances
  59295. if (useInstances) {
  59296. defines.push("#define INSTANCES");
  59297. attribs.push("world0");
  59298. attribs.push("world1");
  59299. attribs.push("world2");
  59300. attribs.push("world3");
  59301. }
  59302. // Get correct effect
  59303. var join = defines.join("\n");
  59304. if (this._cachedDefines !== join) {
  59305. this._cachedDefines = join;
  59306. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59307. }
  59308. return this._volumetricLightScatteringPass.isReady();
  59309. };
  59310. /**
  59311. * Sets the new light position for light scattering effect
  59312. * @param {BABYLON.Vector3} The new custom light position
  59313. */
  59314. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59315. this.customMeshPosition = position;
  59316. };
  59317. /**
  59318. * Returns the light position for light scattering effect
  59319. * @return {BABYLON.Vector3} The custom light position
  59320. */
  59321. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59322. return this.customMeshPosition;
  59323. };
  59324. /**
  59325. * Disposes the internal assets and detaches the post-process from the camera
  59326. */
  59327. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59328. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59329. if (rttIndex !== -1) {
  59330. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59331. }
  59332. this._volumetricLightScatteringRTT.dispose();
  59333. _super.prototype.dispose.call(this, camera);
  59334. };
  59335. /**
  59336. * Returns the render target texture used by the post-process
  59337. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59338. */
  59339. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59340. return this._volumetricLightScatteringRTT;
  59341. };
  59342. // Private methods
  59343. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59344. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59345. return true;
  59346. }
  59347. return false;
  59348. };
  59349. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59350. var _this = this;
  59351. var engine = scene.getEngine();
  59352. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59353. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59354. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59355. this._volumetricLightScatteringRTT.renderList = null;
  59356. this._volumetricLightScatteringRTT.renderParticles = false;
  59357. var camera = this.getCamera();
  59358. if (camera) {
  59359. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59360. }
  59361. else {
  59362. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59363. }
  59364. // Custom render function for submeshes
  59365. var renderSubMesh = function (subMesh) {
  59366. var mesh = subMesh.getRenderingMesh();
  59367. if (_this._meshExcluded(mesh)) {
  59368. return;
  59369. }
  59370. var material = subMesh.getMaterial();
  59371. if (!material) {
  59372. return;
  59373. }
  59374. var scene = mesh.getScene();
  59375. var engine = scene.getEngine();
  59376. // Culling
  59377. engine.setState(material.backFaceCulling);
  59378. // Managing instances
  59379. var batch = mesh._getInstancesRenderList(subMesh._id);
  59380. if (batch.mustReturn) {
  59381. return;
  59382. }
  59383. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59384. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59385. var effect = _this._volumetricLightScatteringPass;
  59386. if (mesh === _this.mesh) {
  59387. if (subMesh.effect) {
  59388. effect = subMesh.effect;
  59389. }
  59390. else {
  59391. effect = material.getEffect();
  59392. }
  59393. }
  59394. engine.enableEffect(effect);
  59395. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59396. if (mesh === _this.mesh) {
  59397. material.bind(mesh.getWorldMatrix(), mesh);
  59398. }
  59399. else {
  59400. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59401. // Alpha test
  59402. if (material && material.needAlphaTesting()) {
  59403. var alphaTexture = material.getAlphaTestTexture();
  59404. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59405. if (alphaTexture) {
  59406. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59407. }
  59408. }
  59409. // Bones
  59410. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59411. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59412. }
  59413. }
  59414. // Draw
  59415. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59416. }
  59417. };
  59418. // Render target texture callbacks
  59419. var savedSceneClearColor;
  59420. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59421. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59422. savedSceneClearColor = scene.clearColor;
  59423. scene.clearColor = sceneClearColor;
  59424. });
  59425. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59426. scene.clearColor = savedSceneClearColor;
  59427. });
  59428. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59429. var engine = scene.getEngine();
  59430. var index;
  59431. if (depthOnlySubMeshes.length) {
  59432. engine.setColorWrite(false);
  59433. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59434. renderSubMesh(depthOnlySubMeshes.data[index]);
  59435. }
  59436. engine.setColorWrite(true);
  59437. }
  59438. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59439. renderSubMesh(opaqueSubMeshes.data[index]);
  59440. }
  59441. engine.setAlphaTesting(true);
  59442. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59443. renderSubMesh(alphaTestSubMeshes.data[index]);
  59444. }
  59445. engine.setAlphaTesting(false);
  59446. if (transparentSubMeshes.length) {
  59447. // Sort sub meshes
  59448. for (index = 0; index < transparentSubMeshes.length; index++) {
  59449. var submesh = transparentSubMeshes.data[index];
  59450. var boundingInfo = submesh.getBoundingInfo();
  59451. if (boundingInfo && scene.activeCamera) {
  59452. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59453. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59454. }
  59455. }
  59456. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59457. sortedArray.sort(function (a, b) {
  59458. // Alpha index first
  59459. if (a._alphaIndex > b._alphaIndex) {
  59460. return 1;
  59461. }
  59462. if (a._alphaIndex < b._alphaIndex) {
  59463. return -1;
  59464. }
  59465. // Then distance to camera
  59466. if (a._distanceToCamera < b._distanceToCamera) {
  59467. return 1;
  59468. }
  59469. if (a._distanceToCamera > b._distanceToCamera) {
  59470. return -1;
  59471. }
  59472. return 0;
  59473. });
  59474. // Render sub meshes
  59475. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59476. for (index = 0; index < sortedArray.length; index++) {
  59477. renderSubMesh(sortedArray[index]);
  59478. }
  59479. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59480. }
  59481. };
  59482. };
  59483. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59484. var transform = scene.getTransformMatrix();
  59485. var meshPosition;
  59486. if (this.useCustomMeshPosition) {
  59487. meshPosition = this.customMeshPosition;
  59488. }
  59489. else if (this.attachedNode) {
  59490. meshPosition = this.attachedNode.position;
  59491. }
  59492. else {
  59493. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59494. }
  59495. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59496. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59497. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59498. if (this.invert)
  59499. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59500. };
  59501. // Static methods
  59502. /**
  59503. * Creates a default mesh for the Volumeric Light Scattering post-process
  59504. * @param {string} The mesh name
  59505. * @param {BABYLON.Scene} The scene where to create the mesh
  59506. * @return {BABYLON.Mesh} the default mesh
  59507. */
  59508. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59509. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59510. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59511. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59512. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59513. mesh.material = material;
  59514. return mesh;
  59515. };
  59516. __decorate([
  59517. BABYLON.serializeAsVector3()
  59518. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59519. __decorate([
  59520. BABYLON.serialize()
  59521. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59522. __decorate([
  59523. BABYLON.serialize()
  59524. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59525. __decorate([
  59526. BABYLON.serializeAsMeshReference()
  59527. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59528. __decorate([
  59529. BABYLON.serialize()
  59530. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59531. __decorate([
  59532. BABYLON.serialize()
  59533. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59534. __decorate([
  59535. BABYLON.serialize()
  59536. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59537. __decorate([
  59538. BABYLON.serialize()
  59539. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59540. __decorate([
  59541. BABYLON.serialize()
  59542. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59543. return VolumetricLightScatteringPostProcess;
  59544. }(BABYLON.PostProcess));
  59545. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59546. })(BABYLON || (BABYLON = {}));
  59547. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59548. //
  59549. // This post-process allows the modification of rendered colors by using
  59550. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59551. //
  59552. // The object needs to be provided an url to a texture containing the color
  59553. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59554. // Use an image editing software to tweak the LUT to match your needs.
  59555. //
  59556. // For an example of a color LUT, see here:
  59557. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59558. // For explanations on color grading, see here:
  59559. // http://udn.epicgames.com/Three/ColorGrading.html
  59560. //
  59561. var BABYLON;
  59562. (function (BABYLON) {
  59563. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59564. __extends(ColorCorrectionPostProcess, _super);
  59565. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59566. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59567. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59568. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59569. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59570. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59571. _this.onApply = function (effect) {
  59572. effect.setTexture("colorTable", _this._colorTableTexture);
  59573. };
  59574. return _this;
  59575. }
  59576. return ColorCorrectionPostProcess;
  59577. }(BABYLON.PostProcess));
  59578. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59579. })(BABYLON || (BABYLON = {}));
  59580. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59581. var BABYLON;
  59582. (function (BABYLON) {
  59583. var TonemappingOperator;
  59584. (function (TonemappingOperator) {
  59585. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59586. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59587. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59588. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59589. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59590. ;
  59591. var TonemapPostProcess = /** @class */ (function (_super) {
  59592. __extends(TonemapPostProcess, _super);
  59593. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59595. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59596. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59597. _this._operator = _operator;
  59598. _this.exposureAdjustment = exposureAdjustment;
  59599. var defines = "#define ";
  59600. if (_this._operator === TonemappingOperator.Hable)
  59601. defines += "HABLE_TONEMAPPING";
  59602. else if (_this._operator === TonemappingOperator.Reinhard)
  59603. defines += "REINHARD_TONEMAPPING";
  59604. else if (_this._operator === TonemappingOperator.HejiDawson)
  59605. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59606. else if (_this._operator === TonemappingOperator.Photographic)
  59607. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59608. //sadly a second call to create the effect.
  59609. _this.updateEffect(defines);
  59610. _this.onApply = function (effect) {
  59611. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59612. };
  59613. return _this;
  59614. }
  59615. return TonemapPostProcess;
  59616. }(BABYLON.PostProcess));
  59617. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59618. })(BABYLON || (BABYLON = {}));
  59619. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59620. var BABYLON;
  59621. (function (BABYLON) {
  59622. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59623. __extends(DisplayPassPostProcess, _super);
  59624. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59625. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59626. }
  59627. return DisplayPassPostProcess;
  59628. }(BABYLON.PostProcess));
  59629. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59630. })(BABYLON || (BABYLON = {}));
  59631. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59632. var BABYLON;
  59633. (function (BABYLON) {
  59634. var HighlightsPostProcess = /** @class */ (function (_super) {
  59635. __extends(HighlightsPostProcess, _super);
  59636. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59637. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59638. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59639. }
  59640. return HighlightsPostProcess;
  59641. }(BABYLON.PostProcess));
  59642. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59643. })(BABYLON || (BABYLON = {}));
  59644. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59645. var BABYLON;
  59646. (function (BABYLON) {
  59647. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59648. __extends(ImageProcessingPostProcess, _super);
  59649. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59650. if (camera === void 0) { camera = null; }
  59651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59652. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59653. _this._fromLinearSpace = true;
  59654. /**
  59655. * Defines cache preventing GC.
  59656. */
  59657. _this._defines = {
  59658. IMAGEPROCESSING: false,
  59659. VIGNETTE: false,
  59660. VIGNETTEBLENDMODEMULTIPLY: false,
  59661. VIGNETTEBLENDMODEOPAQUE: false,
  59662. TONEMAPPING: false,
  59663. CONTRAST: false,
  59664. COLORCURVES: false,
  59665. COLORGRADING: false,
  59666. COLORGRADING3D: false,
  59667. FROMLINEARSPACE: false,
  59668. SAMPLER3DGREENDEPTH: false,
  59669. SAMPLER3DBGRMAP: false,
  59670. IMAGEPROCESSINGPOSTPROCESS: false,
  59671. EXPOSURE: false,
  59672. };
  59673. // Setup the default processing configuration to the scene.
  59674. _this._attachImageProcessingConfiguration(null, true);
  59675. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59676. _this.onApply = function (effect) {
  59677. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59678. };
  59679. return _this;
  59680. }
  59681. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59682. /**
  59683. * Gets the image processing configuration used either in this material.
  59684. */
  59685. get: function () {
  59686. return this._imageProcessingConfiguration;
  59687. },
  59688. /**
  59689. * Sets the Default image processing configuration used either in the this material.
  59690. *
  59691. * If sets to null, the scene one is in use.
  59692. */
  59693. set: function (value) {
  59694. this._attachImageProcessingConfiguration(value);
  59695. },
  59696. enumerable: true,
  59697. configurable: true
  59698. });
  59699. /**
  59700. * Attaches a new image processing configuration to the PBR Material.
  59701. * @param configuration
  59702. */
  59703. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59704. var _this = this;
  59705. if (doNotBuild === void 0) { doNotBuild = false; }
  59706. if (configuration === this._imageProcessingConfiguration) {
  59707. return;
  59708. }
  59709. // Detaches observer.
  59710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59712. }
  59713. // Pick the scene configuration if needed.
  59714. if (!configuration) {
  59715. var scene = null;
  59716. var engine = this.getEngine();
  59717. var camera = this.getCamera();
  59718. if (camera) {
  59719. scene = camera.getScene();
  59720. }
  59721. else if (engine && engine.scenes) {
  59722. var scenes = engine.scenes;
  59723. scene = scenes[scenes.length - 1];
  59724. }
  59725. else {
  59726. scene = BABYLON.Engine.LastCreatedScene;
  59727. }
  59728. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59729. }
  59730. else {
  59731. this._imageProcessingConfiguration = configuration;
  59732. }
  59733. // Attaches observer.
  59734. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59735. _this._updateParameters();
  59736. });
  59737. // Ensure the effect will be rebuilt.
  59738. if (!doNotBuild) {
  59739. this._updateParameters();
  59740. }
  59741. };
  59742. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59743. /**
  59744. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59745. */
  59746. get: function () {
  59747. return this.imageProcessingConfiguration.colorCurves;
  59748. },
  59749. /**
  59750. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59751. */
  59752. set: function (value) {
  59753. this.imageProcessingConfiguration.colorCurves = value;
  59754. },
  59755. enumerable: true,
  59756. configurable: true
  59757. });
  59758. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59759. /**
  59760. * Gets wether the color curves effect is enabled.
  59761. */
  59762. get: function () {
  59763. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59764. },
  59765. /**
  59766. * Sets wether the color curves effect is enabled.
  59767. */
  59768. set: function (value) {
  59769. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59770. },
  59771. enumerable: true,
  59772. configurable: true
  59773. });
  59774. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59775. /**
  59776. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59777. */
  59778. get: function () {
  59779. return this.imageProcessingConfiguration.colorGradingTexture;
  59780. },
  59781. /**
  59782. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59783. */
  59784. set: function (value) {
  59785. this.imageProcessingConfiguration.colorGradingTexture = value;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59791. /**
  59792. * Gets wether the color grading effect is enabled.
  59793. */
  59794. get: function () {
  59795. return this.imageProcessingConfiguration.colorGradingEnabled;
  59796. },
  59797. /**
  59798. * Gets wether the color grading effect is enabled.
  59799. */
  59800. set: function (value) {
  59801. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59802. },
  59803. enumerable: true,
  59804. configurable: true
  59805. });
  59806. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59807. /**
  59808. * Gets exposure used in the effect.
  59809. */
  59810. get: function () {
  59811. return this.imageProcessingConfiguration.exposure;
  59812. },
  59813. /**
  59814. * Sets exposure used in the effect.
  59815. */
  59816. set: function (value) {
  59817. this.imageProcessingConfiguration.exposure = value;
  59818. },
  59819. enumerable: true,
  59820. configurable: true
  59821. });
  59822. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59823. /**
  59824. * Gets wether tonemapping is enabled or not.
  59825. */
  59826. get: function () {
  59827. return this._imageProcessingConfiguration.toneMappingEnabled;
  59828. },
  59829. /**
  59830. * Sets wether tonemapping is enabled or not
  59831. */
  59832. set: function (value) {
  59833. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59834. },
  59835. enumerable: true,
  59836. configurable: true
  59837. });
  59838. ;
  59839. ;
  59840. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59841. /**
  59842. * Gets contrast used in the effect.
  59843. */
  59844. get: function () {
  59845. return this.imageProcessingConfiguration.contrast;
  59846. },
  59847. /**
  59848. * Sets contrast used in the effect.
  59849. */
  59850. set: function (value) {
  59851. this.imageProcessingConfiguration.contrast = value;
  59852. },
  59853. enumerable: true,
  59854. configurable: true
  59855. });
  59856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59857. /**
  59858. * Gets Vignette stretch size.
  59859. */
  59860. get: function () {
  59861. return this.imageProcessingConfiguration.vignetteStretch;
  59862. },
  59863. /**
  59864. * Sets Vignette stretch size.
  59865. */
  59866. set: function (value) {
  59867. this.imageProcessingConfiguration.vignetteStretch = value;
  59868. },
  59869. enumerable: true,
  59870. configurable: true
  59871. });
  59872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59873. /**
  59874. * Gets Vignette centre X Offset.
  59875. */
  59876. get: function () {
  59877. return this.imageProcessingConfiguration.vignetteCentreX;
  59878. },
  59879. /**
  59880. * Sets Vignette centre X Offset.
  59881. */
  59882. set: function (value) {
  59883. this.imageProcessingConfiguration.vignetteCentreX = value;
  59884. },
  59885. enumerable: true,
  59886. configurable: true
  59887. });
  59888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59889. /**
  59890. * Gets Vignette centre Y Offset.
  59891. */
  59892. get: function () {
  59893. return this.imageProcessingConfiguration.vignetteCentreY;
  59894. },
  59895. /**
  59896. * Sets Vignette centre Y Offset.
  59897. */
  59898. set: function (value) {
  59899. this.imageProcessingConfiguration.vignetteCentreY = value;
  59900. },
  59901. enumerable: true,
  59902. configurable: true
  59903. });
  59904. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59905. /**
  59906. * Gets Vignette weight or intensity of the vignette effect.
  59907. */
  59908. get: function () {
  59909. return this.imageProcessingConfiguration.vignetteWeight;
  59910. },
  59911. /**
  59912. * Sets Vignette weight or intensity of the vignette effect.
  59913. */
  59914. set: function (value) {
  59915. this.imageProcessingConfiguration.vignetteWeight = value;
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59921. /**
  59922. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59923. * if vignetteEnabled is set to true.
  59924. */
  59925. get: function () {
  59926. return this.imageProcessingConfiguration.vignetteColor;
  59927. },
  59928. /**
  59929. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59930. * if vignetteEnabled is set to true.
  59931. */
  59932. set: function (value) {
  59933. this.imageProcessingConfiguration.vignetteColor = value;
  59934. },
  59935. enumerable: true,
  59936. configurable: true
  59937. });
  59938. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59939. /**
  59940. * Gets Camera field of view used by the Vignette effect.
  59941. */
  59942. get: function () {
  59943. return this.imageProcessingConfiguration.vignetteCameraFov;
  59944. },
  59945. /**
  59946. * Sets Camera field of view used by the Vignette effect.
  59947. */
  59948. set: function (value) {
  59949. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59950. },
  59951. enumerable: true,
  59952. configurable: true
  59953. });
  59954. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59955. /**
  59956. * Gets the vignette blend mode allowing different kind of effect.
  59957. */
  59958. get: function () {
  59959. return this.imageProcessingConfiguration.vignetteBlendMode;
  59960. },
  59961. /**
  59962. * Sets the vignette blend mode allowing different kind of effect.
  59963. */
  59964. set: function (value) {
  59965. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59966. },
  59967. enumerable: true,
  59968. configurable: true
  59969. });
  59970. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59971. /**
  59972. * Gets wether the vignette effect is enabled.
  59973. */
  59974. get: function () {
  59975. return this.imageProcessingConfiguration.vignetteEnabled;
  59976. },
  59977. /**
  59978. * Sets wether the vignette effect is enabled.
  59979. */
  59980. set: function (value) {
  59981. this.imageProcessingConfiguration.vignetteEnabled = value;
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59987. /**
  59988. * Gets wether the input of the processing is in Gamma or Linear Space.
  59989. */
  59990. get: function () {
  59991. return this._fromLinearSpace;
  59992. },
  59993. /**
  59994. * Sets wether the input of the processing is in Gamma or Linear Space.
  59995. */
  59996. set: function (value) {
  59997. if (this._fromLinearSpace === value) {
  59998. return;
  59999. }
  60000. this._fromLinearSpace = value;
  60001. this._updateParameters();
  60002. },
  60003. enumerable: true,
  60004. configurable: true
  60005. });
  60006. ImageProcessingPostProcess.prototype.getClassName = function () {
  60007. return "ImageProcessingPostProcess";
  60008. };
  60009. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60010. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60011. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60012. var defines = "";
  60013. for (var define in this._defines) {
  60014. if (this._defines[define]) {
  60015. defines += "#define " + define + ";\r\n";
  60016. }
  60017. }
  60018. var samplers = ["textureSampler"];
  60019. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60020. var uniforms = ["scale"];
  60021. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60022. this.updateEffect(defines, uniforms, samplers);
  60023. };
  60024. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60025. _super.prototype.dispose.call(this, camera);
  60026. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60027. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60028. }
  60029. this.imageProcessingConfiguration.applyByPostProcess = false;
  60030. };
  60031. __decorate([
  60032. BABYLON.serialize()
  60033. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60034. return ImageProcessingPostProcess;
  60035. }(BABYLON.PostProcess));
  60036. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60037. })(BABYLON || (BABYLON = {}));
  60038. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60039. var BABYLON;
  60040. (function (BABYLON) {
  60041. var BlurPostProcess = /** @class */ (function (_super) {
  60042. __extends(BlurPostProcess, _super);
  60043. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60045. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60046. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60047. _this.direction = direction;
  60048. _this._packedFloat = false;
  60049. _this.onApplyObservable.add(function (effect) {
  60050. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60051. });
  60052. _this.kernel = kernel;
  60053. return _this;
  60054. }
  60055. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60056. /**
  60057. * Gets the length in pixels of the blur sample region
  60058. */
  60059. get: function () {
  60060. return this._idealKernel;
  60061. },
  60062. /**
  60063. * Sets the length in pixels of the blur sample region
  60064. */
  60065. set: function (v) {
  60066. if (this._idealKernel === v) {
  60067. return;
  60068. }
  60069. v = Math.max(v, 1);
  60070. this._idealKernel = v;
  60071. this._kernel = this._nearestBestKernel(v);
  60072. this._updateParameters();
  60073. },
  60074. enumerable: true,
  60075. configurable: true
  60076. });
  60077. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60078. /**
  60079. * Gets wether or not the blur is unpacking/repacking floats
  60080. */
  60081. get: function () {
  60082. return this._packedFloat;
  60083. },
  60084. /**
  60085. * Sets wether or not the blur needs to unpack/repack floats
  60086. */
  60087. set: function (v) {
  60088. if (this._packedFloat === v) {
  60089. return;
  60090. }
  60091. this._packedFloat = v;
  60092. this._updateParameters();
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. BlurPostProcess.prototype._updateParameters = function () {
  60098. // Generate sampling offsets and weights
  60099. var N = this._kernel;
  60100. var centerIndex = (N - 1) / 2;
  60101. // Generate Gaussian sampling weights over kernel
  60102. var offsets = [];
  60103. var weights = [];
  60104. var totalWeight = 0;
  60105. for (var i = 0; i < N; i++) {
  60106. var u = i / (N - 1);
  60107. var w = this._gaussianWeight(u * 2.0 - 1);
  60108. offsets[i] = (i - centerIndex);
  60109. weights[i] = w;
  60110. totalWeight += w;
  60111. }
  60112. // Normalize weights
  60113. for (var i = 0; i < weights.length; i++) {
  60114. weights[i] /= totalWeight;
  60115. }
  60116. // Optimize: combine samples to take advantage of hardware linear sampling
  60117. // Walk from left to center, combining pairs (symmetrically)
  60118. var linearSamplingWeights = [];
  60119. var linearSamplingOffsets = [];
  60120. var linearSamplingMap = [];
  60121. for (var i = 0; i <= centerIndex; i += 2) {
  60122. var j = Math.min(i + 1, Math.floor(centerIndex));
  60123. var singleCenterSample = i === j;
  60124. if (singleCenterSample) {
  60125. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60126. }
  60127. else {
  60128. var sharedCell = j === centerIndex;
  60129. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60130. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60131. if (offsetLinear === 0) {
  60132. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60133. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60134. }
  60135. else {
  60136. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60137. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60138. }
  60139. }
  60140. }
  60141. for (var i = 0; i < linearSamplingMap.length; i++) {
  60142. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60143. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60144. }
  60145. // Replace with optimized
  60146. offsets = linearSamplingOffsets;
  60147. weights = linearSamplingWeights;
  60148. // Generate shaders
  60149. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60150. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60151. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60152. var defines = "";
  60153. for (var i = 0; i < varyingCount; i++) {
  60154. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60155. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60156. }
  60157. var depCount = 0;
  60158. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60159. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60160. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60161. depCount++;
  60162. }
  60163. if (this.packedFloat) {
  60164. defines += "#define PACKEDFLOAT 1";
  60165. }
  60166. this.updateEffect(defines, null, null, {
  60167. varyingCount: varyingCount,
  60168. depCount: depCount
  60169. });
  60170. };
  60171. /**
  60172. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60173. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60174. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60175. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60176. * The gaps between physical kernels are compensated for in the weighting of the samples
  60177. * @param idealKernel Ideal blur kernel.
  60178. * @return Nearest best kernel.
  60179. */
  60180. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60181. var v = Math.round(idealKernel);
  60182. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60183. var k = _a[_i];
  60184. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60185. return Math.max(k, 3);
  60186. }
  60187. }
  60188. return Math.max(v, 3);
  60189. };
  60190. /**
  60191. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60192. * @param x The point on the Gaussian distribution to sample.
  60193. * @return the value of the Gaussian function at x.
  60194. */
  60195. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60196. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60197. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60198. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60199. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60200. // truncated at around 1.3% of peak strength.
  60201. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60202. var sigma = (1 / 3);
  60203. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60204. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60205. var weight = (1.0 / denominator) * Math.exp(exponent);
  60206. return weight;
  60207. };
  60208. /**
  60209. * Generates a string that can be used as a floating point number in GLSL.
  60210. * @param x Value to print.
  60211. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60212. * @return GLSL float string.
  60213. */
  60214. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60215. if (decimalFigures === void 0) { decimalFigures = 8; }
  60216. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60217. };
  60218. return BlurPostProcess;
  60219. }(BABYLON.PostProcess));
  60220. BABYLON.BlurPostProcess = BlurPostProcess;
  60221. })(BABYLON || (BABYLON = {}));
  60222. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60223. var BABYLON;
  60224. (function (BABYLON) {
  60225. var Bone = /** @class */ (function (_super) {
  60226. __extends(Bone, _super);
  60227. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60228. if (parentBone === void 0) { parentBone = null; }
  60229. if (localMatrix === void 0) { localMatrix = null; }
  60230. if (restPose === void 0) { restPose = null; }
  60231. if (baseMatrix === void 0) { baseMatrix = null; }
  60232. if (index === void 0) { index = null; }
  60233. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60234. _this.name = name;
  60235. _this.children = new Array();
  60236. _this.animations = new Array();
  60237. // Set this value to map this bone to a different index in the transform matrices.
  60238. // Set this value to -1 to exclude the bone from the transform matrices.
  60239. _this._index = null;
  60240. _this._worldTransform = new BABYLON.Matrix();
  60241. _this._absoluteTransform = new BABYLON.Matrix();
  60242. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60243. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60244. _this._scaleVector = BABYLON.Vector3.One();
  60245. _this._negateScaleChildren = BABYLON.Vector3.One();
  60246. _this._scalingDeterminant = 1;
  60247. _this._skeleton = skeleton;
  60248. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60249. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60250. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60251. _this._index = index;
  60252. skeleton.bones.push(_this);
  60253. _this.setParent(parentBone, false);
  60254. _this._updateDifferenceMatrix();
  60255. return _this;
  60256. }
  60257. Object.defineProperty(Bone.prototype, "_matrix", {
  60258. get: function () {
  60259. return this._localMatrix;
  60260. },
  60261. set: function (val) {
  60262. if (this._localMatrix) {
  60263. this._localMatrix.copyFrom(val);
  60264. }
  60265. else {
  60266. this._localMatrix = val;
  60267. }
  60268. },
  60269. enumerable: true,
  60270. configurable: true
  60271. });
  60272. // Members
  60273. Bone.prototype.getSkeleton = function () {
  60274. return this._skeleton;
  60275. };
  60276. Bone.prototype.getParent = function () {
  60277. return this._parent;
  60278. };
  60279. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60280. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60281. if (this._parent === parent) {
  60282. return;
  60283. }
  60284. if (this._parent) {
  60285. var index = this._parent.children.indexOf(this);
  60286. if (index !== -1) {
  60287. this._parent.children.splice(index, 1);
  60288. }
  60289. }
  60290. this._parent = parent;
  60291. if (this._parent) {
  60292. this._parent.children.push(this);
  60293. }
  60294. if (updateDifferenceMatrix) {
  60295. this._updateDifferenceMatrix();
  60296. }
  60297. };
  60298. Bone.prototype.getLocalMatrix = function () {
  60299. return this._localMatrix;
  60300. };
  60301. Bone.prototype.getBaseMatrix = function () {
  60302. return this._baseMatrix;
  60303. };
  60304. Bone.prototype.getRestPose = function () {
  60305. return this._restPose;
  60306. };
  60307. Bone.prototype.returnToRest = function () {
  60308. this.updateMatrix(this._restPose.clone());
  60309. };
  60310. Bone.prototype.getWorldMatrix = function () {
  60311. return this._worldTransform;
  60312. };
  60313. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60314. return this._invertedAbsoluteTransform;
  60315. };
  60316. Bone.prototype.getAbsoluteTransform = function () {
  60317. return this._absoluteTransform;
  60318. };
  60319. Object.defineProperty(Bone.prototype, "position", {
  60320. // Properties (matches AbstractMesh properties)
  60321. get: function () {
  60322. return this.getPosition();
  60323. },
  60324. set: function (newPosition) {
  60325. this.setPosition(newPosition);
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. Object.defineProperty(Bone.prototype, "rotation", {
  60331. get: function () {
  60332. return this.getRotation();
  60333. },
  60334. set: function (newRotation) {
  60335. this.setRotation(newRotation);
  60336. },
  60337. enumerable: true,
  60338. configurable: true
  60339. });
  60340. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60341. get: function () {
  60342. return this.getRotationQuaternion();
  60343. },
  60344. set: function (newRotation) {
  60345. this.setRotationQuaternion(newRotation);
  60346. },
  60347. enumerable: true,
  60348. configurable: true
  60349. });
  60350. Object.defineProperty(Bone.prototype, "scaling", {
  60351. get: function () {
  60352. return this.getScale();
  60353. },
  60354. set: function (newScaling) {
  60355. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60356. },
  60357. enumerable: true,
  60358. configurable: true
  60359. });
  60360. // Methods
  60361. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60362. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60363. this._baseMatrix = matrix.clone();
  60364. this._localMatrix = matrix.clone();
  60365. this._skeleton._markAsDirty();
  60366. if (updateDifferenceMatrix) {
  60367. this._updateDifferenceMatrix();
  60368. }
  60369. };
  60370. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60371. if (!rootMatrix) {
  60372. rootMatrix = this._baseMatrix;
  60373. }
  60374. if (this._parent) {
  60375. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60376. }
  60377. else {
  60378. this._absoluteTransform.copyFrom(rootMatrix);
  60379. }
  60380. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60381. for (var index = 0; index < this.children.length; index++) {
  60382. this.children[index]._updateDifferenceMatrix();
  60383. }
  60384. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60385. };
  60386. Bone.prototype.markAsDirty = function () {
  60387. this._currentRenderId++;
  60388. this._skeleton._markAsDirty();
  60389. };
  60390. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60391. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60392. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60393. // all animation may be coming from a library skeleton, so may need to create animation
  60394. if (this.animations.length === 0) {
  60395. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60396. this.animations[0].setKeys([]);
  60397. }
  60398. // get animation info / verify there is such a range from the source bone
  60399. var sourceRange = source.animations[0].getRange(rangeName);
  60400. if (!sourceRange) {
  60401. return false;
  60402. }
  60403. var from = sourceRange.from;
  60404. var to = sourceRange.to;
  60405. var sourceKeys = source.animations[0].getKeys();
  60406. // rescaling prep
  60407. var sourceBoneLength = source.length;
  60408. var sourceParent = source.getParent();
  60409. var parent = this.getParent();
  60410. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60411. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60412. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60413. var destKeys = this.animations[0].getKeys();
  60414. // loop vars declaration
  60415. var orig;
  60416. var origTranslation;
  60417. var mat;
  60418. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60419. orig = sourceKeys[key];
  60420. if (orig.frame >= from && orig.frame <= to) {
  60421. if (rescaleAsRequired) {
  60422. mat = orig.value.clone();
  60423. // scale based on parent ratio, when bone has parent
  60424. if (parentScalingReqd) {
  60425. origTranslation = mat.getTranslation();
  60426. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60427. // scale based on skeleton dimension ratio when root bone, and value is passed
  60428. }
  60429. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60430. origTranslation = mat.getTranslation();
  60431. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60432. // use original when root bone, and no data for skelDimensionsRatio
  60433. }
  60434. else {
  60435. mat = orig.value;
  60436. }
  60437. }
  60438. else {
  60439. mat = orig.value;
  60440. }
  60441. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60442. }
  60443. }
  60444. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60445. return true;
  60446. };
  60447. /**
  60448. * Translate the bone in local or world space.
  60449. * @param vec The amount to translate the bone.
  60450. * @param space The space that the translation is in.
  60451. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60452. */
  60453. Bone.prototype.translate = function (vec, space, mesh) {
  60454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60455. var lm = this.getLocalMatrix();
  60456. if (space == BABYLON.Space.LOCAL) {
  60457. lm.m[12] += vec.x;
  60458. lm.m[13] += vec.y;
  60459. lm.m[14] += vec.z;
  60460. }
  60461. else {
  60462. var wm = null;
  60463. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60464. if (mesh) {
  60465. wm = mesh.getWorldMatrix();
  60466. }
  60467. this._skeleton.computeAbsoluteTransforms();
  60468. var tmat = Bone._tmpMats[0];
  60469. var tvec = Bone._tmpVecs[0];
  60470. if (this._parent) {
  60471. if (mesh && wm) {
  60472. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60473. tmat.multiplyToRef(wm, tmat);
  60474. }
  60475. else {
  60476. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60477. }
  60478. }
  60479. tmat.m[12] = 0;
  60480. tmat.m[13] = 0;
  60481. tmat.m[14] = 0;
  60482. tmat.invert();
  60483. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60484. lm.m[12] += tvec.x;
  60485. lm.m[13] += tvec.y;
  60486. lm.m[14] += tvec.z;
  60487. }
  60488. this.markAsDirty();
  60489. };
  60490. /**
  60491. * Set the postion of the bone in local or world space.
  60492. * @param position The position to set the bone.
  60493. * @param space The space that the position is in.
  60494. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60495. */
  60496. Bone.prototype.setPosition = function (position, space, mesh) {
  60497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60498. var lm = this.getLocalMatrix();
  60499. if (space == BABYLON.Space.LOCAL) {
  60500. lm.m[12] = position.x;
  60501. lm.m[13] = position.y;
  60502. lm.m[14] = position.z;
  60503. }
  60504. else {
  60505. var wm = null;
  60506. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60507. if (mesh) {
  60508. wm = mesh.getWorldMatrix();
  60509. }
  60510. this._skeleton.computeAbsoluteTransforms();
  60511. var tmat = Bone._tmpMats[0];
  60512. var vec = Bone._tmpVecs[0];
  60513. if (this._parent) {
  60514. if (mesh && wm) {
  60515. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60516. tmat.multiplyToRef(wm, tmat);
  60517. }
  60518. else {
  60519. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60520. }
  60521. }
  60522. tmat.invert();
  60523. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60524. lm.m[12] = vec.x;
  60525. lm.m[13] = vec.y;
  60526. lm.m[14] = vec.z;
  60527. }
  60528. this.markAsDirty();
  60529. };
  60530. /**
  60531. * Set the absolute postion of the bone (world space).
  60532. * @param position The position to set the bone.
  60533. * @param mesh The mesh that this bone is attached to.
  60534. */
  60535. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60536. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60537. };
  60538. /**
  60539. * Set the scale of the bone on the x, y and z axes.
  60540. * @param x The scale of the bone on the x axis.
  60541. * @param x The scale of the bone on the y axis.
  60542. * @param z The scale of the bone on the z axis.
  60543. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60544. */
  60545. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60546. if (scaleChildren === void 0) { scaleChildren = false; }
  60547. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60548. if (!scaleChildren) {
  60549. this._negateScaleChildren.x = 1 / x;
  60550. this._negateScaleChildren.y = 1 / y;
  60551. this._negateScaleChildren.z = 1 / z;
  60552. }
  60553. this._syncScaleVector();
  60554. }
  60555. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60556. };
  60557. /**
  60558. * Scale the bone on the x, y and z axes.
  60559. * @param x The amount to scale the bone on the x axis.
  60560. * @param x The amount to scale the bone on the y axis.
  60561. * @param z The amount to scale the bone on the z axis.
  60562. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60563. */
  60564. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60565. if (scaleChildren === void 0) { scaleChildren = false; }
  60566. var locMat = this.getLocalMatrix();
  60567. var origLocMat = Bone._tmpMats[0];
  60568. origLocMat.copyFrom(locMat);
  60569. var origLocMatInv = Bone._tmpMats[1];
  60570. origLocMatInv.copyFrom(origLocMat);
  60571. origLocMatInv.invert();
  60572. var scaleMat = Bone._tmpMats[2];
  60573. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60574. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60575. this._scaleVector.x *= x;
  60576. this._scaleVector.y *= y;
  60577. this._scaleVector.z *= z;
  60578. locMat.multiplyToRef(origLocMatInv, locMat);
  60579. locMat.multiplyToRef(scaleMat, locMat);
  60580. locMat.multiplyToRef(origLocMat, locMat);
  60581. var parent = this.getParent();
  60582. if (parent) {
  60583. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60584. }
  60585. else {
  60586. this.getAbsoluteTransform().copyFrom(locMat);
  60587. }
  60588. var len = this.children.length;
  60589. scaleMat.invert();
  60590. for (var i = 0; i < len; i++) {
  60591. var child = this.children[i];
  60592. var cm = child.getLocalMatrix();
  60593. cm.multiplyToRef(scaleMat, cm);
  60594. var lm = child.getLocalMatrix();
  60595. lm.m[12] *= x;
  60596. lm.m[13] *= y;
  60597. lm.m[14] *= z;
  60598. }
  60599. this.computeAbsoluteTransforms();
  60600. if (scaleChildren) {
  60601. for (var i = 0; i < len; i++) {
  60602. this.children[i].scale(x, y, z, scaleChildren);
  60603. }
  60604. }
  60605. this.markAsDirty();
  60606. };
  60607. /**
  60608. * Set the yaw, pitch, and roll of the bone in local or world space.
  60609. * @param yaw The rotation of the bone on the y axis.
  60610. * @param pitch The rotation of the bone on the x axis.
  60611. * @param roll The rotation of the bone on the z axis.
  60612. * @param space The space that the axes of rotation are in.
  60613. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60614. */
  60615. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60617. var rotMat = Bone._tmpMats[0];
  60618. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60619. var rotMatInv = Bone._tmpMats[1];
  60620. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60621. rotMatInv.multiplyToRef(rotMat, rotMat);
  60622. this._rotateWithMatrix(rotMat, space, mesh);
  60623. };
  60624. /**
  60625. * Rotate the bone on an axis in local or world space.
  60626. * @param axis The axis to rotate the bone on.
  60627. * @param amount The amount to rotate the bone.
  60628. * @param space The space that the axis is in.
  60629. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60630. */
  60631. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60633. var rmat = Bone._tmpMats[0];
  60634. rmat.m[12] = 0;
  60635. rmat.m[13] = 0;
  60636. rmat.m[14] = 0;
  60637. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60638. this._rotateWithMatrix(rmat, space, mesh);
  60639. };
  60640. /**
  60641. * Set the rotation of the bone to a particular axis angle in local or world space.
  60642. * @param axis The axis to rotate the bone on.
  60643. * @param angle The angle that the bone should be rotated to.
  60644. * @param space The space that the axis is in.
  60645. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60646. */
  60647. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60649. var rotMat = Bone._tmpMats[0];
  60650. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60651. var rotMatInv = Bone._tmpMats[1];
  60652. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60653. rotMatInv.multiplyToRef(rotMat, rotMat);
  60654. this._rotateWithMatrix(rotMat, space, mesh);
  60655. };
  60656. /**
  60657. * Set the euler rotation of the bone in local of world space.
  60658. * @param rotation The euler rotation that the bone should be set to.
  60659. * @param space The space that the rotation is in.
  60660. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60661. */
  60662. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60664. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60665. };
  60666. /**
  60667. * Set the quaternion rotation of the bone in local of world space.
  60668. * @param quat The quaternion rotation that the bone should be set to.
  60669. * @param space The space that the rotation is in.
  60670. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60671. */
  60672. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60673. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60674. var rotMatInv = Bone._tmpMats[0];
  60675. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60676. var rotMat = Bone._tmpMats[1];
  60677. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60678. rotMatInv.multiplyToRef(rotMat, rotMat);
  60679. this._rotateWithMatrix(rotMat, space, mesh);
  60680. };
  60681. /**
  60682. * Set the rotation matrix of the bone in local of world space.
  60683. * @param rotMat The rotation matrix that the bone should be set to.
  60684. * @param space The space that the rotation is in.
  60685. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60686. */
  60687. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60689. var rotMatInv = Bone._tmpMats[0];
  60690. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60691. var rotMat2 = Bone._tmpMats[1];
  60692. rotMat2.copyFrom(rotMat);
  60693. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60694. this._rotateWithMatrix(rotMat2, space, mesh);
  60695. };
  60696. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60698. var lmat = this.getLocalMatrix();
  60699. var lx = lmat.m[12];
  60700. var ly = lmat.m[13];
  60701. var lz = lmat.m[14];
  60702. var parent = this.getParent();
  60703. var parentScale = Bone._tmpMats[3];
  60704. var parentScaleInv = Bone._tmpMats[4];
  60705. if (parent) {
  60706. if (space == BABYLON.Space.WORLD) {
  60707. if (mesh) {
  60708. parentScale.copyFrom(mesh.getWorldMatrix());
  60709. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60710. }
  60711. else {
  60712. parentScale.copyFrom(parent.getAbsoluteTransform());
  60713. }
  60714. }
  60715. else {
  60716. parentScale = parent._scaleMatrix;
  60717. }
  60718. parentScaleInv.copyFrom(parentScale);
  60719. parentScaleInv.invert();
  60720. lmat.multiplyToRef(parentScale, lmat);
  60721. lmat.multiplyToRef(rmat, lmat);
  60722. lmat.multiplyToRef(parentScaleInv, lmat);
  60723. }
  60724. else {
  60725. if (space == BABYLON.Space.WORLD && mesh) {
  60726. parentScale.copyFrom(mesh.getWorldMatrix());
  60727. parentScaleInv.copyFrom(parentScale);
  60728. parentScaleInv.invert();
  60729. lmat.multiplyToRef(parentScale, lmat);
  60730. lmat.multiplyToRef(rmat, lmat);
  60731. lmat.multiplyToRef(parentScaleInv, lmat);
  60732. }
  60733. else {
  60734. lmat.multiplyToRef(rmat, lmat);
  60735. }
  60736. }
  60737. lmat.m[12] = lx;
  60738. lmat.m[13] = ly;
  60739. lmat.m[14] = lz;
  60740. this.computeAbsoluteTransforms();
  60741. this.markAsDirty();
  60742. };
  60743. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60745. if (space == BABYLON.Space.WORLD) {
  60746. var scaleMatrix = Bone._tmpMats[2];
  60747. scaleMatrix.copyFrom(this._scaleMatrix);
  60748. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60749. if (mesh) {
  60750. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60751. var meshScale = Bone._tmpMats[3];
  60752. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60753. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60754. }
  60755. rotMatInv.invert();
  60756. scaleMatrix.m[0] *= this._scalingDeterminant;
  60757. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60758. }
  60759. else {
  60760. rotMatInv.copyFrom(this.getLocalMatrix());
  60761. rotMatInv.invert();
  60762. var scaleMatrix = Bone._tmpMats[2];
  60763. scaleMatrix.copyFrom(this._scaleMatrix);
  60764. if (this._parent) {
  60765. var pscaleMatrix = Bone._tmpMats[3];
  60766. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60767. pscaleMatrix.invert();
  60768. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60769. }
  60770. else {
  60771. scaleMatrix.m[0] *= this._scalingDeterminant;
  60772. }
  60773. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60774. }
  60775. };
  60776. /**
  60777. * Get the scale of the bone
  60778. * @returns the scale of the bone
  60779. */
  60780. Bone.prototype.getScale = function () {
  60781. return this._scaleVector.clone();
  60782. };
  60783. /**
  60784. * Copy the scale of the bone to a vector3.
  60785. * @param result The vector3 to copy the scale to
  60786. */
  60787. Bone.prototype.getScaleToRef = function (result) {
  60788. result.copyFrom(this._scaleVector);
  60789. };
  60790. /**
  60791. * Get the position of the bone in local or world space.
  60792. * @param space The space that the returned position is in.
  60793. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60794. * @returns The position of the bone
  60795. */
  60796. Bone.prototype.getPosition = function (space, mesh) {
  60797. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60798. if (mesh === void 0) { mesh = null; }
  60799. var pos = BABYLON.Vector3.Zero();
  60800. this.getPositionToRef(space, mesh, pos);
  60801. return pos;
  60802. };
  60803. /**
  60804. * Copy the position of the bone to a vector3 in local or world space.
  60805. * @param space The space that the returned position is in.
  60806. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60807. * @param result The vector3 to copy the position to.
  60808. */
  60809. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60811. if (space == BABYLON.Space.LOCAL) {
  60812. var lm = this.getLocalMatrix();
  60813. result.x = lm.m[12];
  60814. result.y = lm.m[13];
  60815. result.z = lm.m[14];
  60816. }
  60817. else {
  60818. var wm = null;
  60819. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60820. if (mesh) {
  60821. wm = mesh.getWorldMatrix();
  60822. }
  60823. this._skeleton.computeAbsoluteTransforms();
  60824. var tmat = Bone._tmpMats[0];
  60825. if (mesh && wm) {
  60826. tmat.copyFrom(this.getAbsoluteTransform());
  60827. tmat.multiplyToRef(wm, tmat);
  60828. }
  60829. else {
  60830. tmat = this.getAbsoluteTransform();
  60831. }
  60832. result.x = tmat.m[12];
  60833. result.y = tmat.m[13];
  60834. result.z = tmat.m[14];
  60835. }
  60836. };
  60837. /**
  60838. * Get the absolute position of the bone (world space).
  60839. * @param mesh The mesh that this bone is attached to.
  60840. * @returns The absolute position of the bone
  60841. */
  60842. Bone.prototype.getAbsolutePosition = function (mesh) {
  60843. if (mesh === void 0) { mesh = null; }
  60844. var pos = BABYLON.Vector3.Zero();
  60845. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60846. return pos;
  60847. };
  60848. /**
  60849. * Copy the absolute position of the bone (world space) to the result param.
  60850. * @param mesh The mesh that this bone is attached to.
  60851. * @param result The vector3 to copy the absolute position to.
  60852. */
  60853. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60854. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60855. };
  60856. /**
  60857. * Compute the absolute transforms of this bone and its children.
  60858. */
  60859. Bone.prototype.computeAbsoluteTransforms = function () {
  60860. if (this._parent) {
  60861. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60862. }
  60863. else {
  60864. this._absoluteTransform.copyFrom(this._localMatrix);
  60865. var poseMatrix = this._skeleton.getPoseMatrix();
  60866. if (poseMatrix) {
  60867. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60868. }
  60869. }
  60870. var children = this.children;
  60871. var len = children.length;
  60872. for (var i = 0; i < len; i++) {
  60873. children[i].computeAbsoluteTransforms();
  60874. }
  60875. };
  60876. Bone.prototype._syncScaleVector = function () {
  60877. var lm = this.getLocalMatrix();
  60878. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60879. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60880. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60881. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60882. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60883. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60884. this._scaleVector.x = xs * Math.sqrt(xsq);
  60885. this._scaleVector.y = ys * Math.sqrt(ysq);
  60886. this._scaleVector.z = zs * Math.sqrt(zsq);
  60887. if (this._parent) {
  60888. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60889. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60890. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60891. }
  60892. 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);
  60893. };
  60894. /**
  60895. * Get the world direction from an axis that is in the local space of the bone.
  60896. * @param localAxis The local direction that is used to compute the world direction.
  60897. * @param mesh The mesh that this bone is attached to.
  60898. * @returns The world direction
  60899. */
  60900. Bone.prototype.getDirection = function (localAxis, mesh) {
  60901. if (mesh === void 0) { mesh = null; }
  60902. var result = BABYLON.Vector3.Zero();
  60903. this.getDirectionToRef(localAxis, mesh, result);
  60904. return result;
  60905. };
  60906. /**
  60907. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60908. * @param localAxis The local direction that is used to compute the world direction.
  60909. * @param mesh The mesh that this bone is attached to.
  60910. * @param result The vector3 that the world direction will be copied to.
  60911. */
  60912. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60913. if (mesh === void 0) { mesh = null; }
  60914. var wm = null;
  60915. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60916. if (mesh) {
  60917. wm = mesh.getWorldMatrix();
  60918. }
  60919. this._skeleton.computeAbsoluteTransforms();
  60920. var mat = Bone._tmpMats[0];
  60921. mat.copyFrom(this.getAbsoluteTransform());
  60922. if (mesh && wm) {
  60923. mat.multiplyToRef(wm, mat);
  60924. }
  60925. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60926. result.normalize();
  60927. };
  60928. /**
  60929. * Get the euler rotation of the bone in local or world space.
  60930. * @param space The space that the rotation should be in.
  60931. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60932. * @returns The euler rotation
  60933. */
  60934. Bone.prototype.getRotation = function (space, mesh) {
  60935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60936. if (mesh === void 0) { mesh = null; }
  60937. var result = BABYLON.Vector3.Zero();
  60938. this.getRotationToRef(space, mesh, result);
  60939. return result;
  60940. };
  60941. /**
  60942. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60943. * @param space The space that the rotation should be in.
  60944. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60945. * @param result The vector3 that the rotation should be copied to.
  60946. */
  60947. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60949. if (mesh === void 0) { mesh = null; }
  60950. var quat = Bone._tmpQuat;
  60951. this.getRotationQuaternionToRef(space, mesh, quat);
  60952. quat.toEulerAnglesToRef(result);
  60953. };
  60954. /**
  60955. * Get the quaternion rotation of the bone in either local or world space.
  60956. * @param space The space that the rotation should be in.
  60957. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60958. * @returns The quaternion rotation
  60959. */
  60960. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60962. if (mesh === void 0) { mesh = null; }
  60963. var result = BABYLON.Quaternion.Identity();
  60964. this.getRotationQuaternionToRef(space, mesh, result);
  60965. return result;
  60966. };
  60967. /**
  60968. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60969. * @param space The space that the rotation should be in.
  60970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60971. * @param result The quaternion that the rotation should be copied to.
  60972. */
  60973. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60975. if (mesh === void 0) { mesh = null; }
  60976. if (space == BABYLON.Space.LOCAL) {
  60977. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60978. }
  60979. else {
  60980. var mat = Bone._tmpMats[0];
  60981. var amat = this.getAbsoluteTransform();
  60982. if (mesh) {
  60983. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60984. }
  60985. else {
  60986. mat.copyFrom(amat);
  60987. }
  60988. mat.m[0] *= this._scalingDeterminant;
  60989. mat.m[1] *= this._scalingDeterminant;
  60990. mat.m[2] *= this._scalingDeterminant;
  60991. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60992. }
  60993. };
  60994. /**
  60995. * Get the rotation matrix of the bone in local or world space.
  60996. * @param space The space that the rotation should be in.
  60997. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60998. * @returns The rotation matrix
  60999. */
  61000. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61002. var result = BABYLON.Matrix.Identity();
  61003. this.getRotationMatrixToRef(space, mesh, result);
  61004. return result;
  61005. };
  61006. /**
  61007. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61008. * @param space The space that the rotation should be in.
  61009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61010. * @param result The quaternion that the rotation should be copied to.
  61011. */
  61012. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61013. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61014. if (space == BABYLON.Space.LOCAL) {
  61015. this.getLocalMatrix().getRotationMatrixToRef(result);
  61016. }
  61017. else {
  61018. var mat = Bone._tmpMats[0];
  61019. var amat = this.getAbsoluteTransform();
  61020. if (mesh) {
  61021. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61022. }
  61023. else {
  61024. mat.copyFrom(amat);
  61025. }
  61026. mat.m[0] *= this._scalingDeterminant;
  61027. mat.m[1] *= this._scalingDeterminant;
  61028. mat.m[2] *= this._scalingDeterminant;
  61029. mat.getRotationMatrixToRef(result);
  61030. }
  61031. };
  61032. /**
  61033. * Get the world position of a point that is in the local space of the bone.
  61034. * @param position The local position
  61035. * @param mesh The mesh that this bone is attached to.
  61036. * @returns The world position
  61037. */
  61038. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61039. if (mesh === void 0) { mesh = null; }
  61040. var result = BABYLON.Vector3.Zero();
  61041. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61042. return result;
  61043. };
  61044. /**
  61045. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61046. * @param position The local position
  61047. * @param mesh The mesh that this bone is attached to.
  61048. * @param result The vector3 that the world position should be copied to.
  61049. */
  61050. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61051. if (mesh === void 0) { mesh = null; }
  61052. var wm = null;
  61053. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61054. if (mesh) {
  61055. wm = mesh.getWorldMatrix();
  61056. }
  61057. this._skeleton.computeAbsoluteTransforms();
  61058. var tmat = Bone._tmpMats[0];
  61059. if (mesh && wm) {
  61060. tmat.copyFrom(this.getAbsoluteTransform());
  61061. tmat.multiplyToRef(wm, tmat);
  61062. }
  61063. else {
  61064. tmat = this.getAbsoluteTransform();
  61065. }
  61066. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61067. };
  61068. /**
  61069. * Get the local position of a point that is in world space.
  61070. * @param position The world position
  61071. * @param mesh The mesh that this bone is attached to.
  61072. * @returns The local position
  61073. */
  61074. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61075. if (mesh === void 0) { mesh = null; }
  61076. var result = BABYLON.Vector3.Zero();
  61077. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61078. return result;
  61079. };
  61080. /**
  61081. * Get the local position of a point that is in world space and copy it to the result param.
  61082. * @param position The world position
  61083. * @param mesh The mesh that this bone is attached to.
  61084. * @param result The vector3 that the local position should be copied to.
  61085. */
  61086. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61087. if (mesh === void 0) { mesh = null; }
  61088. var wm = null;
  61089. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61090. if (mesh) {
  61091. wm = mesh.getWorldMatrix();
  61092. }
  61093. this._skeleton.computeAbsoluteTransforms();
  61094. var tmat = Bone._tmpMats[0];
  61095. tmat.copyFrom(this.getAbsoluteTransform());
  61096. if (mesh && wm) {
  61097. tmat.multiplyToRef(wm, tmat);
  61098. }
  61099. tmat.invert();
  61100. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61101. };
  61102. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61103. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61104. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61105. return Bone;
  61106. }(BABYLON.Node));
  61107. BABYLON.Bone = Bone;
  61108. })(BABYLON || (BABYLON = {}));
  61109. //# sourceMappingURL=babylon.bone.js.map
  61110. var BABYLON;
  61111. (function (BABYLON) {
  61112. var BoneIKController = /** @class */ (function () {
  61113. function BoneIKController(mesh, bone, options) {
  61114. this.targetPosition = BABYLON.Vector3.Zero();
  61115. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61116. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61117. this.poleAngle = 0;
  61118. this.slerpAmount = 1;
  61119. this._bone1Quat = BABYLON.Quaternion.Identity();
  61120. this._bone1Mat = BABYLON.Matrix.Identity();
  61121. this._bone2Ang = Math.PI;
  61122. this._maxAngle = Math.PI;
  61123. this._rightHandedSystem = false;
  61124. this._bendAxis = BABYLON.Vector3.Right();
  61125. this._slerping = false;
  61126. this._adjustRoll = 0;
  61127. this._bone2 = bone;
  61128. this._bone1 = bone.getParent();
  61129. if (!this._bone1) {
  61130. return;
  61131. }
  61132. this.mesh = mesh;
  61133. var bonePos = bone.getPosition();
  61134. if (bone.getAbsoluteTransform().determinant() > 0) {
  61135. this._rightHandedSystem = true;
  61136. this._bendAxis.x = 0;
  61137. this._bendAxis.y = 0;
  61138. this._bendAxis.z = -1;
  61139. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61140. this._adjustRoll = Math.PI * .5;
  61141. this._bendAxis.z = 1;
  61142. }
  61143. }
  61144. if (this._bone1.length) {
  61145. var boneScale1 = this._bone1.getScale();
  61146. var boneScale2 = this._bone2.getScale();
  61147. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61148. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61149. }
  61150. else if (this._bone1.children[0]) {
  61151. mesh.computeWorldMatrix(true);
  61152. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61153. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61154. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61155. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61156. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61157. }
  61158. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61159. this.maxAngle = Math.PI;
  61160. if (options) {
  61161. if (options.targetMesh) {
  61162. this.targetMesh = options.targetMesh;
  61163. this.targetMesh.computeWorldMatrix(true);
  61164. }
  61165. if (options.poleTargetMesh) {
  61166. this.poleTargetMesh = options.poleTargetMesh;
  61167. this.poleTargetMesh.computeWorldMatrix(true);
  61168. }
  61169. else if (options.poleTargetBone) {
  61170. this.poleTargetBone = options.poleTargetBone;
  61171. }
  61172. else if (this._bone1.getParent()) {
  61173. this.poleTargetBone = this._bone1.getParent();
  61174. }
  61175. if (options.poleTargetLocalOffset) {
  61176. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61177. }
  61178. if (options.poleAngle) {
  61179. this.poleAngle = options.poleAngle;
  61180. }
  61181. if (options.bendAxis) {
  61182. this._bendAxis.copyFrom(options.bendAxis);
  61183. }
  61184. if (options.maxAngle) {
  61185. this.maxAngle = options.maxAngle;
  61186. }
  61187. if (options.slerpAmount) {
  61188. this.slerpAmount = options.slerpAmount;
  61189. }
  61190. }
  61191. }
  61192. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61193. get: function () {
  61194. return this._maxAngle;
  61195. },
  61196. set: function (value) {
  61197. this._setMaxAngle(value);
  61198. },
  61199. enumerable: true,
  61200. configurable: true
  61201. });
  61202. BoneIKController.prototype._setMaxAngle = function (ang) {
  61203. if (ang < 0) {
  61204. ang = 0;
  61205. }
  61206. if (ang > Math.PI || ang == undefined) {
  61207. ang = Math.PI;
  61208. }
  61209. this._maxAngle = ang;
  61210. var a = this._bone1Length;
  61211. var b = this._bone2Length;
  61212. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61213. };
  61214. BoneIKController.prototype.update = function () {
  61215. var bone1 = this._bone1;
  61216. if (!bone1) {
  61217. return;
  61218. }
  61219. var target = this.targetPosition;
  61220. var poleTarget = this.poleTargetPosition;
  61221. var mat1 = BoneIKController._tmpMats[0];
  61222. var mat2 = BoneIKController._tmpMats[1];
  61223. if (this.targetMesh) {
  61224. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61225. }
  61226. if (this.poleTargetBone) {
  61227. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61228. }
  61229. else if (this.poleTargetMesh) {
  61230. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61231. }
  61232. var bonePos = BoneIKController._tmpVecs[0];
  61233. var zaxis = BoneIKController._tmpVecs[1];
  61234. var xaxis = BoneIKController._tmpVecs[2];
  61235. var yaxis = BoneIKController._tmpVecs[3];
  61236. var upAxis = BoneIKController._tmpVecs[4];
  61237. var _tmpQuat = BoneIKController._tmpQuat;
  61238. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61239. poleTarget.subtractToRef(bonePos, upAxis);
  61240. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61241. upAxis.y = 1;
  61242. }
  61243. else {
  61244. upAxis.normalize();
  61245. }
  61246. target.subtractToRef(bonePos, yaxis);
  61247. yaxis.normalize();
  61248. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61249. zaxis.normalize();
  61250. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61251. xaxis.normalize();
  61252. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61253. var a = this._bone1Length;
  61254. var b = this._bone2Length;
  61255. var c = BABYLON.Vector3.Distance(bonePos, target);
  61256. if (this._maxReach > 0) {
  61257. c = Math.min(this._maxReach, c);
  61258. }
  61259. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61260. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61261. if (acosa > 1) {
  61262. acosa = 1;
  61263. }
  61264. if (acosb > 1) {
  61265. acosb = 1;
  61266. }
  61267. if (acosa < -1) {
  61268. acosa = -1;
  61269. }
  61270. if (acosb < -1) {
  61271. acosb = -1;
  61272. }
  61273. var angA = Math.acos(acosa);
  61274. var angB = Math.acos(acosb);
  61275. var angC = -angA - angB;
  61276. if (this._rightHandedSystem) {
  61277. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61278. mat2.multiplyToRef(mat1, mat1);
  61279. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61280. mat2.multiplyToRef(mat1, mat1);
  61281. }
  61282. else {
  61283. var _tmpVec = BoneIKController._tmpVecs[5];
  61284. _tmpVec.copyFrom(this._bendAxis);
  61285. _tmpVec.x *= -1;
  61286. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61287. mat2.multiplyToRef(mat1, mat1);
  61288. }
  61289. if (this.poleAngle) {
  61290. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61291. mat1.multiplyToRef(mat2, mat1);
  61292. }
  61293. if (this._bone1) {
  61294. if (this.slerpAmount < 1) {
  61295. if (!this._slerping) {
  61296. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61297. }
  61298. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61299. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61300. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61301. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61302. this._slerping = true;
  61303. }
  61304. else {
  61305. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61306. this._bone1Mat.copyFrom(mat1);
  61307. this._slerping = false;
  61308. }
  61309. }
  61310. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61311. this._bone2Ang = angC;
  61312. };
  61313. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61314. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61315. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61316. return BoneIKController;
  61317. }());
  61318. BABYLON.BoneIKController = BoneIKController;
  61319. })(BABYLON || (BABYLON = {}));
  61320. //# sourceMappingURL=babylon.boneIKController.js.map
  61321. var BABYLON;
  61322. (function (BABYLON) {
  61323. var BoneLookController = /** @class */ (function () {
  61324. /**
  61325. * Create a BoneLookController
  61326. * @param mesh the mesh that the bone belongs to
  61327. * @param bone the bone that will be looking to the target
  61328. * @param target the target Vector3 to look at
  61329. * @param settings optional settings:
  61330. * - maxYaw: the maximum angle the bone will yaw to
  61331. * - minYaw: the minimum angle the bone will yaw to
  61332. * - maxPitch: the maximum angle the bone will pitch to
  61333. * - minPitch: the minimum angle the bone will yaw to
  61334. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61335. * - upAxis: the up axis of the coordinate system
  61336. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61337. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61338. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61339. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61340. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61341. * - adjustRoll: used to make an adjustment to the roll of the bone
  61342. **/
  61343. function BoneLookController(mesh, bone, target, options) {
  61344. /**
  61345. * The up axis of the coordinate system that is used when the bone is rotated.
  61346. */
  61347. this.upAxis = BABYLON.Vector3.Up();
  61348. /**
  61349. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61350. */
  61351. this.upAxisSpace = BABYLON.Space.LOCAL;
  61352. /**
  61353. * Used to make an adjustment to the yaw of the bone.
  61354. */
  61355. this.adjustYaw = 0;
  61356. /**
  61357. * Used to make an adjustment to the pitch of the bone.
  61358. */
  61359. this.adjustPitch = 0;
  61360. /**
  61361. * Used to make an adjustment to the roll of the bone.
  61362. */
  61363. this.adjustRoll = 0;
  61364. /**
  61365. * 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).
  61366. */
  61367. this.slerpAmount = 1;
  61368. this._boneQuat = BABYLON.Quaternion.Identity();
  61369. this._slerping = false;
  61370. this._firstFrameSkipped = false;
  61371. this._fowardAxis = BABYLON.Vector3.Forward();
  61372. this.mesh = mesh;
  61373. this.bone = bone;
  61374. this.target = target;
  61375. if (options) {
  61376. if (options.adjustYaw) {
  61377. this.adjustYaw = options.adjustYaw;
  61378. }
  61379. if (options.adjustPitch) {
  61380. this.adjustPitch = options.adjustPitch;
  61381. }
  61382. if (options.adjustRoll) {
  61383. this.adjustRoll = options.adjustRoll;
  61384. }
  61385. if (options.maxYaw != null) {
  61386. this.maxYaw = options.maxYaw;
  61387. }
  61388. else {
  61389. this.maxYaw = Math.PI;
  61390. }
  61391. if (options.minYaw != null) {
  61392. this.minYaw = options.minYaw;
  61393. }
  61394. else {
  61395. this.minYaw = -Math.PI;
  61396. }
  61397. if (options.maxPitch != null) {
  61398. this.maxPitch = options.maxPitch;
  61399. }
  61400. else {
  61401. this.maxPitch = Math.PI;
  61402. }
  61403. if (options.minPitch != null) {
  61404. this.minPitch = options.minPitch;
  61405. }
  61406. else {
  61407. this.minPitch = -Math.PI;
  61408. }
  61409. if (options.slerpAmount != null) {
  61410. this.slerpAmount = options.slerpAmount;
  61411. }
  61412. if (options.upAxis != null) {
  61413. this.upAxis = options.upAxis;
  61414. }
  61415. if (options.upAxisSpace != null) {
  61416. this.upAxisSpace = options.upAxisSpace;
  61417. }
  61418. if (options.yawAxis != null || options.pitchAxis != null) {
  61419. var newYawAxis = BABYLON.Axis.Y;
  61420. var newPitchAxis = BABYLON.Axis.X;
  61421. if (options.yawAxis != null) {
  61422. newYawAxis = options.yawAxis.clone();
  61423. newYawAxis.normalize();
  61424. }
  61425. if (options.pitchAxis != null) {
  61426. newPitchAxis = options.pitchAxis.clone();
  61427. newPitchAxis.normalize();
  61428. }
  61429. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61430. this._transformYawPitch = BABYLON.Matrix.Identity();
  61431. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61432. this._transformYawPitchInv = this._transformYawPitch.clone();
  61433. this._transformYawPitch.invert();
  61434. }
  61435. }
  61436. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61437. this.upAxisSpace = BABYLON.Space.LOCAL;
  61438. }
  61439. }
  61440. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61441. /**
  61442. * Get/set the minimum yaw angle that the bone can look to.
  61443. */
  61444. get: function () {
  61445. return this._minYaw;
  61446. },
  61447. set: function (value) {
  61448. this._minYaw = value;
  61449. this._minYawSin = Math.sin(value);
  61450. this._minYawCos = Math.cos(value);
  61451. if (this._maxYaw != null) {
  61452. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61453. this._yawRange = this._maxYaw - this._minYaw;
  61454. }
  61455. },
  61456. enumerable: true,
  61457. configurable: true
  61458. });
  61459. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61460. /**
  61461. * Get/set the maximum yaw angle that the bone can look to.
  61462. */
  61463. get: function () {
  61464. return this._maxYaw;
  61465. },
  61466. set: function (value) {
  61467. this._maxYaw = value;
  61468. this._maxYawSin = Math.sin(value);
  61469. this._maxYawCos = Math.cos(value);
  61470. if (this._minYaw != null) {
  61471. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61472. this._yawRange = this._maxYaw - this._minYaw;
  61473. }
  61474. },
  61475. enumerable: true,
  61476. configurable: true
  61477. });
  61478. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61479. /**
  61480. * Get/set the minimum pitch angle that the bone can look to.
  61481. */
  61482. get: function () {
  61483. return this._minPitch;
  61484. },
  61485. set: function (value) {
  61486. this._minPitch = value;
  61487. this._minPitchTan = Math.tan(value);
  61488. },
  61489. enumerable: true,
  61490. configurable: true
  61491. });
  61492. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61493. /**
  61494. * Get/set the maximum pitch angle that the bone can look to.
  61495. */
  61496. get: function () {
  61497. return this._maxPitch;
  61498. },
  61499. set: function (value) {
  61500. this._maxPitch = value;
  61501. this._maxPitchTan = Math.tan(value);
  61502. },
  61503. enumerable: true,
  61504. configurable: true
  61505. });
  61506. /**
  61507. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61508. */
  61509. BoneLookController.prototype.update = function () {
  61510. //skip the first frame when slerping so that the mesh rotation is correct
  61511. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61512. this._firstFrameSkipped = true;
  61513. return;
  61514. }
  61515. var bone = this.bone;
  61516. var bonePos = BoneLookController._tmpVecs[0];
  61517. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61518. var target = this.target;
  61519. var _tmpMat1 = BoneLookController._tmpMats[0];
  61520. var _tmpMat2 = BoneLookController._tmpMats[1];
  61521. var mesh = this.mesh;
  61522. var parentBone = bone.getParent();
  61523. var upAxis = BoneLookController._tmpVecs[1];
  61524. upAxis.copyFrom(this.upAxis);
  61525. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61526. if (this._transformYawPitch) {
  61527. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61528. }
  61529. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61530. }
  61531. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61532. mesh.getDirectionToRef(upAxis, upAxis);
  61533. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61534. upAxis.normalize();
  61535. }
  61536. }
  61537. var checkYaw = false;
  61538. var checkPitch = false;
  61539. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61540. checkYaw = true;
  61541. }
  61542. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61543. checkPitch = true;
  61544. }
  61545. if (checkYaw || checkPitch) {
  61546. var spaceMat = BoneLookController._tmpMats[2];
  61547. var spaceMatInv = BoneLookController._tmpMats[3];
  61548. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61549. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61550. }
  61551. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61552. spaceMat.copyFrom(mesh.getWorldMatrix());
  61553. }
  61554. else {
  61555. var forwardAxis = BoneLookController._tmpVecs[2];
  61556. forwardAxis.copyFrom(this._fowardAxis);
  61557. if (this._transformYawPitch) {
  61558. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61559. }
  61560. if (parentBone) {
  61561. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61562. }
  61563. else {
  61564. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61565. }
  61566. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61567. rightAxis.normalize();
  61568. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61569. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61570. }
  61571. spaceMat.invertToRef(spaceMatInv);
  61572. var xzlen = null;
  61573. if (checkPitch) {
  61574. var localTarget = BoneLookController._tmpVecs[3];
  61575. target.subtractToRef(bonePos, localTarget);
  61576. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61577. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61578. var pitch = Math.atan2(localTarget.y, xzlen);
  61579. var newPitch = pitch;
  61580. if (pitch > this._maxPitch) {
  61581. localTarget.y = this._maxPitchTan * xzlen;
  61582. newPitch = this._maxPitch;
  61583. }
  61584. else if (pitch < this._minPitch) {
  61585. localTarget.y = this._minPitchTan * xzlen;
  61586. newPitch = this._minPitch;
  61587. }
  61588. if (pitch != newPitch) {
  61589. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61590. localTarget.addInPlace(bonePos);
  61591. target = localTarget;
  61592. }
  61593. }
  61594. if (checkYaw) {
  61595. var localTarget = BoneLookController._tmpVecs[4];
  61596. target.subtractToRef(bonePos, localTarget);
  61597. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61598. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61599. var newYaw = yaw;
  61600. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61601. if (xzlen == null) {
  61602. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61603. }
  61604. if (this._yawRange > Math.PI) {
  61605. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61606. localTarget.z = this._maxYawCos * xzlen;
  61607. localTarget.x = this._maxYawSin * xzlen;
  61608. newYaw = this._maxYaw;
  61609. }
  61610. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61611. localTarget.z = this._minYawCos * xzlen;
  61612. localTarget.x = this._minYawSin * xzlen;
  61613. newYaw = this._minYaw;
  61614. }
  61615. }
  61616. else {
  61617. if (yaw > this._maxYaw) {
  61618. localTarget.z = this._maxYawCos * xzlen;
  61619. localTarget.x = this._maxYawSin * xzlen;
  61620. newYaw = this._maxYaw;
  61621. }
  61622. else if (yaw < this._minYaw) {
  61623. localTarget.z = this._minYawCos * xzlen;
  61624. localTarget.x = this._minYawSin * xzlen;
  61625. newYaw = this._minYaw;
  61626. }
  61627. }
  61628. }
  61629. if (this._slerping && this._yawRange > Math.PI) {
  61630. //are we going to be crossing into the min/max region?
  61631. var boneFwd = BoneLookController._tmpVecs[8];
  61632. boneFwd.copyFrom(BABYLON.Axis.Z);
  61633. if (this._transformYawPitch) {
  61634. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61635. }
  61636. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61637. this._boneQuat.toRotationMatrix(boneRotMat);
  61638. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61639. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61640. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61641. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61642. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61643. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61644. if (angBtwTar > angBtwMidYaw) {
  61645. if (xzlen == null) {
  61646. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61647. }
  61648. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61649. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61650. if (angBtwMin < angBtwMax) {
  61651. newYaw = boneYaw + Math.PI * .75;
  61652. localTarget.z = Math.cos(newYaw) * xzlen;
  61653. localTarget.x = Math.sin(newYaw) * xzlen;
  61654. }
  61655. else {
  61656. newYaw = boneYaw - Math.PI * .75;
  61657. localTarget.z = Math.cos(newYaw) * xzlen;
  61658. localTarget.x = Math.sin(newYaw) * xzlen;
  61659. }
  61660. }
  61661. }
  61662. if (yaw != newYaw) {
  61663. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61664. localTarget.addInPlace(bonePos);
  61665. target = localTarget;
  61666. }
  61667. }
  61668. }
  61669. var zaxis = BoneLookController._tmpVecs[5];
  61670. var xaxis = BoneLookController._tmpVecs[6];
  61671. var yaxis = BoneLookController._tmpVecs[7];
  61672. var _tmpQuat = BoneLookController._tmpQuat;
  61673. target.subtractToRef(bonePos, zaxis);
  61674. zaxis.normalize();
  61675. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61676. xaxis.normalize();
  61677. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61678. yaxis.normalize();
  61679. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61680. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61681. return;
  61682. }
  61683. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61684. return;
  61685. }
  61686. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61687. return;
  61688. }
  61689. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61690. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61691. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61692. }
  61693. if (this.slerpAmount < 1) {
  61694. if (!this._slerping) {
  61695. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61696. }
  61697. if (this._transformYawPitch) {
  61698. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61699. }
  61700. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61701. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61702. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61703. this._slerping = true;
  61704. }
  61705. else {
  61706. if (this._transformYawPitch) {
  61707. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61708. }
  61709. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61710. this._slerping = false;
  61711. }
  61712. };
  61713. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61714. var angDiff = ang2 - ang1;
  61715. angDiff %= Math.PI * 2;
  61716. if (angDiff > Math.PI) {
  61717. angDiff -= Math.PI * 2;
  61718. }
  61719. else if (angDiff < -Math.PI) {
  61720. angDiff += Math.PI * 2;
  61721. }
  61722. return angDiff;
  61723. };
  61724. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61725. ang1 %= (2 * Math.PI);
  61726. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61727. ang2 %= (2 * Math.PI);
  61728. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61729. var ab = 0;
  61730. if (ang1 < ang2) {
  61731. ab = ang2 - ang1;
  61732. }
  61733. else {
  61734. ab = ang1 - ang2;
  61735. }
  61736. if (ab > Math.PI) {
  61737. ab = Math.PI * 2 - ab;
  61738. }
  61739. return ab;
  61740. };
  61741. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61742. ang %= (2 * Math.PI);
  61743. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61744. ang1 %= (2 * Math.PI);
  61745. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61746. ang2 %= (2 * Math.PI);
  61747. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61748. if (ang1 < ang2) {
  61749. if (ang > ang1 && ang < ang2) {
  61750. return true;
  61751. }
  61752. }
  61753. else {
  61754. if (ang > ang2 && ang < ang1) {
  61755. return true;
  61756. }
  61757. }
  61758. return false;
  61759. };
  61760. 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()];
  61761. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61762. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61763. return BoneLookController;
  61764. }());
  61765. BABYLON.BoneLookController = BoneLookController;
  61766. })(BABYLON || (BABYLON = {}));
  61767. //# sourceMappingURL=babylon.boneLookController.js.map
  61768. var BABYLON;
  61769. (function (BABYLON) {
  61770. var Skeleton = /** @class */ (function () {
  61771. function Skeleton(name, id, scene) {
  61772. this.name = name;
  61773. this.id = id;
  61774. this.bones = new Array();
  61775. this.needInitialSkinMatrix = false;
  61776. this._isDirty = true;
  61777. this._meshesWithPoseMatrix = new Array();
  61778. this._identity = BABYLON.Matrix.Identity();
  61779. this._ranges = {};
  61780. this._lastAbsoluteTransformsUpdateId = -1;
  61781. // Events
  61782. /**
  61783. * An event triggered before computing the skeleton's matrices
  61784. * @type {BABYLON.Observable}
  61785. */
  61786. this.onBeforeComputeObservable = new BABYLON.Observable();
  61787. this.bones = [];
  61788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61789. scene.skeletons.push(this);
  61790. //make sure it will recalculate the matrix next time prepare is called.
  61791. this._isDirty = true;
  61792. }
  61793. // Members
  61794. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61795. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61796. return mesh._bonesTransformMatrices;
  61797. }
  61798. if (!this._transformMatrices) {
  61799. this.prepare();
  61800. }
  61801. return this._transformMatrices;
  61802. };
  61803. Skeleton.prototype.getScene = function () {
  61804. return this._scene;
  61805. };
  61806. // Methods
  61807. /**
  61808. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61809. */
  61810. Skeleton.prototype.toString = function (fullDetails) {
  61811. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61812. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61813. if (fullDetails) {
  61814. ret += ", Ranges: {";
  61815. var first = true;
  61816. for (var name_1 in this._ranges) {
  61817. if (first) {
  61818. ret += ", ";
  61819. first = false;
  61820. }
  61821. ret += name_1;
  61822. }
  61823. ret += "}";
  61824. }
  61825. return ret;
  61826. };
  61827. /**
  61828. * Get bone's index searching by name
  61829. * @param {string} name is bone's name to search for
  61830. * @return {number} Indice of the bone. Returns -1 if not found
  61831. */
  61832. Skeleton.prototype.getBoneIndexByName = function (name) {
  61833. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61834. if (this.bones[boneIndex].name === name) {
  61835. return boneIndex;
  61836. }
  61837. }
  61838. return -1;
  61839. };
  61840. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61841. // check name not already in use
  61842. if (!this._ranges[name]) {
  61843. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61844. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61845. if (this.bones[i].animations[0]) {
  61846. this.bones[i].animations[0].createRange(name, from, to);
  61847. }
  61848. }
  61849. }
  61850. };
  61851. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61852. if (deleteFrames === void 0) { deleteFrames = true; }
  61853. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61854. if (this.bones[i].animations[0]) {
  61855. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61856. }
  61857. }
  61858. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61859. };
  61860. Skeleton.prototype.getAnimationRange = function (name) {
  61861. return this._ranges[name];
  61862. };
  61863. /**
  61864. * Returns as an Array, all AnimationRanges defined on this skeleton
  61865. */
  61866. Skeleton.prototype.getAnimationRanges = function () {
  61867. var animationRanges = [];
  61868. var name;
  61869. var i = 0;
  61870. for (name in this._ranges) {
  61871. animationRanges[i] = this._ranges[name];
  61872. i++;
  61873. }
  61874. return animationRanges;
  61875. };
  61876. /**
  61877. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61878. */
  61879. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61880. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61881. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61882. return false;
  61883. }
  61884. var ret = true;
  61885. var frameOffset = this._getHighestAnimationFrame() + 1;
  61886. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61887. var boneDict = {};
  61888. var sourceBones = source.bones;
  61889. var nBones;
  61890. var i;
  61891. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61892. boneDict[sourceBones[i].name] = sourceBones[i];
  61893. }
  61894. if (this.bones.length !== sourceBones.length) {
  61895. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61896. ret = false;
  61897. }
  61898. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61899. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61900. var boneName = this.bones[i].name;
  61901. var sourceBone = boneDict[boneName];
  61902. if (sourceBone) {
  61903. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61904. }
  61905. else {
  61906. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61907. ret = false;
  61908. }
  61909. }
  61910. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61911. var range = source.getAnimationRange(name);
  61912. if (range) {
  61913. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61914. }
  61915. return ret;
  61916. };
  61917. Skeleton.prototype.returnToRest = function () {
  61918. for (var index = 0; index < this.bones.length; index++) {
  61919. this.bones[index].returnToRest();
  61920. }
  61921. };
  61922. Skeleton.prototype._getHighestAnimationFrame = function () {
  61923. var ret = 0;
  61924. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61925. if (this.bones[i].animations[0]) {
  61926. var highest = this.bones[i].animations[0].getHighestFrame();
  61927. if (ret < highest) {
  61928. ret = highest;
  61929. }
  61930. }
  61931. }
  61932. return ret;
  61933. };
  61934. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61935. var range = this.getAnimationRange(name);
  61936. if (!range) {
  61937. return null;
  61938. }
  61939. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61940. };
  61941. Skeleton.prototype._markAsDirty = function () {
  61942. this._isDirty = true;
  61943. };
  61944. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61945. this._meshesWithPoseMatrix.push(mesh);
  61946. };
  61947. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61948. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61949. if (index > -1) {
  61950. this._meshesWithPoseMatrix.splice(index, 1);
  61951. }
  61952. };
  61953. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61954. this.onBeforeComputeObservable.notifyObservers(this);
  61955. for (var index = 0; index < this.bones.length; index++) {
  61956. var bone = this.bones[index];
  61957. var parentBone = bone.getParent();
  61958. if (parentBone) {
  61959. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61960. }
  61961. else {
  61962. if (initialSkinMatrix) {
  61963. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61964. }
  61965. else {
  61966. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61967. }
  61968. }
  61969. if (bone._index !== -1) {
  61970. var mappedIndex = bone._index === null ? index : bone._index;
  61971. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61972. }
  61973. }
  61974. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61975. };
  61976. Skeleton.prototype.prepare = function () {
  61977. if (!this._isDirty) {
  61978. return;
  61979. }
  61980. if (this.needInitialSkinMatrix) {
  61981. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61982. var mesh = this._meshesWithPoseMatrix[index];
  61983. var poseMatrix = mesh.getPoseMatrix();
  61984. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61985. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61986. }
  61987. if (this._synchronizedWithMesh !== mesh) {
  61988. this._synchronizedWithMesh = mesh;
  61989. // Prepare bones
  61990. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61991. var bone = this.bones[boneIndex];
  61992. if (!bone.getParent()) {
  61993. var matrix = bone.getBaseMatrix();
  61994. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61995. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61996. }
  61997. }
  61998. }
  61999. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62000. }
  62001. }
  62002. else {
  62003. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62004. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62005. }
  62006. this._computeTransformMatrices(this._transformMatrices, null);
  62007. }
  62008. this._isDirty = false;
  62009. this._scene._activeBones.addCount(this.bones.length, false);
  62010. };
  62011. Skeleton.prototype.getAnimatables = function () {
  62012. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62013. this._animatables = [];
  62014. for (var index = 0; index < this.bones.length; index++) {
  62015. this._animatables.push(this.bones[index]);
  62016. }
  62017. }
  62018. return this._animatables;
  62019. };
  62020. Skeleton.prototype.clone = function (name, id) {
  62021. var result = new Skeleton(name, id || name, this._scene);
  62022. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62023. for (var index = 0; index < this.bones.length; index++) {
  62024. var source = this.bones[index];
  62025. var parentBone = null;
  62026. var parent_1 = source.getParent();
  62027. if (parent_1) {
  62028. var parentIndex = this.bones.indexOf(parent_1);
  62029. parentBone = result.bones[parentIndex];
  62030. }
  62031. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62032. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62033. }
  62034. if (this._ranges) {
  62035. result._ranges = {};
  62036. for (var rangeName in this._ranges) {
  62037. var range = this._ranges[rangeName];
  62038. if (range) {
  62039. result._ranges[rangeName] = range.clone();
  62040. }
  62041. }
  62042. }
  62043. this._isDirty = true;
  62044. return result;
  62045. };
  62046. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62047. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62048. this.bones.forEach(function (bone) {
  62049. bone.animations.forEach(function (animation) {
  62050. animation.enableBlending = true;
  62051. animation.blendingSpeed = blendingSpeed;
  62052. });
  62053. });
  62054. };
  62055. Skeleton.prototype.dispose = function () {
  62056. this._meshesWithPoseMatrix = [];
  62057. // Animations
  62058. this.getScene().stopAnimation(this);
  62059. // Remove from scene
  62060. this.getScene().removeSkeleton(this);
  62061. };
  62062. Skeleton.prototype.serialize = function () {
  62063. var serializationObject = {};
  62064. serializationObject.name = this.name;
  62065. serializationObject.id = this.id;
  62066. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62067. serializationObject.bones = [];
  62068. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62069. for (var index = 0; index < this.bones.length; index++) {
  62070. var bone = this.bones[index];
  62071. var parent_2 = bone.getParent();
  62072. var serializedBone = {
  62073. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62074. name: bone.name,
  62075. matrix: bone.getBaseMatrix().toArray(),
  62076. rest: bone.getRestPose().toArray()
  62077. };
  62078. serializationObject.bones.push(serializedBone);
  62079. if (bone.length) {
  62080. serializedBone.length = bone.length;
  62081. }
  62082. if (bone.animations && bone.animations.length > 0) {
  62083. serializedBone.animation = bone.animations[0].serialize();
  62084. }
  62085. serializationObject.ranges = [];
  62086. for (var name in this._ranges) {
  62087. var source = this._ranges[name];
  62088. if (!source) {
  62089. continue;
  62090. }
  62091. var range = {};
  62092. range.name = name;
  62093. range.from = source.from;
  62094. range.to = source.to;
  62095. serializationObject.ranges.push(range);
  62096. }
  62097. }
  62098. return serializationObject;
  62099. };
  62100. Skeleton.Parse = function (parsedSkeleton, scene) {
  62101. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62102. if (parsedSkeleton.dimensionsAtRest) {
  62103. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62104. }
  62105. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62106. var index;
  62107. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62108. var parsedBone = parsedSkeleton.bones[index];
  62109. var parentBone = null;
  62110. if (parsedBone.parentBoneIndex > -1) {
  62111. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62112. }
  62113. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62114. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62115. if (parsedBone.length) {
  62116. bone.length = parsedBone.length;
  62117. }
  62118. if (parsedBone.animation) {
  62119. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62120. }
  62121. }
  62122. // placed after bones, so createAnimationRange can cascade down
  62123. if (parsedSkeleton.ranges) {
  62124. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62125. var data = parsedSkeleton.ranges[index];
  62126. skeleton.createAnimationRange(data.name, data.from, data.to);
  62127. }
  62128. }
  62129. return skeleton;
  62130. };
  62131. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62132. if (forceUpdate === void 0) { forceUpdate = false; }
  62133. var renderId = this._scene.getRenderId();
  62134. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62135. this.bones[0].computeAbsoluteTransforms();
  62136. this._lastAbsoluteTransformsUpdateId = renderId;
  62137. }
  62138. };
  62139. Skeleton.prototype.getPoseMatrix = function () {
  62140. var poseMatrix = null;
  62141. if (this._meshesWithPoseMatrix.length > 0) {
  62142. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62143. }
  62144. return poseMatrix;
  62145. };
  62146. Skeleton.prototype.sortBones = function () {
  62147. var bones = new Array();
  62148. var visited = new Array(this.bones.length);
  62149. for (var index = 0; index < this.bones.length; index++) {
  62150. this._sortBones(index, bones, visited);
  62151. }
  62152. this.bones = bones;
  62153. };
  62154. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62155. if (visited[index]) {
  62156. return;
  62157. }
  62158. visited[index] = true;
  62159. var bone = this.bones[index];
  62160. if (bone._index === undefined) {
  62161. bone._index = index;
  62162. }
  62163. var parentBone = bone.getParent();
  62164. if (parentBone) {
  62165. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62166. }
  62167. bones.push(bone);
  62168. };
  62169. return Skeleton;
  62170. }());
  62171. BABYLON.Skeleton = Skeleton;
  62172. })(BABYLON || (BABYLON = {}));
  62173. //# sourceMappingURL=babylon.skeleton.js.map
  62174. var BABYLON;
  62175. (function (BABYLON) {
  62176. var SphericalPolynomial = /** @class */ (function () {
  62177. function SphericalPolynomial() {
  62178. this.x = BABYLON.Vector3.Zero();
  62179. this.y = BABYLON.Vector3.Zero();
  62180. this.z = BABYLON.Vector3.Zero();
  62181. this.xx = BABYLON.Vector3.Zero();
  62182. this.yy = BABYLON.Vector3.Zero();
  62183. this.zz = BABYLON.Vector3.Zero();
  62184. this.xy = BABYLON.Vector3.Zero();
  62185. this.yz = BABYLON.Vector3.Zero();
  62186. this.zx = BABYLON.Vector3.Zero();
  62187. }
  62188. SphericalPolynomial.prototype.addAmbient = function (color) {
  62189. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62190. this.xx = this.xx.add(colorVector);
  62191. this.yy = this.yy.add(colorVector);
  62192. this.zz = this.zz.add(colorVector);
  62193. };
  62194. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62195. var result = new SphericalPolynomial();
  62196. result.x = harmonics.L11.scale(1.02333);
  62197. result.y = harmonics.L1_1.scale(1.02333);
  62198. result.z = harmonics.L10.scale(1.02333);
  62199. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62200. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62201. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62202. result.yz = harmonics.L2_1.scale(0.858086);
  62203. result.zx = harmonics.L21.scale(0.858086);
  62204. result.xy = harmonics.L2_2.scale(0.858086);
  62205. result.scale(1.0 / Math.PI);
  62206. return result;
  62207. };
  62208. SphericalPolynomial.prototype.scale = function (scale) {
  62209. this.x = this.x.scale(scale);
  62210. this.y = this.y.scale(scale);
  62211. this.z = this.z.scale(scale);
  62212. this.xx = this.xx.scale(scale);
  62213. this.yy = this.yy.scale(scale);
  62214. this.zz = this.zz.scale(scale);
  62215. this.yz = this.yz.scale(scale);
  62216. this.zx = this.zx.scale(scale);
  62217. this.xy = this.xy.scale(scale);
  62218. };
  62219. return SphericalPolynomial;
  62220. }());
  62221. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62222. var SphericalHarmonics = /** @class */ (function () {
  62223. function SphericalHarmonics() {
  62224. this.L00 = BABYLON.Vector3.Zero();
  62225. this.L1_1 = BABYLON.Vector3.Zero();
  62226. this.L10 = BABYLON.Vector3.Zero();
  62227. this.L11 = BABYLON.Vector3.Zero();
  62228. this.L2_2 = BABYLON.Vector3.Zero();
  62229. this.L2_1 = BABYLON.Vector3.Zero();
  62230. this.L20 = BABYLON.Vector3.Zero();
  62231. this.L21 = BABYLON.Vector3.Zero();
  62232. this.L22 = BABYLON.Vector3.Zero();
  62233. }
  62234. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62235. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62236. var c = colorVector.scale(deltaSolidAngle);
  62237. this.L00 = this.L00.add(c.scale(0.282095));
  62238. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62239. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62240. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62241. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62242. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62243. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62244. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62245. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62246. };
  62247. SphericalHarmonics.prototype.scale = function (scale) {
  62248. this.L00 = this.L00.scale(scale);
  62249. this.L1_1 = this.L1_1.scale(scale);
  62250. this.L10 = this.L10.scale(scale);
  62251. this.L11 = this.L11.scale(scale);
  62252. this.L2_2 = this.L2_2.scale(scale);
  62253. this.L2_1 = this.L2_1.scale(scale);
  62254. this.L20 = this.L20.scale(scale);
  62255. this.L21 = this.L21.scale(scale);
  62256. this.L22 = this.L22.scale(scale);
  62257. };
  62258. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62259. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62260. //
  62261. // E_lm = A_l * L_lm
  62262. //
  62263. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62264. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62265. // the scaling factors are given in equation 9.
  62266. // Constant (Band 0)
  62267. this.L00 = this.L00.scale(3.141593);
  62268. // Linear (Band 1)
  62269. this.L1_1 = this.L1_1.scale(2.094395);
  62270. this.L10 = this.L10.scale(2.094395);
  62271. this.L11 = this.L11.scale(2.094395);
  62272. // Quadratic (Band 2)
  62273. this.L2_2 = this.L2_2.scale(0.785398);
  62274. this.L2_1 = this.L2_1.scale(0.785398);
  62275. this.L20 = this.L20.scale(0.785398);
  62276. this.L21 = this.L21.scale(0.785398);
  62277. this.L22 = this.L22.scale(0.785398);
  62278. };
  62279. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62280. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62281. // L = (1/pi) * E * rho
  62282. //
  62283. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62284. this.scale(1.0 / Math.PI);
  62285. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62286. // (The pixel shader must apply albedo after texture fetches, etc).
  62287. };
  62288. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62289. var result = new SphericalHarmonics();
  62290. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62291. result.L1_1 = polynomial.y.scale(0.977204);
  62292. result.L10 = polynomial.z.scale(0.977204);
  62293. result.L11 = polynomial.x.scale(0.977204);
  62294. result.L2_2 = polynomial.xy.scale(1.16538);
  62295. result.L2_1 = polynomial.yz.scale(1.16538);
  62296. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62297. result.L21 = polynomial.zx.scale(1.16538);
  62298. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62299. result.scale(Math.PI);
  62300. return result;
  62301. };
  62302. return SphericalHarmonics;
  62303. }());
  62304. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62305. })(BABYLON || (BABYLON = {}));
  62306. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62307. var BABYLON;
  62308. (function (BABYLON) {
  62309. var Internals;
  62310. (function (Internals) {
  62311. var FileFaceOrientation = /** @class */ (function () {
  62312. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62313. this.name = name;
  62314. this.worldAxisForNormal = worldAxisForNormal;
  62315. this.worldAxisForFileX = worldAxisForFileX;
  62316. this.worldAxisForFileY = worldAxisForFileY;
  62317. }
  62318. return FileFaceOrientation;
  62319. }());
  62320. ;
  62321. /**
  62322. * Helper class dealing with the extraction of spherical polynomial dataArray
  62323. * from a cube map.
  62324. */
  62325. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62326. function CubeMapToSphericalPolynomialTools() {
  62327. }
  62328. /**
  62329. * Converts a texture to the according Spherical Polynomial data.
  62330. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62331. *
  62332. * @param texture The texture to extract the information from.
  62333. * @return The Spherical Polynomial data.
  62334. */
  62335. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62336. if (!texture.isCube) {
  62337. // Only supports cube Textures currently.
  62338. return null;
  62339. }
  62340. var size = texture.getSize().width;
  62341. var right = texture.readPixels(0);
  62342. var left = texture.readPixels(1);
  62343. var up;
  62344. var down;
  62345. if (texture.isRenderTarget) {
  62346. up = texture.readPixels(3);
  62347. down = texture.readPixels(2);
  62348. }
  62349. else {
  62350. up = texture.readPixels(2);
  62351. down = texture.readPixels(3);
  62352. }
  62353. var front = texture.readPixels(4);
  62354. var back = texture.readPixels(5);
  62355. var gammaSpace = texture.gammaSpace;
  62356. // Always read as RGBA.
  62357. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62358. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62359. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62360. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62361. }
  62362. var cubeInfo = {
  62363. size: size,
  62364. right: right,
  62365. left: left,
  62366. up: up,
  62367. down: down,
  62368. front: front,
  62369. back: back,
  62370. format: format,
  62371. type: type,
  62372. gammaSpace: gammaSpace,
  62373. };
  62374. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62375. };
  62376. /**
  62377. * Converts a cubemap to the according Spherical Polynomial data.
  62378. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62379. *
  62380. * @param cubeInfo The Cube map to extract the information from.
  62381. * @return The Spherical Polynomial data.
  62382. */
  62383. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62384. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62385. var totalSolidAngle = 0.0;
  62386. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62387. var du = 2.0 / cubeInfo.size;
  62388. var dv = du;
  62389. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62390. var minUV = du * 0.5 - 1.0;
  62391. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62392. var fileFace = this.FileFaces[faceIndex];
  62393. var dataArray = cubeInfo[fileFace.name];
  62394. var v = minUV;
  62395. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62396. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62397. // Because SP is still linear, so summation is fine in that basis.
  62398. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62399. for (var y = 0; y < cubeInfo.size; y++) {
  62400. var u = minUV;
  62401. for (var x = 0; x < cubeInfo.size; x++) {
  62402. // World direction (not normalised)
  62403. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62404. worldDirection.normalize();
  62405. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62406. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62407. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62408. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62409. // Handle Integer types.
  62410. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62411. r /= 255;
  62412. g /= 255;
  62413. b /= 255;
  62414. }
  62415. // Handle Gamma space textures.
  62416. if (cubeInfo.gammaSpace) {
  62417. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62418. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62419. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62420. }
  62421. var color = new BABYLON.Color3(r, g, b);
  62422. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62423. totalSolidAngle += deltaSolidAngle;
  62424. u += du;
  62425. }
  62426. v += dv;
  62427. }
  62428. }
  62429. // Solid angle for entire sphere is 4*pi
  62430. var sphereSolidAngle = 4.0 * Math.PI;
  62431. // Adjust the solid angle to allow for how many faces we processed.
  62432. var facesProcessed = 6.0;
  62433. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62434. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62435. // This is needed because the numerical integration over the cube uses a
  62436. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62437. // and also to compensate for accumulative error due to float precision in the summation.
  62438. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62439. sphericalHarmonics.scale(correctionFactor);
  62440. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62441. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62442. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62443. };
  62444. CubeMapToSphericalPolynomialTools.FileFaces = [
  62445. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62446. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62447. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62448. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62449. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62450. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62451. ];
  62452. return CubeMapToSphericalPolynomialTools;
  62453. }());
  62454. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62455. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62456. })(BABYLON || (BABYLON = {}));
  62457. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62458. var BABYLON;
  62459. (function (BABYLON) {
  62460. var Internals;
  62461. (function (Internals) {
  62462. /**
  62463. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62464. */
  62465. var PanoramaToCubeMapTools = /** @class */ (function () {
  62466. function PanoramaToCubeMapTools() {
  62467. }
  62468. /**
  62469. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62470. *
  62471. * @param float32Array The source data.
  62472. * @param inputWidth The width of the input panorama.
  62473. * @param inputhHeight The height of the input panorama.
  62474. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62475. * @return The cubemap data
  62476. */
  62477. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62478. if (!float32Array) {
  62479. throw "ConvertPanoramaToCubemap: input cannot be null";
  62480. }
  62481. if (float32Array.length != inputWidth * inputHeight * 3) {
  62482. throw "ConvertPanoramaToCubemap: input size is wrong";
  62483. }
  62484. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62485. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62486. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62487. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62488. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62489. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62490. return {
  62491. front: textureFront,
  62492. back: textureBack,
  62493. left: textureLeft,
  62494. right: textureRight,
  62495. up: textureUp,
  62496. down: textureDown,
  62497. size: size,
  62498. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62499. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62500. gammaSpace: false,
  62501. };
  62502. };
  62503. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62504. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62505. var textureArray = new Float32Array(buffer);
  62506. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62507. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62508. var dy = 1 / texSize;
  62509. var fy = 0;
  62510. for (var y = 0; y < texSize; y++) {
  62511. var xv1 = faceData[0];
  62512. var xv2 = faceData[2];
  62513. for (var x = 0; x < texSize; x++) {
  62514. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62515. v.normalize();
  62516. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62517. // 3 channels per pixels
  62518. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62519. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62520. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62521. xv1 = xv1.add(rotDX1);
  62522. xv2 = xv2.add(rotDX2);
  62523. }
  62524. fy += dy;
  62525. }
  62526. return textureArray;
  62527. };
  62528. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62529. var theta = Math.atan2(vDir.z, vDir.x);
  62530. var phi = Math.acos(vDir.y);
  62531. while (theta < -Math.PI)
  62532. theta += 2 * Math.PI;
  62533. while (theta > Math.PI)
  62534. theta -= 2 * Math.PI;
  62535. var dx = theta / Math.PI;
  62536. var dy = phi / Math.PI;
  62537. // recenter.
  62538. dx = dx * 0.5 + 0.5;
  62539. var px = Math.round(dx * inputWidth);
  62540. if (px < 0)
  62541. px = 0;
  62542. else if (px >= inputWidth)
  62543. px = inputWidth - 1;
  62544. var py = Math.round(dy * inputHeight);
  62545. if (py < 0)
  62546. py = 0;
  62547. else if (py >= inputHeight)
  62548. py = inputHeight - 1;
  62549. var inputY = (inputHeight - py - 1);
  62550. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62551. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62552. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62553. return {
  62554. r: r,
  62555. g: g,
  62556. b: b
  62557. };
  62558. };
  62559. PanoramaToCubeMapTools.FACE_FRONT = [
  62560. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62561. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62562. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62563. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62564. ];
  62565. PanoramaToCubeMapTools.FACE_BACK = [
  62566. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62567. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62568. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62569. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62570. ];
  62571. PanoramaToCubeMapTools.FACE_RIGHT = [
  62572. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62573. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62574. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62575. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62576. ];
  62577. PanoramaToCubeMapTools.FACE_LEFT = [
  62578. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62579. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62580. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62581. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62582. ];
  62583. PanoramaToCubeMapTools.FACE_DOWN = [
  62584. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62585. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62586. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62587. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62588. ];
  62589. PanoramaToCubeMapTools.FACE_UP = [
  62590. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62591. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62592. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62593. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62594. ];
  62595. return PanoramaToCubeMapTools;
  62596. }());
  62597. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62598. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62599. })(BABYLON || (BABYLON = {}));
  62600. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62601. var BABYLON;
  62602. (function (BABYLON) {
  62603. var Internals;
  62604. (function (Internals) {
  62605. ;
  62606. /**
  62607. * This groups tools to convert HDR texture to native colors array.
  62608. */
  62609. var HDRTools = /** @class */ (function () {
  62610. function HDRTools() {
  62611. }
  62612. HDRTools.Ldexp = function (mantissa, exponent) {
  62613. if (exponent > 1023) {
  62614. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62615. }
  62616. if (exponent < -1074) {
  62617. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62618. }
  62619. return mantissa * Math.pow(2, exponent);
  62620. };
  62621. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62622. if (exponent > 0) {
  62623. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62624. float32array[index + 0] = red * exponent;
  62625. float32array[index + 1] = green * exponent;
  62626. float32array[index + 2] = blue * exponent;
  62627. }
  62628. else {
  62629. float32array[index + 0] = 0;
  62630. float32array[index + 1] = 0;
  62631. float32array[index + 2] = 0;
  62632. }
  62633. };
  62634. HDRTools.readStringLine = function (uint8array, startIndex) {
  62635. var line = "";
  62636. var character = "";
  62637. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62638. character = String.fromCharCode(uint8array[i]);
  62639. if (character == "\n") {
  62640. break;
  62641. }
  62642. line += character;
  62643. }
  62644. return line;
  62645. };
  62646. /**
  62647. * Reads header information from an RGBE texture stored in a native array.
  62648. * More information on this format are available here:
  62649. * https://en.wikipedia.org/wiki/RGBE_image_format
  62650. *
  62651. * @param uint8array The binary file stored in native array.
  62652. * @return The header information.
  62653. */
  62654. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62655. var height = 0;
  62656. var width = 0;
  62657. var line = this.readStringLine(uint8array, 0);
  62658. if (line[0] != '#' || line[1] != '?') {
  62659. throw "Bad HDR Format.";
  62660. }
  62661. var endOfHeader = false;
  62662. var findFormat = false;
  62663. var lineIndex = 0;
  62664. do {
  62665. lineIndex += (line.length + 1);
  62666. line = this.readStringLine(uint8array, lineIndex);
  62667. if (line == "FORMAT=32-bit_rle_rgbe") {
  62668. findFormat = true;
  62669. }
  62670. else if (line.length == 0) {
  62671. endOfHeader = true;
  62672. }
  62673. } while (!endOfHeader);
  62674. if (!findFormat) {
  62675. throw "HDR Bad header format, unsupported FORMAT";
  62676. }
  62677. lineIndex += (line.length + 1);
  62678. line = this.readStringLine(uint8array, lineIndex);
  62679. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62680. var match = sizeRegexp.exec(line);
  62681. // TODO. Support +Y and -X if needed.
  62682. if (!match || match.length < 3) {
  62683. throw "HDR Bad header format, no size";
  62684. }
  62685. width = parseInt(match[2]);
  62686. height = parseInt(match[1]);
  62687. if (width < 8 || width > 0x7fff) {
  62688. throw "HDR Bad header format, unsupported size";
  62689. }
  62690. lineIndex += (line.length + 1);
  62691. return {
  62692. height: height,
  62693. width: width,
  62694. dataPosition: lineIndex
  62695. };
  62696. };
  62697. /**
  62698. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62699. * This RGBE texture needs to store the information as a panorama.
  62700. *
  62701. * More information on this format are available here:
  62702. * https://en.wikipedia.org/wiki/RGBE_image_format
  62703. *
  62704. * @param buffer The binary file stored in an array buffer.
  62705. * @param size The expected size of the extracted cubemap.
  62706. * @return The Cube Map information.
  62707. */
  62708. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62709. var uint8array = new Uint8Array(buffer);
  62710. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62711. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62712. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62713. return cubeMapData;
  62714. };
  62715. /**
  62716. * Returns the pixels data extracted from an RGBE texture.
  62717. * This pixels will be stored left to right up to down in the R G B order in one array.
  62718. *
  62719. * More information on this format are available here:
  62720. * https://en.wikipedia.org/wiki/RGBE_image_format
  62721. *
  62722. * @param uint8array The binary file stored in an array buffer.
  62723. * @param hdrInfo The header information of the file.
  62724. * @return The pixels data in RGB right to left up to down order.
  62725. */
  62726. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62727. // Keep for multi format supports.
  62728. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62729. };
  62730. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62731. var num_scanlines = hdrInfo.height;
  62732. var scanline_width = hdrInfo.width;
  62733. var a, b, c, d, count;
  62734. var dataIndex = hdrInfo.dataPosition;
  62735. var index = 0, endIndex = 0, i = 0;
  62736. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62737. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62738. // 3 channels of 4 bytes per pixel in float.
  62739. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62740. var resultArray = new Float32Array(resultBuffer);
  62741. // read in each successive scanline
  62742. while (num_scanlines > 0) {
  62743. a = uint8array[dataIndex++];
  62744. b = uint8array[dataIndex++];
  62745. c = uint8array[dataIndex++];
  62746. d = uint8array[dataIndex++];
  62747. if (a != 2 || b != 2 || (c & 0x80)) {
  62748. // this file is not run length encoded
  62749. throw "HDR Bad header format, not RLE";
  62750. }
  62751. if (((c << 8) | d) != scanline_width) {
  62752. throw "HDR Bad header format, wrong scan line width";
  62753. }
  62754. index = 0;
  62755. // read each of the four channels for the scanline into the buffer
  62756. for (i = 0; i < 4; i++) {
  62757. endIndex = (i + 1) * scanline_width;
  62758. while (index < endIndex) {
  62759. a = uint8array[dataIndex++];
  62760. b = uint8array[dataIndex++];
  62761. if (a > 128) {
  62762. // a run of the same value
  62763. count = a - 128;
  62764. if ((count == 0) || (count > endIndex - index)) {
  62765. throw "HDR Bad Format, bad scanline data (run)";
  62766. }
  62767. while (count-- > 0) {
  62768. scanLineArray[index++] = b;
  62769. }
  62770. }
  62771. else {
  62772. // a non-run
  62773. count = a;
  62774. if ((count == 0) || (count > endIndex - index)) {
  62775. throw "HDR Bad Format, bad scanline data (non-run)";
  62776. }
  62777. scanLineArray[index++] = b;
  62778. if (--count > 0) {
  62779. for (var j = 0; j < count; j++) {
  62780. scanLineArray[index++] = uint8array[dataIndex++];
  62781. }
  62782. }
  62783. }
  62784. }
  62785. }
  62786. // now convert data from buffer into floats
  62787. for (i = 0; i < scanline_width; i++) {
  62788. a = scanLineArray[i];
  62789. b = scanLineArray[i + scanline_width];
  62790. c = scanLineArray[i + 2 * scanline_width];
  62791. d = scanLineArray[i + 3 * scanline_width];
  62792. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62793. }
  62794. num_scanlines--;
  62795. }
  62796. return resultArray;
  62797. };
  62798. return HDRTools;
  62799. }());
  62800. Internals.HDRTools = HDRTools;
  62801. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62802. })(BABYLON || (BABYLON = {}));
  62803. //# sourceMappingURL=babylon.hdr.js.map
  62804. var BABYLON;
  62805. (function (BABYLON) {
  62806. /**
  62807. * This represents a texture coming from an HDR input.
  62808. *
  62809. * The only supported format is currently panorama picture stored in RGBE format.
  62810. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62811. */
  62812. var HDRCubeTexture = /** @class */ (function (_super) {
  62813. __extends(HDRCubeTexture, _super);
  62814. /**
  62815. * Instantiates an HDRTexture from the following parameters.
  62816. *
  62817. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62818. * @param scene The scene the texture will be used in
  62819. * @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.
  62820. * @param noMipmap Forces to not generate the mipmap if true
  62821. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62822. * @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)
  62823. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62824. */
  62825. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62826. if (noMipmap === void 0) { noMipmap = false; }
  62827. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62828. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62829. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62830. if (onLoad === void 0) { onLoad = null; }
  62831. if (onError === void 0) { onError = null; }
  62832. var _this = _super.call(this, scene) || this;
  62833. _this._useInGammaSpace = false;
  62834. _this._generateHarmonics = true;
  62835. _this._isBABYLONPreprocessed = false;
  62836. _this._onLoad = null;
  62837. _this._onError = null;
  62838. /**
  62839. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62840. */
  62841. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62842. /**
  62843. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62844. * This is usefull at run time to apply the good shader.
  62845. */
  62846. _this.isPMREM = false;
  62847. _this._isBlocking = true;
  62848. if (!url) {
  62849. return _this;
  62850. }
  62851. _this.name = url;
  62852. _this.url = url;
  62853. _this.hasAlpha = false;
  62854. _this.isCube = true;
  62855. _this._textureMatrix = BABYLON.Matrix.Identity();
  62856. _this._onLoad = onLoad;
  62857. _this._onError = onError;
  62858. _this.gammaSpace = false;
  62859. var caps = scene.getEngine().getCaps();
  62860. if (size) {
  62861. _this._isBABYLONPreprocessed = false;
  62862. _this._noMipmap = noMipmap;
  62863. _this._size = size;
  62864. _this._useInGammaSpace = useInGammaSpace;
  62865. _this._usePMREMGenerator = usePMREMGenerator &&
  62866. caps.textureLOD &&
  62867. caps.textureFloat &&
  62868. !_this._useInGammaSpace;
  62869. }
  62870. else {
  62871. _this._isBABYLONPreprocessed = true;
  62872. _this._noMipmap = false;
  62873. _this._useInGammaSpace = false;
  62874. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62875. !_this._useInGammaSpace;
  62876. }
  62877. _this.isPMREM = _this._usePMREMGenerator;
  62878. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62879. if (!_this._texture) {
  62880. if (!scene.useDelayedTextureLoading) {
  62881. _this.loadTexture();
  62882. }
  62883. else {
  62884. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62885. }
  62886. }
  62887. return _this;
  62888. }
  62889. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62890. /**
  62891. * Gets wether or not the texture is blocking during loading.
  62892. */
  62893. get: function () {
  62894. return this._isBlocking;
  62895. },
  62896. /**
  62897. * Sets wether or not the texture is blocking during loading.
  62898. */
  62899. set: function (value) {
  62900. this._isBlocking = value;
  62901. },
  62902. enumerable: true,
  62903. configurable: true
  62904. });
  62905. /**
  62906. * Occurs when the file is a preprocessed .babylon.hdr file.
  62907. */
  62908. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62909. var _this = this;
  62910. var mipLevels = 0;
  62911. var floatArrayView = null;
  62912. var scene = this.getScene();
  62913. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  62914. var mips = new Array();
  62915. if (!floatArrayView) {
  62916. return mips;
  62917. }
  62918. var startIndex = 30;
  62919. for (var level = 0; level < mipLevels; level++) {
  62920. mips.push([]);
  62921. // Fill each pixel of the mip level.
  62922. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62923. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62924. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62925. mips[level].push(faceData);
  62926. startIndex += faceSize;
  62927. }
  62928. }
  62929. return mips;
  62930. } : null;
  62931. var callback = function (buffer) {
  62932. var scene = _this.getScene();
  62933. if (!scene) {
  62934. return null;
  62935. }
  62936. // Create Native Array Views
  62937. var intArrayView = new Int32Array(buffer);
  62938. floatArrayView = new Float32Array(buffer);
  62939. // Fill header.
  62940. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62941. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62942. // Update Texture Information.
  62943. if (!_this._texture) {
  62944. return null;
  62945. }
  62946. _this._texture.updateSize(_this._size, _this._size);
  62947. // Fill polynomial information.
  62948. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62949. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62950. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62951. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62952. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62953. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62954. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62955. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62956. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62957. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62958. _this.sphericalPolynomial = sphericalPolynomial;
  62959. // Fill pixel data.
  62960. mipLevels = intArrayView[29]; // Number of mip levels.
  62961. var startIndex = 30;
  62962. var data = [];
  62963. var faceSize = Math.pow(_this._size, 2) * 3;
  62964. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62965. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62966. startIndex += faceSize;
  62967. }
  62968. var results = [];
  62969. var byteArray = null;
  62970. // Push each faces.
  62971. for (var k = 0; k < 6; k++) {
  62972. var dataFace = null;
  62973. // To be deprecated.
  62974. if (version === 1) {
  62975. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62976. dataFace = data[j];
  62977. }
  62978. // If special cases.
  62979. if (!mipmapGenerator && dataFace) {
  62980. if (!scene.getEngine().getCaps().textureFloat) {
  62981. // 3 channels of 1 bytes per pixel in bytes.
  62982. var byteBuffer = new ArrayBuffer(faceSize);
  62983. byteArray = new Uint8Array(byteBuffer);
  62984. }
  62985. for (var i = 0; i < _this._size * _this._size; i++) {
  62986. // Put in gamma space if requested.
  62987. if (_this._useInGammaSpace) {
  62988. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62989. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62990. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62991. }
  62992. // Convert to int texture for fallback.
  62993. if (byteArray) {
  62994. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62995. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62996. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62997. // May use luminance instead if the result is not accurate.
  62998. var max = Math.max(Math.max(r, g), b);
  62999. if (max > 255) {
  63000. var scale = 255 / max;
  63001. r *= scale;
  63002. g *= scale;
  63003. b *= scale;
  63004. }
  63005. byteArray[(i * 3) + 0] = r;
  63006. byteArray[(i * 3) + 1] = g;
  63007. byteArray[(i * 3) + 2] = b;
  63008. }
  63009. }
  63010. }
  63011. // Fill the array accordingly.
  63012. if (byteArray) {
  63013. results.push(byteArray);
  63014. }
  63015. else {
  63016. results.push(dataFace);
  63017. }
  63018. }
  63019. return results;
  63020. };
  63021. if (scene) {
  63022. 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);
  63023. }
  63024. };
  63025. /**
  63026. * Occurs when the file is raw .hdr file.
  63027. */
  63028. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63029. var _this = this;
  63030. var callback = function (buffer) {
  63031. var scene = _this.getScene();
  63032. if (!scene) {
  63033. return null;
  63034. }
  63035. // Extract the raw linear data.
  63036. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63037. // Generate harmonics if needed.
  63038. if (_this._generateHarmonics) {
  63039. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63040. _this.sphericalPolynomial = sphericalPolynomial;
  63041. }
  63042. var results = [];
  63043. var byteArray = null;
  63044. // Push each faces.
  63045. for (var j = 0; j < 6; j++) {
  63046. // Create uintarray fallback.
  63047. if (!scene.getEngine().getCaps().textureFloat) {
  63048. // 3 channels of 1 bytes per pixel in bytes.
  63049. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63050. byteArray = new Uint8Array(byteBuffer);
  63051. }
  63052. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63053. // If special cases.
  63054. if (_this._useInGammaSpace || byteArray) {
  63055. for (var i = 0; i < _this._size * _this._size; i++) {
  63056. // Put in gamma space if requested.
  63057. if (_this._useInGammaSpace) {
  63058. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63059. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63060. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63061. }
  63062. // Convert to int texture for fallback.
  63063. if (byteArray) {
  63064. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63065. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63066. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63067. // May use luminance instead if the result is not accurate.
  63068. var max = Math.max(Math.max(r, g), b);
  63069. if (max > 255) {
  63070. var scale = 255 / max;
  63071. r *= scale;
  63072. g *= scale;
  63073. b *= scale;
  63074. }
  63075. byteArray[(i * 3) + 0] = r;
  63076. byteArray[(i * 3) + 1] = g;
  63077. byteArray[(i * 3) + 2] = b;
  63078. }
  63079. }
  63080. }
  63081. if (byteArray) {
  63082. results.push(byteArray);
  63083. }
  63084. else {
  63085. results.push(dataFace);
  63086. }
  63087. }
  63088. return results;
  63089. };
  63090. var mipmapGenerator = null;
  63091. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63092. // if (!this._noMipmap &&
  63093. // this._usePMREMGenerator) {
  63094. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63095. // // Custom setup of the generator matching with the PBR shader values.
  63096. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63097. // this._size,
  63098. // this._size,
  63099. // 0,
  63100. // 3,
  63101. // this.getScene().getEngine().getCaps().textureFloat,
  63102. // 2048,
  63103. // 0.25,
  63104. // false,
  63105. // true);
  63106. // return generator.filterCubeMap();
  63107. // };
  63108. // }
  63109. var scene = this.getScene();
  63110. if (scene) {
  63111. 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);
  63112. }
  63113. };
  63114. /**
  63115. * Starts the loading process of the texture.
  63116. */
  63117. HDRCubeTexture.prototype.loadTexture = function () {
  63118. if (this._isBABYLONPreprocessed) {
  63119. this.loadBabylonTexture();
  63120. }
  63121. else {
  63122. this.loadHDRTexture();
  63123. }
  63124. };
  63125. HDRCubeTexture.prototype.clone = function () {
  63126. var scene = this.getScene();
  63127. if (!scene) {
  63128. return this;
  63129. }
  63130. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63131. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63132. // Base texture
  63133. newTexture.level = this.level;
  63134. newTexture.wrapU = this.wrapU;
  63135. newTexture.wrapV = this.wrapV;
  63136. newTexture.coordinatesIndex = this.coordinatesIndex;
  63137. newTexture.coordinatesMode = this.coordinatesMode;
  63138. return newTexture;
  63139. };
  63140. // Methods
  63141. HDRCubeTexture.prototype.delayLoad = function () {
  63142. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63143. return;
  63144. }
  63145. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63146. this._texture = this._getFromCache(this.url, this._noMipmap);
  63147. if (!this._texture) {
  63148. this.loadTexture();
  63149. }
  63150. };
  63151. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63152. return this._textureMatrix;
  63153. };
  63154. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63155. this._textureMatrix = value;
  63156. };
  63157. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63158. var texture = null;
  63159. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63160. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63161. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63162. texture.name = parsedTexture.name;
  63163. texture.hasAlpha = parsedTexture.hasAlpha;
  63164. texture.level = parsedTexture.level;
  63165. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63166. texture.isBlocking = parsedTexture.isBlocking;
  63167. }
  63168. return texture;
  63169. };
  63170. HDRCubeTexture.prototype.serialize = function () {
  63171. if (!this.name) {
  63172. return null;
  63173. }
  63174. var serializationObject = {};
  63175. serializationObject.name = this.name;
  63176. serializationObject.hasAlpha = this.hasAlpha;
  63177. serializationObject.isCube = true;
  63178. serializationObject.level = this.level;
  63179. serializationObject.size = this._size;
  63180. serializationObject.coordinatesMode = this.coordinatesMode;
  63181. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63182. serializationObject.generateHarmonics = this._generateHarmonics;
  63183. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63184. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63185. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63186. serializationObject.noMipmap = this._noMipmap;
  63187. serializationObject.isBlocking = this._isBlocking;
  63188. return serializationObject;
  63189. };
  63190. /**
  63191. * Saves as a file the data contained in the texture in a binary format.
  63192. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63193. * as the spherical used in the lighting.
  63194. * @param url The HDR file url.
  63195. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63196. * @param onError Method called if any error happens during download.
  63197. * @return The packed binary data.
  63198. */
  63199. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63200. if (onError === void 0) { onError = null; }
  63201. var callback = function (buffer) {
  63202. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63203. // Returns a URL you can use as a href.
  63204. var objUrl = window.URL.createObjectURL(data);
  63205. // Simulates a link to it and click to dowload.
  63206. var a = document.createElement("a");
  63207. document.body.appendChild(a);
  63208. a.style.display = "none";
  63209. a.href = objUrl;
  63210. a.download = "envmap.babylon.hdr";
  63211. a.click();
  63212. };
  63213. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63214. };
  63215. /**
  63216. * Serializes the data contained in the texture in a binary format.
  63217. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63218. * as the spherical used in the lighting.
  63219. * @param url The HDR file url.
  63220. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63221. * @param onError Method called if any error happens during download.
  63222. * @return The packed binary data.
  63223. */
  63224. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63225. if (onError === void 0) { onError = null; }
  63226. // Needs the url tho create the texture.
  63227. if (!url) {
  63228. return;
  63229. }
  63230. // Check Power of two size.
  63231. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63232. return;
  63233. }
  63234. // Coming Back in 3.x.
  63235. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63236. };
  63237. HDRCubeTexture._facesMapping = [
  63238. "right",
  63239. "left",
  63240. "up",
  63241. "down",
  63242. "front",
  63243. "back"
  63244. ];
  63245. return HDRCubeTexture;
  63246. }(BABYLON.BaseTexture));
  63247. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63248. })(BABYLON || (BABYLON = {}));
  63249. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63250. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63251. // Huge respect for a such great lib.
  63252. // Earcut license:
  63253. // Copyright (c) 2016, Mapbox
  63254. //
  63255. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63256. // with or without fee is hereby granted, provided that the above copyright notice
  63257. // and this permission notice appear in all copies.
  63258. //
  63259. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63260. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63261. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63262. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63263. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63264. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63265. // THIS SOFTWARE.
  63266. var Earcut;
  63267. (function (Earcut) {
  63268. /**
  63269. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63270. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63271. * @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).
  63272. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63273. */
  63274. function earcut(data, holeIndices, dim) {
  63275. dim = dim || 2;
  63276. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63277. if (!outerNode)
  63278. return triangles;
  63279. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63280. if (hasHoles)
  63281. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63282. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63283. if (data.length > 80 * dim) {
  63284. minX = maxX = data[0];
  63285. minY = maxY = data[1];
  63286. for (var i = dim; i < outerLen; i += dim) {
  63287. x = data[i];
  63288. y = data[i + 1];
  63289. if (x < minX)
  63290. minX = x;
  63291. if (y < minY)
  63292. minY = y;
  63293. if (x > maxX)
  63294. maxX = x;
  63295. if (y > maxY)
  63296. maxY = y;
  63297. }
  63298. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63299. size = Math.max(maxX - minX, maxY - minY);
  63300. }
  63301. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63302. return triangles;
  63303. }
  63304. Earcut.earcut = earcut;
  63305. var Node = /** @class */ (function () {
  63306. function Node(i, x, y) {
  63307. this.i = i;
  63308. this.x = x;
  63309. this.y = y;
  63310. this.prev = null;
  63311. this.next = null;
  63312. this.z = null;
  63313. this.prevZ = null;
  63314. this.nextZ = null;
  63315. this.steiner = false;
  63316. }
  63317. return Node;
  63318. }());
  63319. // create a circular doubly linked list from polygon points in the specified winding order
  63320. function linkedList(data, start, end, dim, clockwise) {
  63321. var i, last = null;
  63322. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63323. for (i = start; i < end; i += dim)
  63324. last = insertNode(i, data[i], data[i + 1], last);
  63325. }
  63326. else {
  63327. for (i = end - dim; i >= start; i -= dim)
  63328. last = insertNode(i, data[i], data[i + 1], last);
  63329. }
  63330. if (last && equals(last, last.next)) {
  63331. removeNode(last);
  63332. last = last.next;
  63333. }
  63334. return last;
  63335. }
  63336. // eliminate colinear or duplicate points
  63337. function filterPoints(start, end) {
  63338. if (!start)
  63339. return start;
  63340. if (!end)
  63341. end = start;
  63342. var p = start, again;
  63343. do {
  63344. again = false;
  63345. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63346. removeNode(p);
  63347. p = end = p.prev;
  63348. if (p === p.next)
  63349. return undefined;
  63350. again = true;
  63351. }
  63352. else {
  63353. p = p.next;
  63354. }
  63355. } while (again || p !== end);
  63356. return end;
  63357. }
  63358. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63359. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63360. if (!ear)
  63361. return;
  63362. // interlink polygon nodes in z-order
  63363. if (!pass && size)
  63364. indexCurve(ear, minX, minY, size);
  63365. var stop = ear, prev, next;
  63366. // iterate through ears, slicing them one by one
  63367. while (ear.prev !== ear.next) {
  63368. prev = ear.prev;
  63369. next = ear.next;
  63370. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63371. // cut off the triangle
  63372. triangles.push(prev.i / dim);
  63373. triangles.push(ear.i / dim);
  63374. triangles.push(next.i / dim);
  63375. removeNode(ear);
  63376. // skipping the next vertice leads to less sliver triangles
  63377. ear = next.next;
  63378. stop = next.next;
  63379. continue;
  63380. }
  63381. ear = next;
  63382. // if we looped through the whole remaining polygon and can't find any more ears
  63383. if (ear === stop) {
  63384. // try filtering points and slicing again
  63385. if (!pass) {
  63386. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63387. // if this didn't work, try curing all small self-intersections locally
  63388. }
  63389. else if (pass === 1) {
  63390. ear = cureLocalIntersections(ear, triangles, dim);
  63391. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63392. // as a last resort, try splitting the remaining polygon into two
  63393. }
  63394. else if (pass === 2) {
  63395. splitEarcut(ear, triangles, dim, minX, minY, size);
  63396. }
  63397. break;
  63398. }
  63399. }
  63400. }
  63401. // check whether a polygon node forms a valid ear with adjacent nodes
  63402. function isEar(ear) {
  63403. var a = ear.prev, b = ear, c = ear.next;
  63404. if (area(a, b, c) >= 0)
  63405. return false; // reflex, can't be an ear
  63406. // now make sure we don't have other points inside the potential ear
  63407. var p = ear.next.next;
  63408. while (p !== ear.prev) {
  63409. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63410. area(p.prev, p, p.next) >= 0)
  63411. return false;
  63412. p = p.next;
  63413. }
  63414. return true;
  63415. }
  63416. function isEarHashed(ear, minX, minY, size) {
  63417. var a = ear.prev, b = ear, c = ear.next;
  63418. if (area(a, b, c) >= 0)
  63419. return false; // reflex, can't be an ear
  63420. // triangle bbox; min & max are calculated like this for speed
  63421. 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);
  63422. // z-order range for the current triangle bbox;
  63423. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63424. // first look for points inside the triangle in increasing z-order
  63425. var p = ear.nextZ;
  63426. while (p && p.z <= maxZ) {
  63427. if (p !== ear.prev &&
  63428. p !== ear.next &&
  63429. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63430. area(p.prev, p, p.next) >= 0)
  63431. return false;
  63432. p = p.nextZ;
  63433. }
  63434. // then look for points in decreasing z-order
  63435. p = ear.prevZ;
  63436. while (p && p.z >= minZ) {
  63437. if (p !== ear.prev &&
  63438. p !== ear.next &&
  63439. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63440. area(p.prev, p, p.next) >= 0)
  63441. return false;
  63442. p = p.prevZ;
  63443. }
  63444. return true;
  63445. }
  63446. // go through all polygon nodes and cure small local self-intersections
  63447. function cureLocalIntersections(start, triangles, dim) {
  63448. var p = start;
  63449. do {
  63450. var a = p.prev, b = p.next.next;
  63451. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63452. triangles.push(a.i / dim);
  63453. triangles.push(p.i / dim);
  63454. triangles.push(b.i / dim);
  63455. // remove two nodes involved
  63456. removeNode(p);
  63457. removeNode(p.next);
  63458. p = start = b;
  63459. }
  63460. p = p.next;
  63461. } while (p !== start);
  63462. return p;
  63463. }
  63464. // try splitting polygon into two and triangulate them independently
  63465. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63466. // look for a valid diagonal that divides the polygon into two
  63467. var a = start;
  63468. do {
  63469. var b = a.next.next;
  63470. while (b !== a.prev) {
  63471. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63472. // split the polygon in two by the diagonal
  63473. var c = splitPolygon(a, b);
  63474. // filter colinear points around the cuts
  63475. a = filterPoints(a, a.next);
  63476. c = filterPoints(c, c.next);
  63477. // run earcut on each half
  63478. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63479. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63480. return;
  63481. }
  63482. b = b.next;
  63483. }
  63484. a = a.next;
  63485. } while (a !== start);
  63486. }
  63487. // link every hole into the outer loop, producing a single-ring polygon without holes
  63488. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63489. var queue = [], i, len, start, end, list;
  63490. for (i = 0, len = holeIndices.length; i < len; i++) {
  63491. start = holeIndices[i] * dim;
  63492. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63493. list = linkedList(data, start, end, dim, false);
  63494. if (list === list.next)
  63495. list.steiner = true;
  63496. queue.push(getLeftmost(list));
  63497. }
  63498. queue.sort(compareX);
  63499. // process holes from left to right
  63500. for (i = 0; i < queue.length; i++) {
  63501. eliminateHole(queue[i], outerNode);
  63502. outerNode = filterPoints(outerNode, outerNode.next);
  63503. }
  63504. return outerNode;
  63505. }
  63506. function compareX(a, b) {
  63507. return a.x - b.x;
  63508. }
  63509. // find a bridge between vertices that connects hole with an outer ring and and link it
  63510. function eliminateHole(hole, outerNode) {
  63511. outerNode = findHoleBridge(hole, outerNode);
  63512. if (outerNode) {
  63513. var b = splitPolygon(outerNode, hole);
  63514. filterPoints(b, b.next);
  63515. }
  63516. }
  63517. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63518. function findHoleBridge(hole, outerNode) {
  63519. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63520. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63521. // segment's endpoint with lesser x will be potential connection point
  63522. do {
  63523. if (hy <= p.y && hy >= p.next.y) {
  63524. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63525. if (x <= hx && x > qx) {
  63526. qx = x;
  63527. if (x === hx) {
  63528. if (hy === p.y)
  63529. return p;
  63530. if (hy === p.next.y)
  63531. return p.next;
  63532. }
  63533. m = p.x < p.next.x ? p : p.next;
  63534. }
  63535. }
  63536. p = p.next;
  63537. } while (p !== outerNode);
  63538. if (!m)
  63539. return null;
  63540. if (hx === qx)
  63541. return m.prev; // hole touches outer segment; pick lower endpoint
  63542. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63543. // if there are no points found, we have a valid connection;
  63544. // otherwise choose the point of the minimum angle with the ray as connection point
  63545. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63546. p = m.next;
  63547. while (p !== stop) {
  63548. if (hx >= p.x &&
  63549. p.x >= mx &&
  63550. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63551. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63552. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63553. m = p;
  63554. tanMin = tan;
  63555. }
  63556. }
  63557. p = p.next;
  63558. }
  63559. return m;
  63560. }
  63561. // interlink polygon nodes in z-order
  63562. function indexCurve(start, minX, minY, size) {
  63563. var p = start;
  63564. do {
  63565. if (p.z === null)
  63566. p.z = zOrder(p.x, p.y, minX, minY, size);
  63567. p.prevZ = p.prev;
  63568. p.nextZ = p.next;
  63569. p = p.next;
  63570. } while (p !== start);
  63571. p.prevZ.nextZ = null;
  63572. p.prevZ = null;
  63573. sortLinked(p);
  63574. }
  63575. // Simon Tatham's linked list merge sort algorithm
  63576. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63577. function sortLinked(list) {
  63578. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63579. do {
  63580. p = list;
  63581. list = null;
  63582. tail = null;
  63583. numMerges = 0;
  63584. while (p) {
  63585. numMerges++;
  63586. q = p;
  63587. pSize = 0;
  63588. for (i = 0; i < inSize; i++) {
  63589. pSize++;
  63590. q = q.nextZ;
  63591. if (!q)
  63592. break;
  63593. }
  63594. qSize = inSize;
  63595. while (pSize > 0 || (qSize > 0 && q)) {
  63596. if (pSize === 0) {
  63597. e = q;
  63598. q = q.nextZ;
  63599. qSize--;
  63600. }
  63601. else if (qSize === 0 || !q) {
  63602. e = p;
  63603. p = p.nextZ;
  63604. pSize--;
  63605. }
  63606. else if (p.z <= q.z) {
  63607. e = p;
  63608. p = p.nextZ;
  63609. pSize--;
  63610. }
  63611. else {
  63612. e = q;
  63613. q = q.nextZ;
  63614. qSize--;
  63615. }
  63616. if (tail)
  63617. tail.nextZ = e;
  63618. else
  63619. list = e;
  63620. e.prevZ = tail;
  63621. tail = e;
  63622. }
  63623. p = q;
  63624. }
  63625. tail.nextZ = null;
  63626. inSize *= 2;
  63627. } while (numMerges > 1);
  63628. return list;
  63629. }
  63630. // z-order of a point given coords and size of the data bounding box
  63631. function zOrder(x, y, minX, minY, size) {
  63632. // coords are transformed into non-negative 15-bit integer range
  63633. x = 32767 * (x - minX) / size;
  63634. y = 32767 * (y - minY) / size;
  63635. x = (x | (x << 8)) & 0x00FF00FF;
  63636. x = (x | (x << 4)) & 0x0F0F0F0F;
  63637. x = (x | (x << 2)) & 0x33333333;
  63638. x = (x | (x << 1)) & 0x55555555;
  63639. y = (y | (y << 8)) & 0x00FF00FF;
  63640. y = (y | (y << 4)) & 0x0F0F0F0F;
  63641. y = (y | (y << 2)) & 0x33333333;
  63642. y = (y | (y << 1)) & 0x55555555;
  63643. return x | (y << 1);
  63644. }
  63645. // find the leftmost node of a polygon ring
  63646. function getLeftmost(start) {
  63647. var p = start, leftmost = start;
  63648. do {
  63649. if (p.x < leftmost.x)
  63650. leftmost = p;
  63651. p = p.next;
  63652. } while (p !== start);
  63653. return leftmost;
  63654. }
  63655. // check if a point lies within a convex triangle
  63656. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63657. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63658. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63659. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63660. }
  63661. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63662. function isValidDiagonal(a, b) {
  63663. return a.next.i !== b.i &&
  63664. a.prev.i !== b.i &&
  63665. !intersectsPolygon(a, b) &&
  63666. locallyInside(a, b) &&
  63667. locallyInside(b, a) &&
  63668. middleInside(a, b);
  63669. }
  63670. // signed area of a triangle
  63671. function area(p, q, r) {
  63672. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63673. }
  63674. // check if two points are equal
  63675. function equals(p1, p2) {
  63676. return p1.x === p2.x && p1.y === p2.y;
  63677. }
  63678. // check if two segments intersect
  63679. function intersects(p1, q1, p2, q2) {
  63680. if ((equals(p1, q1) && equals(p2, q2)) ||
  63681. (equals(p1, q2) && equals(p2, q1)))
  63682. return true;
  63683. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63684. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63685. }
  63686. // check if a polygon diagonal intersects any polygon segments
  63687. function intersectsPolygon(a, b) {
  63688. var p = a;
  63689. do {
  63690. if (p.i !== a.i &&
  63691. p.next.i !== a.i &&
  63692. p.i !== b.i &&
  63693. p.next.i !== b.i &&
  63694. intersects(p, p.next, a, b))
  63695. return true;
  63696. p = p.next;
  63697. } while (p !== a);
  63698. return false;
  63699. }
  63700. // check if a polygon diagonal is locally inside the polygon
  63701. function locallyInside(a, b) {
  63702. return area(a.prev, a, a.next) < 0
  63703. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63704. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63705. }
  63706. // check if the middle point of a polygon diagonal is inside the polygon
  63707. function middleInside(a, b) {
  63708. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63709. do {
  63710. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63711. inside = !inside;
  63712. p = p.next;
  63713. } while (p !== a);
  63714. return inside;
  63715. }
  63716. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63717. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63718. function splitPolygon(a, b) {
  63719. 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;
  63720. a.next = b;
  63721. b.prev = a;
  63722. a2.next = an;
  63723. an.prev = a2;
  63724. b2.next = a2;
  63725. a2.prev = b2;
  63726. bp.next = b2;
  63727. b2.prev = bp;
  63728. return b2;
  63729. }
  63730. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63731. function insertNode(i, x, y, last) {
  63732. var p = new Node(i, x, y);
  63733. if (!last) {
  63734. p.prev = p;
  63735. p.next = p;
  63736. }
  63737. else {
  63738. p.next = last.next;
  63739. p.prev = last;
  63740. last.next.prev = p;
  63741. last.next = p;
  63742. }
  63743. return p;
  63744. }
  63745. function removeNode(p) {
  63746. p.next.prev = p.prev;
  63747. p.prev.next = p.next;
  63748. if (p.prevZ)
  63749. p.prevZ.nextZ = p.nextZ;
  63750. if (p.nextZ)
  63751. p.nextZ.prevZ = p.prevZ;
  63752. }
  63753. /**
  63754. * return a percentage difference between the polygon area and its triangulation area;
  63755. * used to verify correctness of triangulation
  63756. */
  63757. function deviation(data, holeIndices, dim, triangles) {
  63758. var hasHoles = holeIndices && holeIndices.length;
  63759. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63760. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63761. if (hasHoles) {
  63762. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63763. var start = holeIndices[i] * dim;
  63764. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63765. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63766. }
  63767. }
  63768. var trianglesArea = 0;
  63769. for (i = 0; i < triangles.length; i += 3) {
  63770. var a = triangles[i] * dim;
  63771. var b = triangles[i + 1] * dim;
  63772. var c = triangles[i + 2] * dim;
  63773. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63774. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63775. }
  63776. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63777. }
  63778. Earcut.deviation = deviation;
  63779. ;
  63780. function signedArea(data, start, end, dim) {
  63781. var sum = 0;
  63782. for (var i = start, j = end - dim; i < end; i += dim) {
  63783. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63784. j = i;
  63785. }
  63786. return sum;
  63787. }
  63788. /**
  63789. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63790. */
  63791. function flatten(data) {
  63792. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63793. for (var i = 0; i < data.length; i++) {
  63794. for (var j = 0; j < data[i].length; j++) {
  63795. for (var d = 0; d < dim; d++)
  63796. result.vertices.push(data[i][j][d]);
  63797. }
  63798. if (i > 0) {
  63799. holeIndex += data[i - 1].length;
  63800. result.holes.push(holeIndex);
  63801. }
  63802. }
  63803. return result;
  63804. }
  63805. Earcut.flatten = flatten;
  63806. ;
  63807. })(Earcut || (Earcut = {}));
  63808. //# sourceMappingURL=babylon.earcut.js.map
  63809. var BABYLON;
  63810. (function (BABYLON) {
  63811. var IndexedVector2 = /** @class */ (function (_super) {
  63812. __extends(IndexedVector2, _super);
  63813. function IndexedVector2(original, index) {
  63814. var _this = _super.call(this, original.x, original.y) || this;
  63815. _this.index = index;
  63816. return _this;
  63817. }
  63818. return IndexedVector2;
  63819. }(BABYLON.Vector2));
  63820. var PolygonPoints = /** @class */ (function () {
  63821. function PolygonPoints() {
  63822. this.elements = new Array();
  63823. }
  63824. PolygonPoints.prototype.add = function (originalPoints) {
  63825. var _this = this;
  63826. var result = new Array();
  63827. originalPoints.forEach(function (point) {
  63828. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63829. var newPoint = new IndexedVector2(point, _this.elements.length);
  63830. result.push(newPoint);
  63831. _this.elements.push(newPoint);
  63832. }
  63833. });
  63834. return result;
  63835. };
  63836. PolygonPoints.prototype.computeBounds = function () {
  63837. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63838. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63839. this.elements.forEach(function (point) {
  63840. // x
  63841. if (point.x < lmin.x) {
  63842. lmin.x = point.x;
  63843. }
  63844. else if (point.x > lmax.x) {
  63845. lmax.x = point.x;
  63846. }
  63847. // y
  63848. if (point.y < lmin.y) {
  63849. lmin.y = point.y;
  63850. }
  63851. else if (point.y > lmax.y) {
  63852. lmax.y = point.y;
  63853. }
  63854. });
  63855. return {
  63856. min: lmin,
  63857. max: lmax,
  63858. width: lmax.x - lmin.x,
  63859. height: lmax.y - lmin.y
  63860. };
  63861. };
  63862. return PolygonPoints;
  63863. }());
  63864. var Polygon = /** @class */ (function () {
  63865. function Polygon() {
  63866. }
  63867. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63868. return [
  63869. new BABYLON.Vector2(xmin, ymin),
  63870. new BABYLON.Vector2(xmax, ymin),
  63871. new BABYLON.Vector2(xmax, ymax),
  63872. new BABYLON.Vector2(xmin, ymax)
  63873. ];
  63874. };
  63875. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63876. if (cx === void 0) { cx = 0; }
  63877. if (cy === void 0) { cy = 0; }
  63878. if (numberOfSides === void 0) { numberOfSides = 32; }
  63879. var result = new Array();
  63880. var angle = 0;
  63881. var increment = (Math.PI * 2) / numberOfSides;
  63882. for (var i = 0; i < numberOfSides; i++) {
  63883. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63884. angle -= increment;
  63885. }
  63886. return result;
  63887. };
  63888. Polygon.Parse = function (input) {
  63889. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63890. var i, result = [];
  63891. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63892. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63893. }
  63894. return result;
  63895. };
  63896. Polygon.StartingAt = function (x, y) {
  63897. return BABYLON.Path2.StartingAt(x, y);
  63898. };
  63899. return Polygon;
  63900. }());
  63901. BABYLON.Polygon = Polygon;
  63902. var PolygonMeshBuilder = /** @class */ (function () {
  63903. function PolygonMeshBuilder(name, contours, scene) {
  63904. this._points = new PolygonPoints();
  63905. this._outlinepoints = new PolygonPoints();
  63906. this._holes = new Array();
  63907. this._epoints = new Array();
  63908. this._eholes = new Array();
  63909. this._name = name;
  63910. this._scene = scene;
  63911. var points;
  63912. if (contours instanceof BABYLON.Path2) {
  63913. points = contours.getPoints();
  63914. }
  63915. else {
  63916. points = contours;
  63917. }
  63918. this._addToepoint(points);
  63919. this._points.add(points);
  63920. this._outlinepoints.add(points);
  63921. }
  63922. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63923. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63924. var p = points_1[_i];
  63925. this._epoints.push(p.x, p.y);
  63926. }
  63927. };
  63928. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63929. this._points.add(hole);
  63930. var holepoints = new PolygonPoints();
  63931. holepoints.add(hole);
  63932. this._holes.push(holepoints);
  63933. this._eholes.push(this._epoints.length / 2);
  63934. this._addToepoint(hole);
  63935. return this;
  63936. };
  63937. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63938. var _this = this;
  63939. if (updatable === void 0) { updatable = false; }
  63940. if (depth === void 0) { depth = 0; }
  63941. var result = new BABYLON.Mesh(this._name, this._scene);
  63942. var normals = new Array();
  63943. var positions = new Array();
  63944. var uvs = new Array();
  63945. var bounds = this._points.computeBounds();
  63946. this._points.elements.forEach(function (p) {
  63947. normals.push(0, 1.0, 0);
  63948. positions.push(p.x, 0, p.y);
  63949. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63950. });
  63951. var indices = new Array();
  63952. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63953. for (var i = 0; i < res.length; i++) {
  63954. indices.push(res[i]);
  63955. }
  63956. if (depth > 0) {
  63957. var positionscount = (positions.length / 3); //get the current pointcount
  63958. this._points.elements.forEach(function (p) {
  63959. normals.push(0, -1.0, 0);
  63960. positions.push(p.x, -depth, p.y);
  63961. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63962. });
  63963. var totalCount = indices.length;
  63964. for (var i = 0; i < totalCount; i += 3) {
  63965. var i0 = indices[i + 0];
  63966. var i1 = indices[i + 1];
  63967. var i2 = indices[i + 2];
  63968. indices.push(i2 + positionscount);
  63969. indices.push(i1 + positionscount);
  63970. indices.push(i0 + positionscount);
  63971. }
  63972. //Add the sides
  63973. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63974. this._holes.forEach(function (hole) {
  63975. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63976. });
  63977. }
  63978. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63979. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63980. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63981. result.setIndices(indices);
  63982. return result;
  63983. };
  63984. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63985. var StartIndex = positions.length / 3;
  63986. var ulength = 0;
  63987. for (var i = 0; i < points.elements.length; i++) {
  63988. var p = points.elements[i];
  63989. var p1;
  63990. if ((i + 1) > points.elements.length - 1) {
  63991. p1 = points.elements[0];
  63992. }
  63993. else {
  63994. p1 = points.elements[i + 1];
  63995. }
  63996. positions.push(p.x, 0, p.y);
  63997. positions.push(p.x, -depth, p.y);
  63998. positions.push(p1.x, 0, p1.y);
  63999. positions.push(p1.x, -depth, p1.y);
  64000. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64001. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64002. var v3 = v2.subtract(v1);
  64003. var v4 = new BABYLON.Vector3(0, 1, 0);
  64004. var vn = BABYLON.Vector3.Cross(v3, v4);
  64005. vn = vn.normalize();
  64006. uvs.push(ulength / bounds.width, 0);
  64007. uvs.push(ulength / bounds.width, 1);
  64008. ulength += v3.length();
  64009. uvs.push((ulength / bounds.width), 0);
  64010. uvs.push((ulength / bounds.width), 1);
  64011. if (!flip) {
  64012. normals.push(-vn.x, -vn.y, -vn.z);
  64013. normals.push(-vn.x, -vn.y, -vn.z);
  64014. normals.push(-vn.x, -vn.y, -vn.z);
  64015. normals.push(-vn.x, -vn.y, -vn.z);
  64016. indices.push(StartIndex);
  64017. indices.push(StartIndex + 1);
  64018. indices.push(StartIndex + 2);
  64019. indices.push(StartIndex + 1);
  64020. indices.push(StartIndex + 3);
  64021. indices.push(StartIndex + 2);
  64022. }
  64023. else {
  64024. normals.push(vn.x, vn.y, vn.z);
  64025. normals.push(vn.x, vn.y, vn.z);
  64026. normals.push(vn.x, vn.y, vn.z);
  64027. normals.push(vn.x, vn.y, vn.z);
  64028. indices.push(StartIndex);
  64029. indices.push(StartIndex + 2);
  64030. indices.push(StartIndex + 1);
  64031. indices.push(StartIndex + 1);
  64032. indices.push(StartIndex + 2);
  64033. indices.push(StartIndex + 3);
  64034. }
  64035. StartIndex += 4;
  64036. }
  64037. ;
  64038. };
  64039. return PolygonMeshBuilder;
  64040. }());
  64041. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64042. })(BABYLON || (BABYLON = {}));
  64043. //# sourceMappingURL=babylon.polygonMesh.js.map
  64044. var BABYLON;
  64045. (function (BABYLON) {
  64046. // Unique ID when we import meshes from Babylon to CSG
  64047. var currentCSGMeshId = 0;
  64048. // # class Vertex
  64049. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64050. // one to provide additional features like texture coordinates and vertex
  64051. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64052. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64053. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64054. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64055. // is not used anywhere else.
  64056. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64057. var Vertex = /** @class */ (function () {
  64058. function Vertex(pos, normal, uv) {
  64059. this.pos = pos;
  64060. this.normal = normal;
  64061. this.uv = uv;
  64062. }
  64063. Vertex.prototype.clone = function () {
  64064. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64065. };
  64066. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64067. // orientation of a polygon is flipped.
  64068. Vertex.prototype.flip = function () {
  64069. this.normal = this.normal.scale(-1);
  64070. };
  64071. // Create a new vertex between this vertex and `other` by linearly
  64072. // interpolating all properties using a parameter of `t`. Subclasses should
  64073. // override this to interpolate additional properties.
  64074. Vertex.prototype.interpolate = function (other, t) {
  64075. 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));
  64076. };
  64077. return Vertex;
  64078. }());
  64079. // # class Plane
  64080. // Represents a plane in 3D space.
  64081. var Plane = /** @class */ (function () {
  64082. function Plane(normal, w) {
  64083. this.normal = normal;
  64084. this.w = w;
  64085. }
  64086. Plane.FromPoints = function (a, b, c) {
  64087. var v0 = c.subtract(a);
  64088. var v1 = b.subtract(a);
  64089. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64090. return null;
  64091. }
  64092. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64093. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64094. };
  64095. Plane.prototype.clone = function () {
  64096. return new Plane(this.normal.clone(), this.w);
  64097. };
  64098. Plane.prototype.flip = function () {
  64099. this.normal.scaleInPlace(-1);
  64100. this.w = -this.w;
  64101. };
  64102. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64103. // fragments in the appropriate lists. Coplanar polygons go into either
  64104. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64105. // respect to this plane. Polygons in front or in back of this plane go into
  64106. // either `front` or `back`.
  64107. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64108. var COPLANAR = 0;
  64109. var FRONT = 1;
  64110. var BACK = 2;
  64111. var SPANNING = 3;
  64112. // Classify each point as well as the entire polygon into one of the above
  64113. // four classes.
  64114. var polygonType = 0;
  64115. var types = [];
  64116. var i;
  64117. var t;
  64118. for (i = 0; i < polygon.vertices.length; i++) {
  64119. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64120. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64121. polygonType |= type;
  64122. types.push(type);
  64123. }
  64124. // Put the polygon in the correct list, splitting it when necessary.
  64125. switch (polygonType) {
  64126. case COPLANAR:
  64127. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64128. break;
  64129. case FRONT:
  64130. front.push(polygon);
  64131. break;
  64132. case BACK:
  64133. back.push(polygon);
  64134. break;
  64135. case SPANNING:
  64136. var f = [], b = [];
  64137. for (i = 0; i < polygon.vertices.length; i++) {
  64138. var j = (i + 1) % polygon.vertices.length;
  64139. var ti = types[i], tj = types[j];
  64140. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64141. if (ti !== BACK)
  64142. f.push(vi);
  64143. if (ti !== FRONT)
  64144. b.push(ti !== BACK ? vi.clone() : vi);
  64145. if ((ti | tj) === SPANNING) {
  64146. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64147. var v = vi.interpolate(vj, t);
  64148. f.push(v);
  64149. b.push(v.clone());
  64150. }
  64151. }
  64152. var poly;
  64153. if (f.length >= 3) {
  64154. poly = new Polygon(f, polygon.shared);
  64155. if (poly.plane)
  64156. front.push(poly);
  64157. }
  64158. if (b.length >= 3) {
  64159. poly = new Polygon(b, polygon.shared);
  64160. if (poly.plane)
  64161. back.push(poly);
  64162. }
  64163. break;
  64164. }
  64165. };
  64166. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64167. // point is on the plane.
  64168. Plane.EPSILON = 1e-5;
  64169. return Plane;
  64170. }());
  64171. // # class Polygon
  64172. // Represents a convex polygon. The vertices used to initialize a polygon must
  64173. // be coplanar and form a convex loop.
  64174. //
  64175. // Each convex polygon has a `shared` property, which is shared between all
  64176. // polygons that are clones of each other or were split from the same polygon.
  64177. // This can be used to define per-polygon properties (such as surface color).
  64178. var Polygon = /** @class */ (function () {
  64179. function Polygon(vertices, shared) {
  64180. this.vertices = vertices;
  64181. this.shared = shared;
  64182. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64183. }
  64184. Polygon.prototype.clone = function () {
  64185. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64186. return new Polygon(vertices, this.shared);
  64187. };
  64188. Polygon.prototype.flip = function () {
  64189. this.vertices.reverse().map(function (v) { v.flip(); });
  64190. this.plane.flip();
  64191. };
  64192. return Polygon;
  64193. }());
  64194. // # class Node
  64195. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64196. // by picking a polygon to split along. That polygon (and all other coplanar
  64197. // polygons) are added directly to that node and the other polygons are added to
  64198. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64199. // no distinction between internal and leaf nodes.
  64200. var Node = /** @class */ (function () {
  64201. function Node(polygons) {
  64202. this.plane = null;
  64203. this.front = null;
  64204. this.back = null;
  64205. this.polygons = new Array();
  64206. if (polygons) {
  64207. this.build(polygons);
  64208. }
  64209. }
  64210. Node.prototype.clone = function () {
  64211. var node = new Node();
  64212. node.plane = this.plane && this.plane.clone();
  64213. node.front = this.front && this.front.clone();
  64214. node.back = this.back && this.back.clone();
  64215. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64216. return node;
  64217. };
  64218. // Convert solid space to empty space and empty space to solid space.
  64219. Node.prototype.invert = function () {
  64220. for (var i = 0; i < this.polygons.length; i++) {
  64221. this.polygons[i].flip();
  64222. }
  64223. if (this.plane) {
  64224. this.plane.flip();
  64225. }
  64226. if (this.front) {
  64227. this.front.invert();
  64228. }
  64229. if (this.back) {
  64230. this.back.invert();
  64231. }
  64232. var temp = this.front;
  64233. this.front = this.back;
  64234. this.back = temp;
  64235. };
  64236. // Recursively remove all polygons in `polygons` that are inside this BSP
  64237. // tree.
  64238. Node.prototype.clipPolygons = function (polygons) {
  64239. if (!this.plane)
  64240. return polygons.slice();
  64241. var front = new Array(), back = new Array();
  64242. for (var i = 0; i < polygons.length; i++) {
  64243. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64244. }
  64245. if (this.front) {
  64246. front = this.front.clipPolygons(front);
  64247. }
  64248. if (this.back) {
  64249. back = this.back.clipPolygons(back);
  64250. }
  64251. else {
  64252. back = [];
  64253. }
  64254. return front.concat(back);
  64255. };
  64256. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64257. // `bsp`.
  64258. Node.prototype.clipTo = function (bsp) {
  64259. this.polygons = bsp.clipPolygons(this.polygons);
  64260. if (this.front)
  64261. this.front.clipTo(bsp);
  64262. if (this.back)
  64263. this.back.clipTo(bsp);
  64264. };
  64265. // Return a list of all polygons in this BSP tree.
  64266. Node.prototype.allPolygons = function () {
  64267. var polygons = this.polygons.slice();
  64268. if (this.front)
  64269. polygons = polygons.concat(this.front.allPolygons());
  64270. if (this.back)
  64271. polygons = polygons.concat(this.back.allPolygons());
  64272. return polygons;
  64273. };
  64274. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64275. // new polygons are filtered down to the bottom of the tree and become new
  64276. // nodes there. Each set of polygons is partitioned using the first polygon
  64277. // (no heuristic is used to pick a good split).
  64278. Node.prototype.build = function (polygons) {
  64279. if (!polygons.length)
  64280. return;
  64281. if (!this.plane)
  64282. this.plane = polygons[0].plane.clone();
  64283. var front = new Array(), back = new Array();
  64284. for (var i = 0; i < polygons.length; i++) {
  64285. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64286. }
  64287. if (front.length) {
  64288. if (!this.front)
  64289. this.front = new Node();
  64290. this.front.build(front);
  64291. }
  64292. if (back.length) {
  64293. if (!this.back)
  64294. this.back = new Node();
  64295. this.back.build(back);
  64296. }
  64297. };
  64298. return Node;
  64299. }());
  64300. var CSG = /** @class */ (function () {
  64301. function CSG() {
  64302. this.polygons = new Array();
  64303. }
  64304. // Convert BABYLON.Mesh to BABYLON.CSG
  64305. CSG.FromMesh = function (mesh) {
  64306. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64307. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64308. if (mesh instanceof BABYLON.Mesh) {
  64309. mesh.computeWorldMatrix(true);
  64310. matrix = mesh.getWorldMatrix();
  64311. meshPosition = mesh.position.clone();
  64312. meshRotation = mesh.rotation.clone();
  64313. if (mesh.rotationQuaternion) {
  64314. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64315. }
  64316. meshScaling = mesh.scaling.clone();
  64317. }
  64318. else {
  64319. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64320. }
  64321. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64322. var subMeshes = mesh.subMeshes;
  64323. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64324. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64325. vertices = [];
  64326. for (var j = 0; j < 3; j++) {
  64327. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64328. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64329. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64330. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64331. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64332. vertex = new Vertex(position, normal, uv);
  64333. vertices.push(vertex);
  64334. }
  64335. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64336. // To handle the case of degenerated triangle
  64337. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64338. if (polygon.plane)
  64339. polygons.push(polygon);
  64340. }
  64341. }
  64342. var csg = CSG.FromPolygons(polygons);
  64343. csg.matrix = matrix;
  64344. csg.position = meshPosition;
  64345. csg.rotation = meshRotation;
  64346. csg.scaling = meshScaling;
  64347. csg.rotationQuaternion = meshRotationQuaternion;
  64348. currentCSGMeshId++;
  64349. return csg;
  64350. };
  64351. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64352. CSG.FromPolygons = function (polygons) {
  64353. var csg = new CSG();
  64354. csg.polygons = polygons;
  64355. return csg;
  64356. };
  64357. CSG.prototype.clone = function () {
  64358. var csg = new CSG();
  64359. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64360. csg.copyTransformAttributes(this);
  64361. return csg;
  64362. };
  64363. CSG.prototype.union = function (csg) {
  64364. var a = new Node(this.clone().polygons);
  64365. var b = new Node(csg.clone().polygons);
  64366. a.clipTo(b);
  64367. b.clipTo(a);
  64368. b.invert();
  64369. b.clipTo(a);
  64370. b.invert();
  64371. a.build(b.allPolygons());
  64372. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64373. };
  64374. CSG.prototype.unionInPlace = function (csg) {
  64375. var a = new Node(this.polygons);
  64376. var b = new Node(csg.polygons);
  64377. a.clipTo(b);
  64378. b.clipTo(a);
  64379. b.invert();
  64380. b.clipTo(a);
  64381. b.invert();
  64382. a.build(b.allPolygons());
  64383. this.polygons = a.allPolygons();
  64384. };
  64385. CSG.prototype.subtract = function (csg) {
  64386. var a = new Node(this.clone().polygons);
  64387. var b = new Node(csg.clone().polygons);
  64388. a.invert();
  64389. a.clipTo(b);
  64390. b.clipTo(a);
  64391. b.invert();
  64392. b.clipTo(a);
  64393. b.invert();
  64394. a.build(b.allPolygons());
  64395. a.invert();
  64396. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64397. };
  64398. CSG.prototype.subtractInPlace = function (csg) {
  64399. var a = new Node(this.polygons);
  64400. var b = new Node(csg.polygons);
  64401. a.invert();
  64402. a.clipTo(b);
  64403. b.clipTo(a);
  64404. b.invert();
  64405. b.clipTo(a);
  64406. b.invert();
  64407. a.build(b.allPolygons());
  64408. a.invert();
  64409. this.polygons = a.allPolygons();
  64410. };
  64411. CSG.prototype.intersect = function (csg) {
  64412. var a = new Node(this.clone().polygons);
  64413. var b = new Node(csg.clone().polygons);
  64414. a.invert();
  64415. b.clipTo(a);
  64416. b.invert();
  64417. a.clipTo(b);
  64418. b.clipTo(a);
  64419. a.build(b.allPolygons());
  64420. a.invert();
  64421. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64422. };
  64423. CSG.prototype.intersectInPlace = function (csg) {
  64424. var a = new Node(this.polygons);
  64425. var b = new Node(csg.polygons);
  64426. a.invert();
  64427. b.clipTo(a);
  64428. b.invert();
  64429. a.clipTo(b);
  64430. b.clipTo(a);
  64431. a.build(b.allPolygons());
  64432. a.invert();
  64433. this.polygons = a.allPolygons();
  64434. };
  64435. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64436. // not modified.
  64437. CSG.prototype.inverse = function () {
  64438. var csg = this.clone();
  64439. csg.inverseInPlace();
  64440. return csg;
  64441. };
  64442. CSG.prototype.inverseInPlace = function () {
  64443. this.polygons.map(function (p) { p.flip(); });
  64444. };
  64445. // This is used to keep meshes transformations so they can be restored
  64446. // when we build back a Babylon Mesh
  64447. // NB : All CSG operations are performed in world coordinates
  64448. CSG.prototype.copyTransformAttributes = function (csg) {
  64449. this.matrix = csg.matrix;
  64450. this.position = csg.position;
  64451. this.rotation = csg.rotation;
  64452. this.scaling = csg.scaling;
  64453. this.rotationQuaternion = csg.rotationQuaternion;
  64454. return this;
  64455. };
  64456. // Build Raw mesh from CSG
  64457. // Coordinates here are in world space
  64458. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64459. var matrix = this.matrix.clone();
  64460. matrix.invert();
  64461. 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;
  64462. if (keepSubMeshes) {
  64463. // Sort Polygons, since subMeshes are indices range
  64464. polygons.sort(function (a, b) {
  64465. if (a.shared.meshId === b.shared.meshId) {
  64466. return a.shared.subMeshId - b.shared.subMeshId;
  64467. }
  64468. else {
  64469. return a.shared.meshId - b.shared.meshId;
  64470. }
  64471. });
  64472. }
  64473. for (var i = 0, il = polygons.length; i < il; i++) {
  64474. polygon = polygons[i];
  64475. // Building SubMeshes
  64476. if (!subMesh_dict[polygon.shared.meshId]) {
  64477. subMesh_dict[polygon.shared.meshId] = {};
  64478. }
  64479. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64480. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64481. indexStart: +Infinity,
  64482. indexEnd: -Infinity,
  64483. materialIndex: polygon.shared.materialIndex
  64484. };
  64485. }
  64486. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64487. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64488. polygonIndices[0] = 0;
  64489. polygonIndices[1] = j - 1;
  64490. polygonIndices[2] = j;
  64491. for (var k = 0; k < 3; k++) {
  64492. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64493. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64494. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64495. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64496. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64497. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64498. // Check if 2 points can be merged
  64499. if (!(typeof vertex_idx !== 'undefined' &&
  64500. normals[vertex_idx * 3] === localNormal.x &&
  64501. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64502. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64503. uvs[vertex_idx * 2] === uv.x &&
  64504. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64505. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64506. uvs.push(uv.x, uv.y);
  64507. normals.push(normal.x, normal.y, normal.z);
  64508. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64509. }
  64510. indices.push(vertex_idx);
  64511. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64512. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64513. currentIndex++;
  64514. }
  64515. }
  64516. }
  64517. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64518. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64519. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64520. mesh.setIndices(indices, null);
  64521. if (keepSubMeshes) {
  64522. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64523. var materialIndexOffset = 0, materialMaxIndex;
  64524. mesh.subMeshes = new Array();
  64525. for (var m in subMesh_dict) {
  64526. materialMaxIndex = -1;
  64527. for (var sm in subMesh_dict[m]) {
  64528. subMesh_obj = subMesh_dict[m][sm];
  64529. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64530. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64531. }
  64532. materialIndexOffset += ++materialMaxIndex;
  64533. }
  64534. }
  64535. return mesh;
  64536. };
  64537. // Build Mesh from CSG taking material and transforms into account
  64538. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64539. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64540. mesh.material = material;
  64541. mesh.position.copyFrom(this.position);
  64542. mesh.rotation.copyFrom(this.rotation);
  64543. if (this.rotationQuaternion) {
  64544. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64545. }
  64546. mesh.scaling.copyFrom(this.scaling);
  64547. mesh.computeWorldMatrix(true);
  64548. return mesh;
  64549. };
  64550. return CSG;
  64551. }());
  64552. BABYLON.CSG = CSG;
  64553. })(BABYLON || (BABYLON = {}));
  64554. //# sourceMappingURL=babylon.csg.js.map
  64555. var BABYLON;
  64556. (function (BABYLON) {
  64557. var LensFlare = /** @class */ (function () {
  64558. function LensFlare(size, position, color, imgUrl, system) {
  64559. this.size = size;
  64560. this.position = position;
  64561. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64562. this.color = color || new BABYLON.Color3(1, 1, 1);
  64563. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64564. this._system = system;
  64565. system.lensFlares.push(this);
  64566. }
  64567. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64568. return new LensFlare(size, position, color, imgUrl, system);
  64569. };
  64570. LensFlare.prototype.dispose = function () {
  64571. if (this.texture) {
  64572. this.texture.dispose();
  64573. }
  64574. // Remove from scene
  64575. var index = this._system.lensFlares.indexOf(this);
  64576. this._system.lensFlares.splice(index, 1);
  64577. };
  64578. ;
  64579. return LensFlare;
  64580. }());
  64581. BABYLON.LensFlare = LensFlare;
  64582. })(BABYLON || (BABYLON = {}));
  64583. //# sourceMappingURL=babylon.lensFlare.js.map
  64584. var BABYLON;
  64585. (function (BABYLON) {
  64586. var LensFlareSystem = /** @class */ (function () {
  64587. function LensFlareSystem(name, emitter, scene) {
  64588. this.name = name;
  64589. this.lensFlares = new Array();
  64590. this.borderLimit = 300;
  64591. this.viewportBorder = 0;
  64592. this.layerMask = 0x0FFFFFFF;
  64593. this._vertexBuffers = {};
  64594. this._isEnabled = true;
  64595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64596. this._emitter = emitter;
  64597. this.id = name;
  64598. scene.lensFlareSystems.push(this);
  64599. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64600. var engine = scene.getEngine();
  64601. // VBO
  64602. var vertices = [];
  64603. vertices.push(1, 1);
  64604. vertices.push(-1, 1);
  64605. vertices.push(-1, -1);
  64606. vertices.push(1, -1);
  64607. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64608. // Indices
  64609. var indices = [];
  64610. indices.push(0);
  64611. indices.push(1);
  64612. indices.push(2);
  64613. indices.push(0);
  64614. indices.push(2);
  64615. indices.push(3);
  64616. this._indexBuffer = engine.createIndexBuffer(indices);
  64617. // Effects
  64618. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64619. }
  64620. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64621. get: function () {
  64622. return this._isEnabled;
  64623. },
  64624. set: function (value) {
  64625. this._isEnabled = value;
  64626. },
  64627. enumerable: true,
  64628. configurable: true
  64629. });
  64630. LensFlareSystem.prototype.getScene = function () {
  64631. return this._scene;
  64632. };
  64633. LensFlareSystem.prototype.getEmitter = function () {
  64634. return this._emitter;
  64635. };
  64636. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64637. this._emitter = newEmitter;
  64638. };
  64639. LensFlareSystem.prototype.getEmitterPosition = function () {
  64640. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64641. };
  64642. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64643. var position = this.getEmitterPosition();
  64644. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64645. this._positionX = position.x;
  64646. this._positionY = position.y;
  64647. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64648. if (this.viewportBorder > 0) {
  64649. globalViewport.x -= this.viewportBorder;
  64650. globalViewport.y -= this.viewportBorder;
  64651. globalViewport.width += this.viewportBorder * 2;
  64652. globalViewport.height += this.viewportBorder * 2;
  64653. position.x += this.viewportBorder;
  64654. position.y += this.viewportBorder;
  64655. this._positionX += this.viewportBorder;
  64656. this._positionY += this.viewportBorder;
  64657. }
  64658. if (position.z > 0) {
  64659. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64660. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64661. return true;
  64662. }
  64663. return true;
  64664. }
  64665. return false;
  64666. };
  64667. LensFlareSystem.prototype._isVisible = function () {
  64668. if (!this._isEnabled || !this._scene.activeCamera) {
  64669. return false;
  64670. }
  64671. var emitterPosition = this.getEmitterPosition();
  64672. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64673. var distance = direction.length();
  64674. direction.normalize();
  64675. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64676. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64677. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64678. };
  64679. LensFlareSystem.prototype.render = function () {
  64680. if (!this._effect.isReady() || !this._scene.activeCamera)
  64681. return false;
  64682. var engine = this._scene.getEngine();
  64683. var viewport = this._scene.activeCamera.viewport;
  64684. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64685. // Position
  64686. if (!this.computeEffectivePosition(globalViewport)) {
  64687. return false;
  64688. }
  64689. // Visibility
  64690. if (!this._isVisible()) {
  64691. return false;
  64692. }
  64693. // Intensity
  64694. var awayX;
  64695. var awayY;
  64696. if (this._positionX < this.borderLimit + globalViewport.x) {
  64697. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64698. }
  64699. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64700. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64701. }
  64702. else {
  64703. awayX = 0;
  64704. }
  64705. if (this._positionY < this.borderLimit + globalViewport.y) {
  64706. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64707. }
  64708. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64709. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64710. }
  64711. else {
  64712. awayY = 0;
  64713. }
  64714. var away = (awayX > awayY) ? awayX : awayY;
  64715. away -= this.viewportBorder;
  64716. if (away > this.borderLimit) {
  64717. away = this.borderLimit;
  64718. }
  64719. var intensity = 1.0 - (away / this.borderLimit);
  64720. if (intensity < 0) {
  64721. return false;
  64722. }
  64723. if (intensity > 1.0) {
  64724. intensity = 1.0;
  64725. }
  64726. if (this.viewportBorder > 0) {
  64727. globalViewport.x += this.viewportBorder;
  64728. globalViewport.y += this.viewportBorder;
  64729. globalViewport.width -= this.viewportBorder * 2;
  64730. globalViewport.height -= this.viewportBorder * 2;
  64731. this._positionX -= this.viewportBorder;
  64732. this._positionY -= this.viewportBorder;
  64733. }
  64734. // Position
  64735. var centerX = globalViewport.x + globalViewport.width / 2;
  64736. var centerY = globalViewport.y + globalViewport.height / 2;
  64737. var distX = centerX - this._positionX;
  64738. var distY = centerY - this._positionY;
  64739. // Effects
  64740. engine.enableEffect(this._effect);
  64741. engine.setState(false);
  64742. engine.setDepthBuffer(false);
  64743. // VBOs
  64744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64745. // Flares
  64746. for (var index = 0; index < this.lensFlares.length; index++) {
  64747. var flare = this.lensFlares[index];
  64748. engine.setAlphaMode(flare.alphaMode);
  64749. var x = centerX - (distX * flare.position);
  64750. var y = centerY - (distY * flare.position);
  64751. var cw = flare.size;
  64752. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64753. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64754. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64755. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64756. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64757. // Texture
  64758. this._effect.setTexture("textureSampler", flare.texture);
  64759. // Color
  64760. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64761. // Draw order
  64762. engine.draw(true, 0, 6);
  64763. }
  64764. engine.setDepthBuffer(true);
  64765. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64766. return true;
  64767. };
  64768. LensFlareSystem.prototype.dispose = function () {
  64769. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64770. if (vertexBuffer) {
  64771. vertexBuffer.dispose();
  64772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64773. }
  64774. if (this._indexBuffer) {
  64775. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64776. this._indexBuffer = null;
  64777. }
  64778. while (this.lensFlares.length) {
  64779. this.lensFlares[0].dispose();
  64780. }
  64781. // Remove from scene
  64782. var index = this._scene.lensFlareSystems.indexOf(this);
  64783. this._scene.lensFlareSystems.splice(index, 1);
  64784. };
  64785. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64786. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64787. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64788. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64789. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64790. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64791. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64792. var parsedFlare = parsedLensFlareSystem.flares[index];
  64793. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64794. }
  64795. return lensFlareSystem;
  64796. };
  64797. LensFlareSystem.prototype.serialize = function () {
  64798. var serializationObject = {};
  64799. serializationObject.id = this.id;
  64800. serializationObject.name = this.name;
  64801. serializationObject.emitterId = this.getEmitter().id;
  64802. serializationObject.borderLimit = this.borderLimit;
  64803. serializationObject.flares = [];
  64804. for (var index = 0; index < this.lensFlares.length; index++) {
  64805. var flare = this.lensFlares[index];
  64806. serializationObject.flares.push({
  64807. size: flare.size,
  64808. position: flare.position,
  64809. color: flare.color.asArray(),
  64810. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64811. });
  64812. }
  64813. return serializationObject;
  64814. };
  64815. return LensFlareSystem;
  64816. }());
  64817. BABYLON.LensFlareSystem = LensFlareSystem;
  64818. })(BABYLON || (BABYLON = {}));
  64819. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64820. var BABYLON;
  64821. (function (BABYLON) {
  64822. /**
  64823. * This is a holder class for the physics joint created by the physics plugin.
  64824. * It holds a set of functions to control the underlying joint.
  64825. */
  64826. var PhysicsJoint = /** @class */ (function () {
  64827. function PhysicsJoint(type, jointData) {
  64828. this.type = type;
  64829. this.jointData = jointData;
  64830. jointData.nativeParams = jointData.nativeParams || {};
  64831. }
  64832. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64833. get: function () {
  64834. return this._physicsJoint;
  64835. },
  64836. set: function (newJoint) {
  64837. if (this._physicsJoint) {
  64838. //remove from the wolrd
  64839. }
  64840. this._physicsJoint = newJoint;
  64841. },
  64842. enumerable: true,
  64843. configurable: true
  64844. });
  64845. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64846. set: function (physicsPlugin) {
  64847. this._physicsPlugin = physicsPlugin;
  64848. },
  64849. enumerable: true,
  64850. configurable: true
  64851. });
  64852. /**
  64853. * Execute a function that is physics-plugin specific.
  64854. * @param {Function} func the function that will be executed.
  64855. * It accepts two parameters: the physics world and the physics joint.
  64856. */
  64857. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64858. func(this._physicsPlugin.world, this._physicsJoint);
  64859. };
  64860. //TODO check if the native joints are the same
  64861. //Joint Types
  64862. PhysicsJoint.DistanceJoint = 0;
  64863. PhysicsJoint.HingeJoint = 1;
  64864. PhysicsJoint.BallAndSocketJoint = 2;
  64865. PhysicsJoint.WheelJoint = 3;
  64866. PhysicsJoint.SliderJoint = 4;
  64867. //OIMO
  64868. PhysicsJoint.PrismaticJoint = 5;
  64869. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64870. PhysicsJoint.UniversalJoint = 6;
  64871. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64872. //Cannon
  64873. //Similar to a Ball-Joint. Different in params
  64874. PhysicsJoint.PointToPointJoint = 8;
  64875. //Cannon only at the moment
  64876. PhysicsJoint.SpringJoint = 9;
  64877. PhysicsJoint.LockJoint = 10;
  64878. return PhysicsJoint;
  64879. }());
  64880. BABYLON.PhysicsJoint = PhysicsJoint;
  64881. /**
  64882. * A class representing a physics distance joint.
  64883. */
  64884. var DistanceJoint = /** @class */ (function (_super) {
  64885. __extends(DistanceJoint, _super);
  64886. function DistanceJoint(jointData) {
  64887. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64888. }
  64889. /**
  64890. * Update the predefined distance.
  64891. */
  64892. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64893. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64894. };
  64895. return DistanceJoint;
  64896. }(PhysicsJoint));
  64897. BABYLON.DistanceJoint = DistanceJoint;
  64898. var MotorEnabledJoint = /** @class */ (function (_super) {
  64899. __extends(MotorEnabledJoint, _super);
  64900. function MotorEnabledJoint(type, jointData) {
  64901. return _super.call(this, type, jointData) || this;
  64902. }
  64903. /**
  64904. * Set the motor values.
  64905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64906. * @param {number} force the force to apply
  64907. * @param {number} maxForce max force for this motor.
  64908. */
  64909. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64910. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64911. };
  64912. /**
  64913. * Set the motor's limits.
  64914. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64915. */
  64916. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64917. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64918. };
  64919. return MotorEnabledJoint;
  64920. }(PhysicsJoint));
  64921. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64922. /**
  64923. * This class represents a single hinge physics joint
  64924. */
  64925. var HingeJoint = /** @class */ (function (_super) {
  64926. __extends(HingeJoint, _super);
  64927. function HingeJoint(jointData) {
  64928. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64929. }
  64930. /**
  64931. * Set the motor values.
  64932. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64933. * @param {number} force the force to apply
  64934. * @param {number} maxForce max force for this motor.
  64935. */
  64936. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64937. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64938. };
  64939. /**
  64940. * Set the motor's limits.
  64941. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64942. */
  64943. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64944. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64945. };
  64946. return HingeJoint;
  64947. }(MotorEnabledJoint));
  64948. BABYLON.HingeJoint = HingeJoint;
  64949. /**
  64950. * This class represents a dual hinge physics joint (same as wheel joint)
  64951. */
  64952. var Hinge2Joint = /** @class */ (function (_super) {
  64953. __extends(Hinge2Joint, _super);
  64954. function Hinge2Joint(jointData) {
  64955. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64956. }
  64957. /**
  64958. * Set the motor values.
  64959. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64960. * @param {number} force the force to apply
  64961. * @param {number} maxForce max force for this motor.
  64962. * @param {motorIndex} the motor's index, 0 or 1.
  64963. */
  64964. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64965. if (motorIndex === void 0) { motorIndex = 0; }
  64966. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  64967. };
  64968. /**
  64969. * Set the motor limits.
  64970. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64971. * @param {number} upperLimit the upper limit
  64972. * @param {number} lowerLimit lower limit
  64973. * @param {motorIndex} the motor's index, 0 or 1.
  64974. */
  64975. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64976. if (motorIndex === void 0) { motorIndex = 0; }
  64977. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64978. };
  64979. return Hinge2Joint;
  64980. }(MotorEnabledJoint));
  64981. BABYLON.Hinge2Joint = Hinge2Joint;
  64982. })(BABYLON || (BABYLON = {}));
  64983. //# sourceMappingURL=babylon.physicsJoint.js.map
  64984. var BABYLON;
  64985. (function (BABYLON) {
  64986. var PhysicsImpostor = /** @class */ (function () {
  64987. function PhysicsImpostor(object, type, _options, _scene) {
  64988. if (_options === void 0) { _options = { mass: 0 }; }
  64989. var _this = this;
  64990. this.object = object;
  64991. this.type = type;
  64992. this._options = _options;
  64993. this._scene = _scene;
  64994. this._bodyUpdateRequired = false;
  64995. this._onBeforePhysicsStepCallbacks = new Array();
  64996. this._onAfterPhysicsStepCallbacks = new Array();
  64997. this._onPhysicsCollideCallbacks = [];
  64998. this._deltaPosition = BABYLON.Vector3.Zero();
  64999. this._isDisposed = false;
  65000. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  65001. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  65002. /**
  65003. * this function is executed by the physics engine.
  65004. */
  65005. this.beforeStep = function () {
  65006. if (!_this._physicsEngine) {
  65007. return;
  65008. }
  65009. if (_this._options.ignoreParent && _this.object.parent) {
  65010. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  65011. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  65012. }
  65013. else {
  65014. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  65015. }
  65016. //conjugate deltaRotation
  65017. if (_this.object.rotationQuaternion) {
  65018. if (_this._deltaRotationConjugated) {
  65019. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  65020. }
  65021. else {
  65022. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  65023. }
  65024. }
  65025. // Only if not disabled
  65026. if (!_this._options.disableBidirectionalTransformation) {
  65027. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  65028. }
  65029. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65030. func(_this);
  65031. });
  65032. };
  65033. /**
  65034. * this function is executed by the physics engine.
  65035. */
  65036. this.afterStep = function () {
  65037. if (!_this._physicsEngine) {
  65038. return;
  65039. }
  65040. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65041. func(_this);
  65042. });
  65043. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65044. if (_this._options.ignoreParent && _this.object.parent) {
  65045. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  65046. }
  65047. else {
  65048. _this.object.position.addInPlace(_this._deltaPosition);
  65049. }
  65050. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  65051. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  65052. }
  65053. };
  65054. /**
  65055. * Legacy collision detection event support
  65056. */
  65057. this.onCollideEvent = null;
  65058. //event and body object due to cannon's event-based architecture.
  65059. this.onCollide = function (e) {
  65060. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65061. return;
  65062. }
  65063. if (!_this._physicsEngine) {
  65064. return;
  65065. }
  65066. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65067. if (otherImpostor) {
  65068. // Legacy collision detection event support
  65069. if (_this.onCollideEvent) {
  65070. _this.onCollideEvent(_this, otherImpostor);
  65071. }
  65072. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65073. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65074. }).forEach(function (obj) {
  65075. obj.callback(_this, otherImpostor);
  65076. });
  65077. }
  65078. };
  65079. //sanity check!
  65080. if (!this.object) {
  65081. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65082. return;
  65083. }
  65084. //legacy support for old syntax.
  65085. if (!this._scene && object.getScene) {
  65086. this._scene = object.getScene();
  65087. }
  65088. if (!this._scene) {
  65089. return;
  65090. }
  65091. this._physicsEngine = this._scene.getPhysicsEngine();
  65092. if (!this._physicsEngine) {
  65093. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65094. }
  65095. else {
  65096. //set the object's quaternion, if not set
  65097. if (!this.object.rotationQuaternion) {
  65098. if (this.object.rotation) {
  65099. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65100. }
  65101. else {
  65102. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65103. }
  65104. }
  65105. //default options params
  65106. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65107. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65108. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65109. this._joints = [];
  65110. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65111. if (!this.object.parent || this._options.ignoreParent) {
  65112. this._init();
  65113. }
  65114. else if (this.object.parent.physicsImpostor) {
  65115. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65116. }
  65117. }
  65118. }
  65119. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65120. get: function () {
  65121. return this._isDisposed;
  65122. },
  65123. enumerable: true,
  65124. configurable: true
  65125. });
  65126. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65127. get: function () {
  65128. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65129. },
  65130. set: function (value) {
  65131. this.setMass(value);
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65137. get: function () {
  65138. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65139. },
  65140. set: function (value) {
  65141. if (!this._physicsEngine) {
  65142. return;
  65143. }
  65144. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65145. },
  65146. enumerable: true,
  65147. configurable: true
  65148. });
  65149. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65150. get: function () {
  65151. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65152. },
  65153. set: function (value) {
  65154. if (!this._physicsEngine) {
  65155. return;
  65156. }
  65157. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65158. },
  65159. enumerable: true,
  65160. configurable: true
  65161. });
  65162. /**
  65163. * This function will completly initialize this impostor.
  65164. * It will create a new body - but only if this mesh has no parent.
  65165. * If it has, this impostor will not be used other than to define the impostor
  65166. * of the child mesh.
  65167. */
  65168. PhysicsImpostor.prototype._init = function () {
  65169. if (!this._physicsEngine) {
  65170. return;
  65171. }
  65172. this._physicsEngine.removeImpostor(this);
  65173. this.physicsBody = null;
  65174. this._parent = this._parent || this._getPhysicsParent();
  65175. if (!this.parent || this._options.ignoreParent) {
  65176. this._physicsEngine.addImpostor(this);
  65177. }
  65178. };
  65179. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65180. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65181. var parentMesh = this.object.parent;
  65182. return parentMesh.physicsImpostor;
  65183. }
  65184. return null;
  65185. };
  65186. /**
  65187. * Should a new body be generated.
  65188. */
  65189. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65190. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65191. };
  65192. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65193. this.forceUpdate();
  65194. };
  65195. /**
  65196. * Force a regeneration of this or the parent's impostor's body.
  65197. * Use under cautious - This will remove all joints already implemented.
  65198. */
  65199. PhysicsImpostor.prototype.forceUpdate = function () {
  65200. this._init();
  65201. if (this.parent && !this._options.ignoreParent) {
  65202. this.parent.forceUpdate();
  65203. }
  65204. };
  65205. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65206. /*public get mesh(): AbstractMesh {
  65207. return this._mesh;
  65208. }*/
  65209. /**
  65210. * Gets the body that holds this impostor. Either its own, or its parent.
  65211. */
  65212. get: function () {
  65213. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65214. },
  65215. /**
  65216. * Set the physics body. Used mainly by the physics engine/plugin
  65217. */
  65218. set: function (physicsBody) {
  65219. if (this._physicsBody && this._physicsEngine) {
  65220. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65221. }
  65222. this._physicsBody = physicsBody;
  65223. this.resetUpdateFlags();
  65224. },
  65225. enumerable: true,
  65226. configurable: true
  65227. });
  65228. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65229. get: function () {
  65230. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65231. },
  65232. set: function (value) {
  65233. this._parent = value;
  65234. },
  65235. enumerable: true,
  65236. configurable: true
  65237. });
  65238. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65239. this._bodyUpdateRequired = false;
  65240. };
  65241. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65242. if (this.object.getBoundingInfo) {
  65243. var q = this.object.rotationQuaternion;
  65244. //reset rotation
  65245. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65246. //calculate the world matrix with no rotation
  65247. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65248. var boundingInfo = this.object.getBoundingInfo();
  65249. var size = void 0;
  65250. if (boundingInfo) {
  65251. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65252. }
  65253. else {
  65254. size = BABYLON.Vector3.Zero();
  65255. }
  65256. //bring back the rotation
  65257. this.object.rotationQuaternion = q;
  65258. //calculate the world matrix with the new rotation
  65259. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65260. return size;
  65261. }
  65262. else {
  65263. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65264. }
  65265. };
  65266. PhysicsImpostor.prototype.getObjectCenter = function () {
  65267. if (this.object.getBoundingInfo) {
  65268. var boundingInfo = this.object.getBoundingInfo();
  65269. if (!boundingInfo) {
  65270. return this.object.position;
  65271. }
  65272. return boundingInfo.boundingBox.centerWorld;
  65273. }
  65274. else {
  65275. return this.object.position;
  65276. }
  65277. };
  65278. /**
  65279. * Get a specific parametes from the options parameter.
  65280. */
  65281. PhysicsImpostor.prototype.getParam = function (paramName) {
  65282. return this._options[paramName];
  65283. };
  65284. /**
  65285. * Sets a specific parameter in the options given to the physics plugin
  65286. */
  65287. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65288. this._options[paramName] = value;
  65289. this._bodyUpdateRequired = true;
  65290. };
  65291. /**
  65292. * Specifically change the body's mass option. Won't recreate the physics body object
  65293. */
  65294. PhysicsImpostor.prototype.setMass = function (mass) {
  65295. if (this.getParam("mass") !== mass) {
  65296. this.setParam("mass", mass);
  65297. }
  65298. if (this._physicsEngine) {
  65299. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65300. }
  65301. };
  65302. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65304. };
  65305. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65306. if (this._physicsEngine) {
  65307. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65308. }
  65309. };
  65310. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65311. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65312. };
  65313. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65314. if (this._physicsEngine) {
  65315. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65316. }
  65317. };
  65318. /**
  65319. * Execute a function with the physics plugin native code.
  65320. * Provide a function the will have two variables - the world object and the physics body object.
  65321. */
  65322. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65323. if (this._physicsEngine) {
  65324. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65325. }
  65326. };
  65327. /**
  65328. * Register a function that will be executed before the physics world is stepping forward.
  65329. */
  65330. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65331. this._onBeforePhysicsStepCallbacks.push(func);
  65332. };
  65333. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65334. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65335. if (index > -1) {
  65336. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65337. }
  65338. else {
  65339. BABYLON.Tools.Warn("Function to remove was not found");
  65340. }
  65341. };
  65342. /**
  65343. * Register a function that will be executed after the physics step
  65344. */
  65345. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65346. this._onAfterPhysicsStepCallbacks.push(func);
  65347. };
  65348. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65349. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65350. if (index > -1) {
  65351. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65352. }
  65353. else {
  65354. BABYLON.Tools.Warn("Function to remove was not found");
  65355. }
  65356. };
  65357. /**
  65358. * register a function that will be executed when this impostor collides against a different body.
  65359. */
  65360. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65361. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65362. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65363. };
  65364. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65365. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65366. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65367. if (index > -1) {
  65368. this._onPhysicsCollideCallbacks.splice(index, 1);
  65369. }
  65370. else {
  65371. BABYLON.Tools.Warn("Function to remove was not found");
  65372. }
  65373. };
  65374. /**
  65375. * Apply a force
  65376. */
  65377. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65378. if (this._physicsEngine) {
  65379. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65380. }
  65381. return this;
  65382. };
  65383. /**
  65384. * Apply an impulse
  65385. */
  65386. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65387. if (this._physicsEngine) {
  65388. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65389. }
  65390. return this;
  65391. };
  65392. /**
  65393. * A help function to create a joint.
  65394. */
  65395. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65396. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65397. this.addJoint(otherImpostor, joint);
  65398. return this;
  65399. };
  65400. /**
  65401. * Add a joint to this impostor with a different impostor.
  65402. */
  65403. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65404. this._joints.push({
  65405. otherImpostor: otherImpostor,
  65406. joint: joint
  65407. });
  65408. if (this._physicsEngine) {
  65409. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65410. }
  65411. return this;
  65412. };
  65413. /**
  65414. * Will keep this body still, in a sleep mode.
  65415. */
  65416. PhysicsImpostor.prototype.sleep = function () {
  65417. if (this._physicsEngine) {
  65418. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65419. }
  65420. return this;
  65421. };
  65422. /**
  65423. * Wake the body up.
  65424. */
  65425. PhysicsImpostor.prototype.wakeUp = function () {
  65426. if (this._physicsEngine) {
  65427. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65428. }
  65429. return this;
  65430. };
  65431. PhysicsImpostor.prototype.clone = function (newObject) {
  65432. if (!newObject)
  65433. return null;
  65434. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65435. };
  65436. PhysicsImpostor.prototype.dispose = function () {
  65437. var _this = this;
  65438. //no dispose if no physics engine is available.
  65439. if (!this._physicsEngine) {
  65440. return;
  65441. }
  65442. this._joints.forEach(function (j) {
  65443. if (_this._physicsEngine) {
  65444. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65445. }
  65446. });
  65447. //dispose the physics body
  65448. this._physicsEngine.removeImpostor(this);
  65449. if (this.parent) {
  65450. this.parent.forceUpdate();
  65451. }
  65452. else {
  65453. /*this._object.getChildMeshes().forEach(function(mesh) {
  65454. if (mesh.physicsImpostor) {
  65455. if (disposeChildren) {
  65456. mesh.physicsImpostor.dispose();
  65457. mesh.physicsImpostor = null;
  65458. }
  65459. }
  65460. })*/
  65461. }
  65462. this._isDisposed = true;
  65463. };
  65464. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65465. this._deltaPosition.copyFrom(position);
  65466. };
  65467. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65468. if (!this._deltaRotation) {
  65469. this._deltaRotation = new BABYLON.Quaternion();
  65470. }
  65471. this._deltaRotation.copyFrom(rotation);
  65472. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65473. };
  65474. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65475. if (this._physicsEngine) {
  65476. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65477. }
  65478. return this;
  65479. };
  65480. PhysicsImpostor.prototype.getRadius = function () {
  65481. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65482. };
  65483. /**
  65484. * Sync a bone with this impostor
  65485. * @param bone The bone to sync to the impostor.
  65486. * @param boneMesh The mesh that the bone is influencing.
  65487. * @param jointPivot The pivot of the joint / bone in local space.
  65488. * @param distToJoint Optional distance from the impostor to the joint.
  65489. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65490. */
  65491. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65492. var tempVec = PhysicsImpostor._tmpVecs[0];
  65493. var mesh = this.object;
  65494. if (mesh.rotationQuaternion) {
  65495. if (adjustRotation) {
  65496. var tempQuat = PhysicsImpostor._tmpQuat;
  65497. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65498. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65499. }
  65500. else {
  65501. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65502. }
  65503. }
  65504. tempVec.x = 0;
  65505. tempVec.y = 0;
  65506. tempVec.z = 0;
  65507. if (jointPivot) {
  65508. tempVec.x = jointPivot.x;
  65509. tempVec.y = jointPivot.y;
  65510. tempVec.z = jointPivot.z;
  65511. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65512. if (distToJoint === undefined || distToJoint === null) {
  65513. distToJoint = jointPivot.length();
  65514. }
  65515. tempVec.x *= distToJoint;
  65516. tempVec.y *= distToJoint;
  65517. tempVec.z *= distToJoint;
  65518. }
  65519. if (bone.getParent()) {
  65520. tempVec.addInPlace(mesh.getAbsolutePosition());
  65521. bone.setAbsolutePosition(tempVec, boneMesh);
  65522. }
  65523. else {
  65524. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65525. boneMesh.position.x -= tempVec.x;
  65526. boneMesh.position.y -= tempVec.y;
  65527. boneMesh.position.z -= tempVec.z;
  65528. }
  65529. };
  65530. /**
  65531. * Sync impostor to a bone
  65532. * @param bone The bone that the impostor will be synced to.
  65533. * @param boneMesh The mesh that the bone is influencing.
  65534. * @param jointPivot The pivot of the joint / bone in local space.
  65535. * @param distToJoint Optional distance from the impostor to the joint.
  65536. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65537. * @param boneAxis Optional vector3 axis the bone is aligned with
  65538. */
  65539. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65540. var mesh = this.object;
  65541. if (mesh.rotationQuaternion) {
  65542. if (adjustRotation) {
  65543. var tempQuat = PhysicsImpostor._tmpQuat;
  65544. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65545. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65546. }
  65547. else {
  65548. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65549. }
  65550. }
  65551. var pos = PhysicsImpostor._tmpVecs[0];
  65552. var boneDir = PhysicsImpostor._tmpVecs[1];
  65553. if (!boneAxis) {
  65554. boneAxis = PhysicsImpostor._tmpVecs[2];
  65555. boneAxis.x = 0;
  65556. boneAxis.y = 1;
  65557. boneAxis.z = 0;
  65558. }
  65559. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65560. bone.getAbsolutePositionToRef(boneMesh, pos);
  65561. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65562. distToJoint = jointPivot.length();
  65563. }
  65564. if (distToJoint !== undefined && distToJoint !== null) {
  65565. pos.x += boneDir.x * distToJoint;
  65566. pos.y += boneDir.y * distToJoint;
  65567. pos.z += boneDir.z * distToJoint;
  65568. }
  65569. mesh.setAbsolutePosition(pos);
  65570. };
  65571. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65572. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65573. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65574. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65575. //Impostor types
  65576. PhysicsImpostor.NoImpostor = 0;
  65577. PhysicsImpostor.SphereImpostor = 1;
  65578. PhysicsImpostor.BoxImpostor = 2;
  65579. PhysicsImpostor.PlaneImpostor = 3;
  65580. PhysicsImpostor.MeshImpostor = 4;
  65581. PhysicsImpostor.CylinderImpostor = 7;
  65582. PhysicsImpostor.ParticleImpostor = 8;
  65583. PhysicsImpostor.HeightmapImpostor = 9;
  65584. return PhysicsImpostor;
  65585. }());
  65586. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65587. })(BABYLON || (BABYLON = {}));
  65588. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65589. var BABYLON;
  65590. (function (BABYLON) {
  65591. var PhysicsEngine = /** @class */ (function () {
  65592. function PhysicsEngine(gravity, _physicsPlugin) {
  65593. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65594. this._physicsPlugin = _physicsPlugin;
  65595. //new methods and parameters
  65596. this._impostors = [];
  65597. this._joints = [];
  65598. if (!this._physicsPlugin.isSupported()) {
  65599. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65600. + "Please make sure it is included.");
  65601. }
  65602. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65603. this.setGravity(gravity);
  65604. this.setTimeStep();
  65605. }
  65606. PhysicsEngine.prototype.setGravity = function (gravity) {
  65607. this.gravity = gravity;
  65608. this._physicsPlugin.setGravity(this.gravity);
  65609. };
  65610. /**
  65611. * Set the time step of the physics engine.
  65612. * default is 1/60.
  65613. * To slow it down, enter 1/600 for example.
  65614. * To speed it up, 1/30
  65615. * @param {number} newTimeStep the new timestep to apply to this world.
  65616. */
  65617. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65618. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65619. this._physicsPlugin.setTimeStep(newTimeStep);
  65620. };
  65621. /**
  65622. * Get the time step of the physics engine.
  65623. */
  65624. PhysicsEngine.prototype.getTimeStep = function () {
  65625. return this._physicsPlugin.getTimeStep();
  65626. };
  65627. PhysicsEngine.prototype.dispose = function () {
  65628. this._impostors.forEach(function (impostor) {
  65629. impostor.dispose();
  65630. });
  65631. this._physicsPlugin.dispose();
  65632. };
  65633. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65634. return this._physicsPlugin.name;
  65635. };
  65636. /**
  65637. * Adding a new impostor for the impostor tracking.
  65638. * This will be done by the impostor itself.
  65639. * @param {PhysicsImpostor} impostor the impostor to add
  65640. */
  65641. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65642. impostor.uniqueId = this._impostors.push(impostor);
  65643. //if no parent, generate the body
  65644. if (!impostor.parent) {
  65645. this._physicsPlugin.generatePhysicsBody(impostor);
  65646. }
  65647. };
  65648. /**
  65649. * Remove an impostor from the engine.
  65650. * This impostor and its mesh will not longer be updated by the physics engine.
  65651. * @param {PhysicsImpostor} impostor the impostor to remove
  65652. */
  65653. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65654. var index = this._impostors.indexOf(impostor);
  65655. if (index > -1) {
  65656. var removed = this._impostors.splice(index, 1);
  65657. //Is it needed?
  65658. if (removed.length) {
  65659. //this will also remove it from the world.
  65660. removed[0].physicsBody = null;
  65661. }
  65662. }
  65663. };
  65664. /**
  65665. * Add a joint to the physics engine
  65666. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65667. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65668. * @param {PhysicsJoint} the joint that will connect both impostors.
  65669. */
  65670. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65671. var impostorJoint = {
  65672. mainImpostor: mainImpostor,
  65673. connectedImpostor: connectedImpostor,
  65674. joint: joint
  65675. };
  65676. joint.physicsPlugin = this._physicsPlugin;
  65677. this._joints.push(impostorJoint);
  65678. this._physicsPlugin.generateJoint(impostorJoint);
  65679. };
  65680. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65681. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65682. return (impostorJoint.connectedImpostor === connectedImpostor
  65683. && impostorJoint.joint === joint
  65684. && impostorJoint.mainImpostor === mainImpostor);
  65685. });
  65686. if (matchingJoints.length) {
  65687. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65688. //TODO remove it from the list as well
  65689. }
  65690. };
  65691. /**
  65692. * Called by the scene. no need to call it.
  65693. */
  65694. PhysicsEngine.prototype._step = function (delta) {
  65695. var _this = this;
  65696. //check if any mesh has no body / requires an update
  65697. this._impostors.forEach(function (impostor) {
  65698. if (impostor.isBodyInitRequired()) {
  65699. _this._physicsPlugin.generatePhysicsBody(impostor);
  65700. }
  65701. });
  65702. if (delta > 0.1) {
  65703. delta = 0.1;
  65704. }
  65705. else if (delta <= 0) {
  65706. delta = 1.0 / 60.0;
  65707. }
  65708. this._physicsPlugin.executeStep(delta, this._impostors);
  65709. };
  65710. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65711. return this._physicsPlugin;
  65712. };
  65713. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65714. for (var i = 0; i < this._impostors.length; ++i) {
  65715. if (this._impostors[i].object === object) {
  65716. return this._impostors[i];
  65717. }
  65718. }
  65719. return null;
  65720. };
  65721. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65722. for (var i = 0; i < this._impostors.length; ++i) {
  65723. if (this._impostors[i].physicsBody === body) {
  65724. return this._impostors[i];
  65725. }
  65726. }
  65727. return null;
  65728. };
  65729. // Statics
  65730. PhysicsEngine.Epsilon = 0.001;
  65731. return PhysicsEngine;
  65732. }());
  65733. BABYLON.PhysicsEngine = PhysicsEngine;
  65734. })(BABYLON || (BABYLON = {}));
  65735. //# sourceMappingURL=babylon.physicsEngine.js.map
  65736. var BABYLON;
  65737. (function (BABYLON) {
  65738. var CannonJSPlugin = /** @class */ (function () {
  65739. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65740. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65741. if (iterations === void 0) { iterations = 10; }
  65742. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65743. this.name = "CannonJSPlugin";
  65744. this._physicsMaterials = new Array();
  65745. this._fixedTimeStep = 1 / 60;
  65746. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65747. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65748. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65749. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65750. this._tmpPosition = BABYLON.Vector3.Zero();
  65751. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65752. this._tmpUnityRotation = new BABYLON.Quaternion();
  65753. if (!this.isSupported()) {
  65754. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65755. return;
  65756. }
  65757. this.world = new this.BJSCANNON.World();
  65758. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65759. this.world.solver.iterations = iterations;
  65760. }
  65761. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65762. this.world.gravity.copy(gravity);
  65763. };
  65764. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65765. this._fixedTimeStep = timeStep;
  65766. };
  65767. CannonJSPlugin.prototype.getTimeStep = function () {
  65768. return this._fixedTimeStep;
  65769. };
  65770. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65771. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65772. };
  65773. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65774. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65775. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65776. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65777. };
  65778. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65779. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65780. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65781. impostor.physicsBody.applyForce(impulse, worldPoint);
  65782. };
  65783. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65784. //parent-child relationship. Does this impostor has a parent impostor?
  65785. if (impostor.parent) {
  65786. if (impostor.physicsBody) {
  65787. this.removePhysicsBody(impostor);
  65788. //TODO is that needed?
  65789. impostor.forceUpdate();
  65790. }
  65791. return;
  65792. }
  65793. //should a new body be created for this impostor?
  65794. if (impostor.isBodyInitRequired()) {
  65795. var shape = this._createShape(impostor);
  65796. //unregister events, if body is being changed
  65797. var oldBody = impostor.physicsBody;
  65798. if (oldBody) {
  65799. this.removePhysicsBody(impostor);
  65800. }
  65801. //create the body and material
  65802. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65803. var bodyCreationObject = {
  65804. mass: impostor.getParam("mass"),
  65805. material: material
  65806. };
  65807. // A simple extend, in case native options were used.
  65808. var nativeOptions = impostor.getParam("nativeOptions");
  65809. for (var key in nativeOptions) {
  65810. if (nativeOptions.hasOwnProperty(key)) {
  65811. bodyCreationObject[key] = nativeOptions[key];
  65812. }
  65813. }
  65814. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65815. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65816. this.world.addEventListener("preStep", impostor.beforeStep);
  65817. this.world.addEventListener("postStep", impostor.afterStep);
  65818. impostor.physicsBody.addShape(shape);
  65819. this.world.add(impostor.physicsBody);
  65820. //try to keep the body moving in the right direction by taking old properties.
  65821. //Should be tested!
  65822. if (oldBody) {
  65823. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65824. impostor.physicsBody[param].copy(oldBody[param]);
  65825. });
  65826. }
  65827. this._processChildMeshes(impostor);
  65828. }
  65829. //now update the body's transformation
  65830. this._updatePhysicsBodyTransformation(impostor);
  65831. };
  65832. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65833. var _this = this;
  65834. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65835. var currentRotation = mainImpostor.object.rotationQuaternion;
  65836. if (meshChildren.length) {
  65837. var processMesh = function (localPosition, mesh) {
  65838. if (!currentRotation || !mesh.rotationQuaternion) {
  65839. return;
  65840. }
  65841. var childImpostor = mesh.getPhysicsImpostor();
  65842. if (childImpostor) {
  65843. var parent = childImpostor.parent;
  65844. if (parent !== mainImpostor) {
  65845. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65846. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65847. if (childImpostor.physicsBody) {
  65848. _this.removePhysicsBody(childImpostor);
  65849. childImpostor.physicsBody = null;
  65850. }
  65851. childImpostor.parent = mainImpostor;
  65852. childImpostor.resetUpdateFlags();
  65853. 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));
  65854. //Add the mass of the children.
  65855. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65856. }
  65857. }
  65858. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65859. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65860. };
  65861. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65862. }
  65863. };
  65864. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65865. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65866. this.world.removeEventListener("preStep", impostor.beforeStep);
  65867. this.world.removeEventListener("postStep", impostor.afterStep);
  65868. this.world.remove(impostor.physicsBody);
  65869. };
  65870. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65871. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65872. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65873. if (!mainBody || !connectedBody) {
  65874. return;
  65875. }
  65876. var constraint;
  65877. var jointData = impostorJoint.joint.jointData;
  65878. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65879. var constraintData = {
  65880. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65881. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65882. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65883. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65884. maxForce: jointData.nativeParams.maxForce,
  65885. collideConnected: !!jointData.collision
  65886. };
  65887. switch (impostorJoint.joint.type) {
  65888. case BABYLON.PhysicsJoint.HingeJoint:
  65889. case BABYLON.PhysicsJoint.Hinge2Joint:
  65890. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65891. break;
  65892. case BABYLON.PhysicsJoint.DistanceJoint:
  65893. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65894. break;
  65895. case BABYLON.PhysicsJoint.SpringJoint:
  65896. var springData = jointData;
  65897. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65898. restLength: springData.length,
  65899. stiffness: springData.stiffness,
  65900. damping: springData.damping,
  65901. localAnchorA: constraintData.pivotA,
  65902. localAnchorB: constraintData.pivotB
  65903. });
  65904. break;
  65905. case BABYLON.PhysicsJoint.LockJoint:
  65906. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65907. break;
  65908. case BABYLON.PhysicsJoint.PointToPointJoint:
  65909. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65910. default:
  65911. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65912. break;
  65913. }
  65914. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  65915. constraint.collideConnected = !!jointData.collision;
  65916. impostorJoint.joint.physicsJoint = constraint;
  65917. //don't add spring as constraint, as it is not one.
  65918. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  65919. this.world.addConstraint(constraint);
  65920. }
  65921. else {
  65922. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65923. constraint.applyForce();
  65924. });
  65925. }
  65926. };
  65927. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65928. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65929. };
  65930. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65931. var index;
  65932. var mat;
  65933. for (index = 0; index < this._physicsMaterials.length; index++) {
  65934. mat = this._physicsMaterials[index];
  65935. if (mat.friction === friction && mat.restitution === restitution) {
  65936. return mat;
  65937. }
  65938. }
  65939. var currentMat = new this.BJSCANNON.Material(name);
  65940. currentMat.friction = friction;
  65941. currentMat.restitution = restitution;
  65942. this._physicsMaterials.push(currentMat);
  65943. return currentMat;
  65944. };
  65945. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65946. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65947. };
  65948. CannonJSPlugin.prototype._createShape = function (impostor) {
  65949. var object = impostor.object;
  65950. var returnValue;
  65951. var extendSize = impostor.getObjectExtendSize();
  65952. switch (impostor.type) {
  65953. case BABYLON.PhysicsImpostor.SphereImpostor:
  65954. var radiusX = extendSize.x;
  65955. var radiusY = extendSize.y;
  65956. var radiusZ = extendSize.z;
  65957. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65958. break;
  65959. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65960. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65961. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65962. break;
  65963. case BABYLON.PhysicsImpostor.BoxImpostor:
  65964. var box = extendSize.scale(0.5);
  65965. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65966. break;
  65967. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65968. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65969. returnValue = new this.BJSCANNON.Plane();
  65970. break;
  65971. case BABYLON.PhysicsImpostor.MeshImpostor:
  65972. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65973. var rawFaces = object.getIndices ? object.getIndices() : [];
  65974. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65975. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65976. break;
  65977. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65978. returnValue = this._createHeightmap(object);
  65979. break;
  65980. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65981. returnValue = new this.BJSCANNON.Particle();
  65982. break;
  65983. }
  65984. return returnValue;
  65985. };
  65986. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65987. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65988. var matrix = new Array();
  65989. //For now pointDepth will not be used and will be automatically calculated.
  65990. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65991. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65992. var boundingInfo = (object.getBoundingInfo());
  65993. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  65994. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  65995. var elementSize = dim * 2 / arraySize;
  65996. for (var i = 0; i < pos.length; i = i + 3) {
  65997. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65998. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65999. var y = pos[i + 1] + minY;
  66000. if (!matrix[x]) {
  66001. matrix[x] = [];
  66002. }
  66003. if (!matrix[x][z]) {
  66004. matrix[x][z] = y;
  66005. }
  66006. matrix[x][z] = Math.max(y, matrix[x][z]);
  66007. }
  66008. for (var x = 0; x <= arraySize; ++x) {
  66009. if (!matrix[x]) {
  66010. var loc = 1;
  66011. while (!matrix[(x + loc) % arraySize]) {
  66012. loc++;
  66013. }
  66014. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66015. //console.log("missing x", x);
  66016. }
  66017. for (var z = 0; z <= arraySize; ++z) {
  66018. if (!matrix[x][z]) {
  66019. var loc = 1;
  66020. var newValue;
  66021. while (newValue === undefined) {
  66022. newValue = matrix[x][(z + loc++) % arraySize];
  66023. }
  66024. matrix[x][z] = newValue;
  66025. }
  66026. }
  66027. }
  66028. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66029. elementSize: elementSize
  66030. });
  66031. //For future reference, needed for body transformation
  66032. shape.minY = minY;
  66033. return shape;
  66034. };
  66035. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66036. var object = impostor.object;
  66037. //make sure it is updated...
  66038. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66039. // The delta between the mesh position and the mesh bounding box center
  66040. var center = impostor.getObjectCenter();
  66041. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  66042. this._tmpPosition.copyFrom(center);
  66043. var quaternion = object.rotationQuaternion;
  66044. if (!quaternion) {
  66045. return;
  66046. }
  66047. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66048. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66049. //-90 DEG in X, precalculated
  66050. quaternion = quaternion.multiply(this._minus90X);
  66051. //Invert! (Precalculated, 90 deg in X)
  66052. //No need to clone. this will never change.
  66053. impostor.setDeltaRotation(this._plus90X);
  66054. }
  66055. //If it is a heightfield, if should be centered.
  66056. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66057. var mesh = object;
  66058. var boundingInfo = mesh.getBoundingInfo();
  66059. //calculate the correct body position:
  66060. var rotationQuaternion = mesh.rotationQuaternion;
  66061. mesh.rotationQuaternion = this._tmpUnityRotation;
  66062. mesh.computeWorldMatrix(true);
  66063. //get original center with no rotation
  66064. var c = center.clone();
  66065. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66066. //rotation is back
  66067. mesh.rotationQuaternion = rotationQuaternion;
  66068. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66069. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66070. mesh.setPivotMatrix(p);
  66071. mesh.computeWorldMatrix(true);
  66072. //calculate the translation
  66073. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66074. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66075. //add it inverted to the delta
  66076. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66077. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66078. mesh.setPivotMatrix(oldPivot);
  66079. mesh.computeWorldMatrix(true);
  66080. }
  66081. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66082. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66083. this._tmpPosition.copyFrom(object.position);
  66084. }
  66085. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66086. //Now update the impostor object
  66087. impostor.physicsBody.position.copy(this._tmpPosition);
  66088. impostor.physicsBody.quaternion.copy(quaternion);
  66089. };
  66090. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66091. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66092. if (impostor.object.rotationQuaternion) {
  66093. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66094. }
  66095. };
  66096. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66097. impostor.physicsBody.position.copy(newPosition);
  66098. impostor.physicsBody.quaternion.copy(newRotation);
  66099. };
  66100. CannonJSPlugin.prototype.isSupported = function () {
  66101. return this.BJSCANNON !== undefined;
  66102. };
  66103. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66104. impostor.physicsBody.velocity.copy(velocity);
  66105. };
  66106. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66107. impostor.physicsBody.angularVelocity.copy(velocity);
  66108. };
  66109. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66110. var v = impostor.physicsBody.velocity;
  66111. if (!v) {
  66112. return null;
  66113. }
  66114. return new BABYLON.Vector3(v.x, v.y, v.z);
  66115. };
  66116. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66117. var v = impostor.physicsBody.angularVelocity;
  66118. if (!v) {
  66119. return null;
  66120. }
  66121. return new BABYLON.Vector3(v.x, v.y, v.z);
  66122. };
  66123. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66124. impostor.physicsBody.mass = mass;
  66125. impostor.physicsBody.updateMassProperties();
  66126. };
  66127. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66128. return impostor.physicsBody.mass;
  66129. };
  66130. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66131. return impostor.physicsBody.material.friction;
  66132. };
  66133. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66134. impostor.physicsBody.material.friction = friction;
  66135. };
  66136. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66137. return impostor.physicsBody.material.restitution;
  66138. };
  66139. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66140. impostor.physicsBody.material.restitution = restitution;
  66141. };
  66142. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66143. impostor.physicsBody.sleep();
  66144. };
  66145. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66146. impostor.physicsBody.wakeUp();
  66147. };
  66148. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66149. joint.physicsJoint.distance = maxDistance;
  66150. };
  66151. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66152. // if (!motorIndex) {
  66153. // joint.physicsJoint.enableMotor();
  66154. // }
  66155. // }
  66156. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66157. // if (!motorIndex) {
  66158. // joint.physicsJoint.disableMotor();
  66159. // }
  66160. // }
  66161. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66162. if (!motorIndex) {
  66163. joint.physicsJoint.enableMotor();
  66164. joint.physicsJoint.setMotorSpeed(speed);
  66165. if (maxForce) {
  66166. this.setLimit(joint, maxForce);
  66167. }
  66168. }
  66169. };
  66170. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66171. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66172. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66173. };
  66174. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66175. var body = impostor.physicsBody;
  66176. mesh.position.x = body.position.x;
  66177. mesh.position.y = body.position.y;
  66178. mesh.position.z = body.position.z;
  66179. if (mesh.rotationQuaternion) {
  66180. mesh.rotationQuaternion.x = body.quaternion.x;
  66181. mesh.rotationQuaternion.y = body.quaternion.y;
  66182. mesh.rotationQuaternion.z = body.quaternion.z;
  66183. mesh.rotationQuaternion.w = body.quaternion.w;
  66184. }
  66185. };
  66186. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66187. var shape = impostor.physicsBody.shapes[0];
  66188. return shape.boundingSphereRadius;
  66189. };
  66190. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66191. var shape = impostor.physicsBody.shapes[0];
  66192. result.x = shape.halfExtents.x * 2;
  66193. result.y = shape.halfExtents.y * 2;
  66194. result.z = shape.halfExtents.z * 2;
  66195. };
  66196. CannonJSPlugin.prototype.dispose = function () {
  66197. };
  66198. return CannonJSPlugin;
  66199. }());
  66200. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66201. })(BABYLON || (BABYLON = {}));
  66202. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66203. var BABYLON;
  66204. (function (BABYLON) {
  66205. var OimoJSPlugin = /** @class */ (function () {
  66206. function OimoJSPlugin(iterations) {
  66207. this.name = "OimoJSPlugin";
  66208. this._tmpImpostorsArray = [];
  66209. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66210. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66211. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66212. this.world.worldscale(1);
  66213. this.world.clear();
  66214. //making sure no stats are calculated
  66215. this.world.isNoStat = true;
  66216. }
  66217. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66218. this.world.gravity.copy(gravity);
  66219. };
  66220. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66221. this.world.timeStep = timeStep;
  66222. };
  66223. OimoJSPlugin.prototype.getTimeStep = function () {
  66224. return this.world.timeStep;
  66225. };
  66226. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66227. var _this = this;
  66228. impostors.forEach(function (impostor) {
  66229. impostor.beforeStep();
  66230. });
  66231. this.world.step();
  66232. impostors.forEach(function (impostor) {
  66233. impostor.afterStep();
  66234. //update the ordered impostors array
  66235. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66236. });
  66237. //check for collisions
  66238. var contact = this.world.contacts;
  66239. while (contact !== null) {
  66240. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66241. contact = contact.next;
  66242. continue;
  66243. }
  66244. //is this body colliding with any other? get the impostor
  66245. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66246. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66247. if (!mainImpostor || !collidingImpostor) {
  66248. contact = contact.next;
  66249. continue;
  66250. }
  66251. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66252. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66253. contact = contact.next;
  66254. }
  66255. };
  66256. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66257. var mass = impostor.physicsBody.massInfo.mass;
  66258. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66259. };
  66260. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66261. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66262. this.applyImpulse(impostor, force, contactPoint);
  66263. };
  66264. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66265. var _this = this;
  66266. //parent-child relationship. Does this impostor has a parent impostor?
  66267. if (impostor.parent) {
  66268. if (impostor.physicsBody) {
  66269. this.removePhysicsBody(impostor);
  66270. //TODO is that needed?
  66271. impostor.forceUpdate();
  66272. }
  66273. return;
  66274. }
  66275. if (impostor.isBodyInitRequired()) {
  66276. var bodyConfig = {
  66277. name: impostor.uniqueId,
  66278. //Oimo must have mass, also for static objects.
  66279. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66280. size: [],
  66281. type: [],
  66282. pos: [],
  66283. rot: [],
  66284. move: impostor.getParam("mass") !== 0,
  66285. //Supporting older versions of Oimo
  66286. world: this.world
  66287. };
  66288. var impostors = [impostor];
  66289. var addToArray = function (parent) {
  66290. if (!parent.getChildMeshes)
  66291. return;
  66292. parent.getChildMeshes().forEach(function (m) {
  66293. if (m.physicsImpostor) {
  66294. impostors.push(m.physicsImpostor);
  66295. //m.physicsImpostor._init();
  66296. }
  66297. });
  66298. };
  66299. addToArray(impostor.object);
  66300. var checkWithEpsilon_1 = function (value) {
  66301. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66302. };
  66303. impostors.forEach(function (i) {
  66304. if (!impostor.object.rotationQuaternion) {
  66305. return;
  66306. }
  66307. //get the correct bounding box
  66308. var oldQuaternion = i.object.rotationQuaternion;
  66309. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66310. x: impostor.object.rotationQuaternion.x,
  66311. y: impostor.object.rotationQuaternion.y,
  66312. z: impostor.object.rotationQuaternion.z,
  66313. s: impostor.object.rotationQuaternion.w
  66314. });
  66315. var extendSize = i.getObjectExtendSize();
  66316. if (i === impostor) {
  66317. var center = impostor.getObjectCenter();
  66318. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66319. //Can also use Array.prototype.push.apply
  66320. bodyConfig.pos.push(center.x);
  66321. bodyConfig.pos.push(center.y);
  66322. bodyConfig.pos.push(center.z);
  66323. //tmp solution
  66324. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66325. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66326. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66327. }
  66328. else {
  66329. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66330. bodyConfig.pos.push(localPosition.x);
  66331. bodyConfig.pos.push(localPosition.y);
  66332. bodyConfig.pos.push(localPosition.z);
  66333. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66334. bodyConfig.rot.push(0);
  66335. bodyConfig.rot.push(0);
  66336. bodyConfig.rot.push(0);
  66337. }
  66338. // register mesh
  66339. switch (i.type) {
  66340. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66341. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66342. case BABYLON.PhysicsImpostor.SphereImpostor:
  66343. var radiusX = extendSize.x;
  66344. var radiusY = extendSize.y;
  66345. var radiusZ = extendSize.z;
  66346. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66347. bodyConfig.type.push('sphere');
  66348. //due to the way oimo works with compounds, add 3 times
  66349. bodyConfig.size.push(size);
  66350. bodyConfig.size.push(size);
  66351. bodyConfig.size.push(size);
  66352. break;
  66353. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66354. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66355. var sizeY = checkWithEpsilon_1(extendSize.y);
  66356. bodyConfig.type.push('cylinder');
  66357. bodyConfig.size.push(sizeX);
  66358. bodyConfig.size.push(sizeY);
  66359. //due to the way oimo works with compounds, add one more value.
  66360. bodyConfig.size.push(sizeY);
  66361. break;
  66362. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66363. case BABYLON.PhysicsImpostor.BoxImpostor:
  66364. default:
  66365. var sizeX = checkWithEpsilon_1(extendSize.x);
  66366. var sizeY = checkWithEpsilon_1(extendSize.y);
  66367. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66368. bodyConfig.type.push('box');
  66369. bodyConfig.size.push(sizeX);
  66370. bodyConfig.size.push(sizeY);
  66371. bodyConfig.size.push(sizeZ);
  66372. break;
  66373. }
  66374. //actually not needed, but hey...
  66375. i.object.rotationQuaternion = oldQuaternion;
  66376. });
  66377. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66378. }
  66379. else {
  66380. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66381. }
  66382. impostor.setDeltaPosition(this._tmpPositionVector);
  66383. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66384. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66385. };
  66386. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66387. //impostor.physicsBody.dispose();
  66388. //Same as : (older oimo versions)
  66389. this.world.removeRigidBody(impostor.physicsBody);
  66390. };
  66391. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66392. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66393. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66394. if (!mainBody || !connectedBody) {
  66395. return;
  66396. }
  66397. var jointData = impostorJoint.joint.jointData;
  66398. var options = jointData.nativeParams || {};
  66399. var type;
  66400. var nativeJointData = {
  66401. body1: mainBody,
  66402. body2: connectedBody,
  66403. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66404. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66405. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66406. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66407. min: options.min,
  66408. max: options.max,
  66409. collision: options.collision || jointData.collision,
  66410. spring: options.spring,
  66411. //supporting older version of Oimo
  66412. world: this.world
  66413. };
  66414. switch (impostorJoint.joint.type) {
  66415. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66416. type = "jointBall";
  66417. break;
  66418. case BABYLON.PhysicsJoint.SpringJoint:
  66419. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66420. var springData = jointData;
  66421. nativeJointData.min = springData.length || nativeJointData.min;
  66422. //Max should also be set, just make sure it is at least min
  66423. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66424. case BABYLON.PhysicsJoint.DistanceJoint:
  66425. type = "jointDistance";
  66426. nativeJointData.max = jointData.maxDistance;
  66427. break;
  66428. case BABYLON.PhysicsJoint.PrismaticJoint:
  66429. type = "jointPrisme";
  66430. break;
  66431. case BABYLON.PhysicsJoint.SliderJoint:
  66432. type = "jointSlide";
  66433. break;
  66434. case BABYLON.PhysicsJoint.WheelJoint:
  66435. type = "jointWheel";
  66436. break;
  66437. case BABYLON.PhysicsJoint.HingeJoint:
  66438. default:
  66439. type = "jointHinge";
  66440. break;
  66441. }
  66442. nativeJointData.type = type;
  66443. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66444. };
  66445. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66446. //Bug in Oimo prevents us from disposing a joint in the playground
  66447. //joint.joint.physicsJoint.dispose();
  66448. //So we will bruteforce it!
  66449. try {
  66450. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66451. }
  66452. catch (e) {
  66453. BABYLON.Tools.Warn(e);
  66454. }
  66455. };
  66456. OimoJSPlugin.prototype.isSupported = function () {
  66457. return this.BJSOIMO !== undefined;
  66458. };
  66459. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66460. if (!impostor.physicsBody.sleeping) {
  66461. //TODO check that
  66462. if (impostor.physicsBody.shapes.next) {
  66463. var parentShape = this._getLastShape(impostor.physicsBody);
  66464. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66465. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66466. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66467. }
  66468. else {
  66469. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66470. }
  66471. if (impostor.object.rotationQuaternion) {
  66472. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66473. impostor.object.rotationQuaternion.normalize();
  66474. }
  66475. }
  66476. };
  66477. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66478. var body = impostor.physicsBody;
  66479. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66480. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66481. body.syncShapes();
  66482. body.awake();
  66483. };
  66484. OimoJSPlugin.prototype._getLastShape = function (body) {
  66485. var lastShape = body.shapes;
  66486. while (lastShape.next) {
  66487. lastShape = lastShape.next;
  66488. }
  66489. return lastShape;
  66490. };
  66491. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66492. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66493. };
  66494. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66495. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66496. };
  66497. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66498. var v = impostor.physicsBody.linearVelocity;
  66499. if (!v) {
  66500. return null;
  66501. }
  66502. return new BABYLON.Vector3(v.x, v.y, v.z);
  66503. };
  66504. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66505. var v = impostor.physicsBody.angularVelocity;
  66506. if (!v) {
  66507. return null;
  66508. }
  66509. return new BABYLON.Vector3(v.x, v.y, v.z);
  66510. };
  66511. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66512. var staticBody = mass === 0;
  66513. //this will actually set the body's density and not its mass.
  66514. //But this is how oimo treats the mass variable.
  66515. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66516. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66517. };
  66518. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66519. return impostor.physicsBody.shapes.density;
  66520. };
  66521. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66522. return impostor.physicsBody.shapes.friction;
  66523. };
  66524. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66525. impostor.physicsBody.shapes.friction = friction;
  66526. };
  66527. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66528. return impostor.physicsBody.shapes.restitution;
  66529. };
  66530. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66531. impostor.physicsBody.shapes.restitution = restitution;
  66532. };
  66533. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66534. impostor.physicsBody.sleep();
  66535. };
  66536. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66537. impostor.physicsBody.awake();
  66538. };
  66539. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66540. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66541. if (minDistance !== void 0) {
  66542. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66543. }
  66544. };
  66545. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66546. //TODO separate rotational and transational motors.
  66547. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66548. if (motor) {
  66549. motor.setMotor(speed, maxForce);
  66550. }
  66551. };
  66552. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66553. //TODO separate rotational and transational motors.
  66554. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66555. if (motor) {
  66556. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66557. }
  66558. };
  66559. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66560. var body = impostor.physicsBody;
  66561. mesh.position.x = body.position.x;
  66562. mesh.position.y = body.position.y;
  66563. mesh.position.z = body.position.z;
  66564. if (mesh.rotationQuaternion) {
  66565. mesh.rotationQuaternion.x = body.orientation.x;
  66566. mesh.rotationQuaternion.y = body.orientation.y;
  66567. mesh.rotationQuaternion.z = body.orientation.z;
  66568. mesh.rotationQuaternion.w = body.orientation.s;
  66569. }
  66570. };
  66571. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66572. return impostor.physicsBody.shapes.radius;
  66573. };
  66574. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66575. var shape = impostor.physicsBody.shapes;
  66576. result.x = shape.halfWidth * 2;
  66577. result.y = shape.halfHeight * 2;
  66578. result.z = shape.halfDepth * 2;
  66579. };
  66580. OimoJSPlugin.prototype.dispose = function () {
  66581. this.world.clear();
  66582. };
  66583. return OimoJSPlugin;
  66584. }());
  66585. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66586. })(BABYLON || (BABYLON = {}));
  66587. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66588. var BABYLON;
  66589. (function (BABYLON) {
  66590. var Internals;
  66591. (function (Internals) {
  66592. /*
  66593. * Based on jsTGALoader - Javascript loader for TGA file
  66594. * By Vincent Thibault
  66595. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66596. */
  66597. var TGATools = /** @class */ (function () {
  66598. function TGATools() {
  66599. }
  66600. TGATools.GetTGAHeader = function (data) {
  66601. var offset = 0;
  66602. var header = {
  66603. id_length: data[offset++],
  66604. colormap_type: data[offset++],
  66605. image_type: data[offset++],
  66606. colormap_index: data[offset++] | data[offset++] << 8,
  66607. colormap_length: data[offset++] | data[offset++] << 8,
  66608. colormap_size: data[offset++],
  66609. origin: [
  66610. data[offset++] | data[offset++] << 8,
  66611. data[offset++] | data[offset++] << 8
  66612. ],
  66613. width: data[offset++] | data[offset++] << 8,
  66614. height: data[offset++] | data[offset++] << 8,
  66615. pixel_size: data[offset++],
  66616. flags: data[offset++]
  66617. };
  66618. return header;
  66619. };
  66620. TGATools.UploadContent = function (gl, data) {
  66621. // Not enough data to contain header ?
  66622. if (data.length < 19) {
  66623. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66624. return;
  66625. }
  66626. // Read Header
  66627. var offset = 18;
  66628. var header = TGATools.GetTGAHeader(data);
  66629. // Assume it's a valid Targa file.
  66630. if (header.id_length + offset > data.length) {
  66631. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66632. return;
  66633. }
  66634. // Skip not needed data
  66635. offset += header.id_length;
  66636. var use_rle = false;
  66637. var use_pal = false;
  66638. var use_rgb = false;
  66639. var use_grey = false;
  66640. // Get some informations.
  66641. switch (header.image_type) {
  66642. case TGATools._TYPE_RLE_INDEXED:
  66643. use_rle = true;
  66644. case TGATools._TYPE_INDEXED:
  66645. use_pal = true;
  66646. break;
  66647. case TGATools._TYPE_RLE_RGB:
  66648. use_rle = true;
  66649. case TGATools._TYPE_RGB:
  66650. use_rgb = true;
  66651. break;
  66652. case TGATools._TYPE_RLE_GREY:
  66653. use_rle = true;
  66654. case TGATools._TYPE_GREY:
  66655. use_grey = true;
  66656. break;
  66657. }
  66658. var pixel_data;
  66659. // var numAlphaBits = header.flags & 0xf;
  66660. var pixel_size = header.pixel_size >> 3;
  66661. var pixel_total = header.width * header.height * pixel_size;
  66662. // Read palettes
  66663. var palettes;
  66664. if (use_pal) {
  66665. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66666. }
  66667. // Read LRE
  66668. if (use_rle) {
  66669. pixel_data = new Uint8Array(pixel_total);
  66670. var c, count, i;
  66671. var localOffset = 0;
  66672. var pixels = new Uint8Array(pixel_size);
  66673. while (offset < pixel_total && localOffset < pixel_total) {
  66674. c = data[offset++];
  66675. count = (c & 0x7f) + 1;
  66676. // RLE pixels
  66677. if (c & 0x80) {
  66678. // Bind pixel tmp array
  66679. for (i = 0; i < pixel_size; ++i) {
  66680. pixels[i] = data[offset++];
  66681. }
  66682. // Copy pixel array
  66683. for (i = 0; i < count; ++i) {
  66684. pixel_data.set(pixels, localOffset + i * pixel_size);
  66685. }
  66686. localOffset += pixel_size * count;
  66687. }
  66688. else {
  66689. count *= pixel_size;
  66690. for (i = 0; i < count; ++i) {
  66691. pixel_data[localOffset + i] = data[offset++];
  66692. }
  66693. localOffset += count;
  66694. }
  66695. }
  66696. }
  66697. else {
  66698. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66699. }
  66700. // Load to texture
  66701. var x_start, y_start, x_step, y_step, y_end, x_end;
  66702. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66703. default:
  66704. case TGATools._ORIGIN_UL:
  66705. x_start = 0;
  66706. x_step = 1;
  66707. x_end = header.width;
  66708. y_start = 0;
  66709. y_step = 1;
  66710. y_end = header.height;
  66711. break;
  66712. case TGATools._ORIGIN_BL:
  66713. x_start = 0;
  66714. x_step = 1;
  66715. x_end = header.width;
  66716. y_start = header.height - 1;
  66717. y_step = -1;
  66718. y_end = -1;
  66719. break;
  66720. case TGATools._ORIGIN_UR:
  66721. x_start = header.width - 1;
  66722. x_step = -1;
  66723. x_end = -1;
  66724. y_start = 0;
  66725. y_step = 1;
  66726. y_end = header.height;
  66727. break;
  66728. case TGATools._ORIGIN_BR:
  66729. x_start = header.width - 1;
  66730. x_step = -1;
  66731. x_end = -1;
  66732. y_start = header.height - 1;
  66733. y_step = -1;
  66734. y_end = -1;
  66735. break;
  66736. }
  66737. // Load the specify method
  66738. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66739. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66740. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66741. };
  66742. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66743. var image = pixel_data, colormap = palettes;
  66744. var width = header.width, height = header.height;
  66745. var color, i = 0, x, y;
  66746. var imageData = new Uint8Array(width * height * 4);
  66747. for (y = y_start; y !== y_end; y += y_step) {
  66748. for (x = x_start; x !== x_end; x += x_step, i++) {
  66749. color = image[i];
  66750. imageData[(x + width * y) * 4 + 3] = 255;
  66751. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66752. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66753. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66754. }
  66755. }
  66756. return imageData;
  66757. };
  66758. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66759. var image = pixel_data;
  66760. var width = header.width, height = header.height;
  66761. var color, i = 0, x, y;
  66762. var imageData = new Uint8Array(width * height * 4);
  66763. for (y = y_start; y !== y_end; y += y_step) {
  66764. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66765. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66766. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66767. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66768. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66769. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66770. }
  66771. }
  66772. return imageData;
  66773. };
  66774. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66775. var image = pixel_data;
  66776. var width = header.width, height = header.height;
  66777. var i = 0, x, y;
  66778. var imageData = new Uint8Array(width * height * 4);
  66779. for (y = y_start; y !== y_end; y += y_step) {
  66780. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66781. imageData[(x + width * y) * 4 + 3] = 255;
  66782. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66783. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66784. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66785. }
  66786. }
  66787. return imageData;
  66788. };
  66789. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66790. var image = pixel_data;
  66791. var width = header.width, height = header.height;
  66792. var i = 0, x, y;
  66793. var imageData = new Uint8Array(width * height * 4);
  66794. for (y = y_start; y !== y_end; y += y_step) {
  66795. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66796. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66797. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66798. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66799. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66800. }
  66801. }
  66802. return imageData;
  66803. };
  66804. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66805. var image = pixel_data;
  66806. var width = header.width, height = header.height;
  66807. var color, i = 0, x, y;
  66808. var imageData = new Uint8Array(width * height * 4);
  66809. for (y = y_start; y !== y_end; y += y_step) {
  66810. for (x = x_start; x !== x_end; x += x_step, i++) {
  66811. color = image[i];
  66812. imageData[(x + width * y) * 4 + 0] = color;
  66813. imageData[(x + width * y) * 4 + 1] = color;
  66814. imageData[(x + width * y) * 4 + 2] = color;
  66815. imageData[(x + width * y) * 4 + 3] = 255;
  66816. }
  66817. }
  66818. return imageData;
  66819. };
  66820. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66821. var image = pixel_data;
  66822. var width = header.width, height = header.height;
  66823. var i = 0, x, y;
  66824. var imageData = new Uint8Array(width * height * 4);
  66825. for (y = y_start; y !== y_end; y += y_step) {
  66826. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66827. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66828. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66829. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66830. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66831. }
  66832. }
  66833. return imageData;
  66834. };
  66835. //private static _TYPE_NO_DATA = 0;
  66836. TGATools._TYPE_INDEXED = 1;
  66837. TGATools._TYPE_RGB = 2;
  66838. TGATools._TYPE_GREY = 3;
  66839. TGATools._TYPE_RLE_INDEXED = 9;
  66840. TGATools._TYPE_RLE_RGB = 10;
  66841. TGATools._TYPE_RLE_GREY = 11;
  66842. TGATools._ORIGIN_MASK = 0x30;
  66843. TGATools._ORIGIN_SHIFT = 0x04;
  66844. TGATools._ORIGIN_BL = 0x00;
  66845. TGATools._ORIGIN_BR = 0x01;
  66846. TGATools._ORIGIN_UL = 0x02;
  66847. TGATools._ORIGIN_UR = 0x03;
  66848. return TGATools;
  66849. }());
  66850. Internals.TGATools = TGATools;
  66851. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66852. })(BABYLON || (BABYLON = {}));
  66853. //# sourceMappingURL=babylon.tga.js.map
  66854. var BABYLON;
  66855. (function (BABYLON) {
  66856. var Internals;
  66857. (function (Internals) {
  66858. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66859. // All values and structures referenced from:
  66860. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66861. var DDS_MAGIC = 0x20534444;
  66862. var
  66863. //DDSD_CAPS = 0x1,
  66864. //DDSD_HEIGHT = 0x2,
  66865. //DDSD_WIDTH = 0x4,
  66866. //DDSD_PITCH = 0x8,
  66867. //DDSD_PIXELFORMAT = 0x1000,
  66868. DDSD_MIPMAPCOUNT = 0x20000;
  66869. //DDSD_LINEARSIZE = 0x80000,
  66870. //DDSD_DEPTH = 0x800000;
  66871. // var DDSCAPS_COMPLEX = 0x8,
  66872. // DDSCAPS_MIPMAP = 0x400000,
  66873. // DDSCAPS_TEXTURE = 0x1000;
  66874. var DDSCAPS2_CUBEMAP = 0x200;
  66875. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66876. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66877. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66878. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66879. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66880. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66881. // DDSCAPS2_VOLUME = 0x200000;
  66882. var
  66883. //DDPF_ALPHAPIXELS = 0x1,
  66884. //DDPF_ALPHA = 0x2,
  66885. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66886. //DDPF_YUV = 0x200,
  66887. DDPF_LUMINANCE = 0x20000;
  66888. function FourCCToInt32(value) {
  66889. return value.charCodeAt(0) +
  66890. (value.charCodeAt(1) << 8) +
  66891. (value.charCodeAt(2) << 16) +
  66892. (value.charCodeAt(3) << 24);
  66893. }
  66894. function Int32ToFourCC(value) {
  66895. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66896. }
  66897. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66898. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66899. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66900. var FOURCC_DX10 = FourCCToInt32("DX10");
  66901. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66902. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66903. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66904. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66905. var headerLengthInt = 31; // The header length in 32 bit ints
  66906. // Offsets into the header array
  66907. var off_magic = 0;
  66908. var off_size = 1;
  66909. var off_flags = 2;
  66910. var off_height = 3;
  66911. var off_width = 4;
  66912. var off_mipmapCount = 7;
  66913. var off_pfFlags = 20;
  66914. var off_pfFourCC = 21;
  66915. var off_RGBbpp = 22;
  66916. // var off_RMask = 23;
  66917. // var off_GMask = 24;
  66918. // var off_BMask = 25;
  66919. // var off_AMask = 26;
  66920. // var off_caps1 = 27;
  66921. var off_caps2 = 28;
  66922. // var off_caps3 = 29;
  66923. // var off_caps4 = 30;
  66924. var off_dxgiFormat = 32;
  66925. ;
  66926. var DDSTools = /** @class */ (function () {
  66927. function DDSTools() {
  66928. }
  66929. DDSTools.GetDDSInfo = function (arrayBuffer) {
  66930. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  66931. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  66932. var mipmapCount = 1;
  66933. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  66934. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66935. }
  66936. var fourCC = header[off_pfFourCC];
  66937. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  66938. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66939. switch (fourCC) {
  66940. case FOURCC_D3DFMT_R16G16B16A16F:
  66941. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66942. break;
  66943. case FOURCC_D3DFMT_R32G32B32A32F:
  66944. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66945. break;
  66946. case FOURCC_DX10:
  66947. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66948. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66949. break;
  66950. }
  66951. }
  66952. return {
  66953. width: header[off_width],
  66954. height: header[off_height],
  66955. mipmapCount: mipmapCount,
  66956. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66957. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66958. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66959. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66960. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66961. dxgiFormat: dxgiFormat,
  66962. textureType: textureType
  66963. };
  66964. };
  66965. DDSTools._ToHalfFloat = function (value) {
  66966. if (!DDSTools._FloatView) {
  66967. DDSTools._FloatView = new Float32Array(1);
  66968. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66969. }
  66970. DDSTools._FloatView[0] = value;
  66971. var x = DDSTools._Int32View[0];
  66972. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66973. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66974. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66975. /* If zero, or denormal, or exponent underflows too much for a denormal
  66976. * half, return signed zero. */
  66977. if (e < 103) {
  66978. return bits;
  66979. }
  66980. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66981. if (e > 142) {
  66982. bits |= 0x7c00;
  66983. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66984. * not Inf, so make sure we set one mantissa bit too. */
  66985. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66986. return bits;
  66987. }
  66988. /* If exponent underflows but not too much, return a denormal */
  66989. if (e < 113) {
  66990. m |= 0x0800;
  66991. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66992. * to 1, which is OK. */
  66993. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66994. return bits;
  66995. }
  66996. bits |= ((e - 112) << 10) | (m >> 1);
  66997. bits += m & 1;
  66998. return bits;
  66999. };
  67000. DDSTools._FromHalfFloat = function (value) {
  67001. var s = (value & 0x8000) >> 15;
  67002. var e = (value & 0x7C00) >> 10;
  67003. var f = value & 0x03FF;
  67004. if (e === 0) {
  67005. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67006. }
  67007. else if (e == 0x1F) {
  67008. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67009. }
  67010. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67011. };
  67012. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67013. var destArray = new Float32Array(dataLength);
  67014. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67015. var index = 0;
  67016. for (var y = 0; y < height; y++) {
  67017. for (var x = 0; x < width; x++) {
  67018. var srcPos = (x + y * width) * 4;
  67019. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67020. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67021. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67022. if (DDSTools.StoreLODInAlphaChannel) {
  67023. destArray[index + 3] = lod;
  67024. }
  67025. else {
  67026. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67027. }
  67028. index += 4;
  67029. }
  67030. }
  67031. return destArray;
  67032. };
  67033. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67034. if (DDSTools.StoreLODInAlphaChannel) {
  67035. var destArray = new Uint16Array(dataLength);
  67036. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67037. var index = 0;
  67038. for (var y = 0; y < height; y++) {
  67039. for (var x = 0; x < width; x++) {
  67040. var srcPos = (x + y * width) * 4;
  67041. destArray[index] = srcData[srcPos];
  67042. destArray[index + 1] = srcData[srcPos + 1];
  67043. destArray[index + 2] = srcData[srcPos + 2];
  67044. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67045. index += 4;
  67046. }
  67047. }
  67048. return destArray;
  67049. }
  67050. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67051. };
  67052. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67053. if (DDSTools.StoreLODInAlphaChannel) {
  67054. var destArray = new Float32Array(dataLength);
  67055. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67056. var index = 0;
  67057. for (var y = 0; y < height; y++) {
  67058. for (var x = 0; x < width; x++) {
  67059. var srcPos = (x + y * width) * 4;
  67060. destArray[index] = srcData[srcPos];
  67061. destArray[index + 1] = srcData[srcPos + 1];
  67062. destArray[index + 2] = srcData[srcPos + 2];
  67063. destArray[index + 3] = lod;
  67064. index += 4;
  67065. }
  67066. }
  67067. return destArray;
  67068. }
  67069. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67070. };
  67071. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67072. var destArray = new Uint8Array(dataLength);
  67073. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67074. var index = 0;
  67075. for (var y = 0; y < height; y++) {
  67076. for (var x = 0; x < width; x++) {
  67077. var srcPos = (x + y * width) * 4;
  67078. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67079. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67080. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67081. if (DDSTools.StoreLODInAlphaChannel) {
  67082. destArray[index + 3] = lod;
  67083. }
  67084. else {
  67085. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67086. }
  67087. index += 4;
  67088. }
  67089. }
  67090. return destArray;
  67091. };
  67092. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67093. var destArray = new Uint8Array(dataLength);
  67094. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67095. var index = 0;
  67096. for (var y = 0; y < height; y++) {
  67097. for (var x = 0; x < width; x++) {
  67098. var srcPos = (x + y * width) * 4;
  67099. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67100. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67101. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67102. if (DDSTools.StoreLODInAlphaChannel) {
  67103. destArray[index + 3] = lod;
  67104. }
  67105. else {
  67106. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67107. }
  67108. index += 4;
  67109. }
  67110. }
  67111. return destArray;
  67112. };
  67113. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67114. var byteArray = new Uint8Array(dataLength);
  67115. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67116. var index = 0;
  67117. for (var y = 0; y < height; y++) {
  67118. for (var x = 0; x < width; x++) {
  67119. var srcPos = (x + y * width) * 4;
  67120. byteArray[index] = srcData[srcPos + 2];
  67121. byteArray[index + 1] = srcData[srcPos + 1];
  67122. byteArray[index + 2] = srcData[srcPos];
  67123. byteArray[index + 3] = srcData[srcPos + 3];
  67124. index += 4;
  67125. }
  67126. }
  67127. return byteArray;
  67128. };
  67129. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67130. var byteArray = new Uint8Array(dataLength);
  67131. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67132. var index = 0;
  67133. for (var y = 0; y < height; y++) {
  67134. for (var x = 0; x < width; x++) {
  67135. var srcPos = (x + y * width) * 3;
  67136. byteArray[index] = srcData[srcPos + 2];
  67137. byteArray[index + 1] = srcData[srcPos + 1];
  67138. byteArray[index + 2] = srcData[srcPos];
  67139. index += 3;
  67140. }
  67141. }
  67142. return byteArray;
  67143. };
  67144. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67145. var byteArray = new Uint8Array(dataLength);
  67146. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67147. var index = 0;
  67148. for (var y = 0; y < height; y++) {
  67149. for (var x = 0; x < width; x++) {
  67150. var srcPos = (x + y * width);
  67151. byteArray[index] = srcData[srcPos];
  67152. index++;
  67153. }
  67154. }
  67155. return byteArray;
  67156. };
  67157. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67158. if (lodIndex === void 0) { lodIndex = -1; }
  67159. var ext = engine.getCaps().s3tc;
  67160. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67161. var internalFormat = 0;
  67162. var format = 0;
  67163. var blockBytes = 1;
  67164. if (header[off_magic] != DDS_MAGIC) {
  67165. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67166. return;
  67167. }
  67168. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67169. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67170. return;
  67171. }
  67172. if (info.isCompressed && !ext) {
  67173. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67174. return;
  67175. }
  67176. var bpp = header[off_RGBbpp];
  67177. dataOffset = header[off_size] + 4;
  67178. var computeFormats = false;
  67179. if (info.isFourCC) {
  67180. fourCC = header[off_pfFourCC];
  67181. switch (fourCC) {
  67182. case FOURCC_DXT1:
  67183. blockBytes = 8;
  67184. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67185. break;
  67186. case FOURCC_DXT3:
  67187. blockBytes = 16;
  67188. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67189. break;
  67190. case FOURCC_DXT5:
  67191. blockBytes = 16;
  67192. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67193. break;
  67194. case FOURCC_D3DFMT_R16G16B16A16F:
  67195. computeFormats = true;
  67196. break;
  67197. case FOURCC_D3DFMT_R32G32B32A32F:
  67198. computeFormats = true;
  67199. break;
  67200. case FOURCC_DX10:
  67201. // There is an additionnal header so dataOffset need to be changed
  67202. dataOffset += 5 * 4; // 5 uints
  67203. var supported = false;
  67204. switch (info.dxgiFormat) {
  67205. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67206. computeFormats = true;
  67207. supported = true;
  67208. break;
  67209. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67210. info.isRGB = true;
  67211. info.isFourCC = false;
  67212. bpp = 32;
  67213. supported = true;
  67214. break;
  67215. }
  67216. if (supported) {
  67217. break;
  67218. }
  67219. default:
  67220. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67221. return;
  67222. }
  67223. }
  67224. if (computeFormats) {
  67225. format = engine._getWebGLTextureType(info.textureType);
  67226. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67227. }
  67228. mipmapCount = 1;
  67229. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67230. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67231. }
  67232. for (var face = 0; face < faces; face++) {
  67233. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67234. width = header[off_width];
  67235. height = header[off_height];
  67236. for (mip = 0; mip < mipmapCount; ++mip) {
  67237. if (lodIndex === -1 || lodIndex === mip) {
  67238. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67239. var i = (lodIndex === -1) ? mip : 0;
  67240. if (!info.isCompressed && info.isFourCC) {
  67241. dataLength = width * height * 4;
  67242. var FloatArray = null;
  67243. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67244. if (bpp === 128) {
  67245. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67246. }
  67247. else if (bpp === 64) {
  67248. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67249. }
  67250. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67251. format = engine._getWebGLTextureType(info.textureType);
  67252. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67253. }
  67254. else {
  67255. if (bpp === 128) {
  67256. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67257. }
  67258. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67259. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67260. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67261. format = engine._getWebGLTextureType(info.textureType);
  67262. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67263. }
  67264. else {
  67265. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67266. }
  67267. }
  67268. if (FloatArray) {
  67269. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67270. }
  67271. }
  67272. else if (info.isRGB) {
  67273. if (bpp === 24) {
  67274. dataLength = width * height * 3;
  67275. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67276. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67277. }
  67278. else {
  67279. dataLength = width * height * 4;
  67280. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67281. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67282. }
  67283. }
  67284. else if (info.isLuminance) {
  67285. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67286. var unpaddedRowSize = width;
  67287. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67288. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67289. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67290. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67291. }
  67292. else {
  67293. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67294. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67295. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67296. }
  67297. }
  67298. dataOffset += width * height * (bpp / 8);
  67299. width *= 0.5;
  67300. height *= 0.5;
  67301. width = Math.max(1.0, width);
  67302. height = Math.max(1.0, height);
  67303. }
  67304. }
  67305. };
  67306. DDSTools.StoreLODInAlphaChannel = false;
  67307. return DDSTools;
  67308. }());
  67309. Internals.DDSTools = DDSTools;
  67310. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67311. })(BABYLON || (BABYLON = {}));
  67312. //# sourceMappingURL=babylon.dds.js.map
  67313. var BABYLON;
  67314. (function (BABYLON) {
  67315. var Internals;
  67316. (function (Internals) {
  67317. /**
  67318. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67319. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67320. */
  67321. var KhronosTextureContainer = /** @class */ (function () {
  67322. /**
  67323. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67324. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67325. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67326. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67327. */
  67328. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67329. this.arrayBuffer = arrayBuffer;
  67330. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67331. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67332. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67333. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67334. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67335. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67336. BABYLON.Tools.Error("texture missing KTX identifier");
  67337. return;
  67338. }
  67339. // load the reset of the header in native 32 bit int
  67340. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67341. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67342. var oppositeEndianess = header[0] === 0x01020304;
  67343. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67344. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67345. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67346. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67347. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67348. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67349. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67350. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67351. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67352. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67353. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67354. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67355. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67356. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67357. if (this.glType !== 0) {
  67358. BABYLON.Tools.Error("only compressed formats currently supported");
  67359. return;
  67360. }
  67361. else {
  67362. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67363. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67364. }
  67365. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67366. BABYLON.Tools.Error("only 2D textures currently supported");
  67367. return;
  67368. }
  67369. if (this.numberOfArrayElements !== 0) {
  67370. BABYLON.Tools.Error("texture arrays not currently supported");
  67371. return;
  67372. }
  67373. if (this.numberOfFaces !== facesExpected) {
  67374. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67375. return;
  67376. }
  67377. // we now have a completely validated file, so could use existence of loadType as success
  67378. // would need to make this more elaborate & adjust checks above to support more than one load type
  67379. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67380. }
  67381. // not as fast hardware based, but will probably never need to use
  67382. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67383. return ((val & 0xFF) << 24)
  67384. | ((val & 0xFF00) << 8)
  67385. | ((val >> 8) & 0xFF00)
  67386. | ((val >> 24) & 0xFF);
  67387. };
  67388. /**
  67389. * It is assumed that the texture has already been created & is currently bound
  67390. */
  67391. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67392. switch (this.loadType) {
  67393. case KhronosTextureContainer.COMPRESSED_2D:
  67394. this._upload2DCompressedLevels(gl, loadMipmaps);
  67395. break;
  67396. case KhronosTextureContainer.TEX_2D:
  67397. case KhronosTextureContainer.COMPRESSED_3D:
  67398. case KhronosTextureContainer.TEX_3D:
  67399. }
  67400. };
  67401. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67402. // initialize width & height for level 1
  67403. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67404. var width = this.pixelWidth;
  67405. var height = this.pixelHeight;
  67406. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67407. for (var level = 0; level < mipmapCount; level++) {
  67408. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67409. for (var face = 0; face < this.numberOfFaces; face++) {
  67410. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67411. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67412. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67413. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67414. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67415. }
  67416. width = Math.max(1.0, width * 0.5);
  67417. height = Math.max(1.0, height * 0.5);
  67418. }
  67419. };
  67420. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67421. // load types
  67422. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67423. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67424. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67425. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67426. return KhronosTextureContainer;
  67427. }());
  67428. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67430. })(BABYLON || (BABYLON = {}));
  67431. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67432. var BABYLON;
  67433. (function (BABYLON) {
  67434. var Debug;
  67435. (function (Debug) {
  67436. /**
  67437. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67438. */
  67439. var SkeletonViewer = /** @class */ (function () {
  67440. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67441. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67442. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67443. this.skeleton = skeleton;
  67444. this.mesh = mesh;
  67445. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67446. this.renderingGroupId = renderingGroupId;
  67447. this.color = BABYLON.Color3.White();
  67448. this._debugLines = new Array();
  67449. this._isEnabled = false;
  67450. this._scene = scene;
  67451. this.update();
  67452. this._renderFunction = this.update.bind(this);
  67453. }
  67454. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67455. get: function () {
  67456. return this._isEnabled;
  67457. },
  67458. set: function (value) {
  67459. if (this._isEnabled === value) {
  67460. return;
  67461. }
  67462. this._isEnabled = value;
  67463. if (value) {
  67464. this._scene.registerBeforeRender(this._renderFunction);
  67465. }
  67466. else {
  67467. this._scene.unregisterBeforeRender(this._renderFunction);
  67468. }
  67469. },
  67470. enumerable: true,
  67471. configurable: true
  67472. });
  67473. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67474. if (x === void 0) { x = 0; }
  67475. if (y === void 0) { y = 0; }
  67476. if (z === void 0) { z = 0; }
  67477. var tmat = BABYLON.Tmp.Matrix[0];
  67478. var parentBone = bone.getParent();
  67479. tmat.copyFrom(bone.getLocalMatrix());
  67480. if (x !== 0 || y !== 0 || z !== 0) {
  67481. var tmat2 = BABYLON.Tmp.Matrix[1];
  67482. BABYLON.Matrix.IdentityToRef(tmat2);
  67483. tmat2.m[12] = x;
  67484. tmat2.m[13] = y;
  67485. tmat2.m[14] = z;
  67486. tmat2.multiplyToRef(tmat, tmat);
  67487. }
  67488. if (parentBone) {
  67489. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67490. }
  67491. tmat.multiplyToRef(meshMat, tmat);
  67492. position.x = tmat.m[12];
  67493. position.y = tmat.m[13];
  67494. position.z = tmat.m[14];
  67495. };
  67496. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67497. var len = bones.length;
  67498. var meshPos = this.mesh.position;
  67499. for (var i = 0; i < len; i++) {
  67500. var bone = bones[i];
  67501. var points = this._debugLines[i];
  67502. if (!points) {
  67503. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67504. this._debugLines[i] = points;
  67505. }
  67506. this._getBonePosition(points[0], bone, meshMat);
  67507. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67508. points[0].subtractInPlace(meshPos);
  67509. points[1].subtractInPlace(meshPos);
  67510. }
  67511. };
  67512. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67513. var len = bones.length;
  67514. var boneNum = 0;
  67515. var meshPos = this.mesh.position;
  67516. for (var i = len - 1; i >= 0; i--) {
  67517. var childBone = bones[i];
  67518. var parentBone = childBone.getParent();
  67519. if (!parentBone) {
  67520. continue;
  67521. }
  67522. var points = this._debugLines[boneNum];
  67523. if (!points) {
  67524. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67525. this._debugLines[boneNum] = points;
  67526. }
  67527. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67528. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67529. points[0].subtractInPlace(meshPos);
  67530. points[1].subtractInPlace(meshPos);
  67531. boneNum++;
  67532. }
  67533. };
  67534. SkeletonViewer.prototype.update = function () {
  67535. if (this.autoUpdateBonesMatrices) {
  67536. this.skeleton.computeAbsoluteTransforms();
  67537. }
  67538. if (this.skeleton.bones[0].length === undefined) {
  67539. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67540. }
  67541. else {
  67542. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67543. }
  67544. if (!this._debugMesh) {
  67545. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67546. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67547. }
  67548. else {
  67549. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67550. }
  67551. this._debugMesh.position.copyFrom(this.mesh.position);
  67552. this._debugMesh.color = this.color;
  67553. };
  67554. SkeletonViewer.prototype.dispose = function () {
  67555. if (this._debugMesh) {
  67556. this.isEnabled = false;
  67557. this._debugMesh.dispose();
  67558. this._debugMesh = null;
  67559. }
  67560. };
  67561. return SkeletonViewer;
  67562. }());
  67563. Debug.SkeletonViewer = SkeletonViewer;
  67564. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67565. })(BABYLON || (BABYLON = {}));
  67566. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67567. var BABYLON;
  67568. (function (BABYLON) {
  67569. var Debug;
  67570. (function (Debug) {
  67571. var AxesViewer = /** @class */ (function () {
  67572. function AxesViewer(scene, scaleLines) {
  67573. if (scaleLines === void 0) { scaleLines = 1; }
  67574. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67575. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67576. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67577. this.scaleLines = 1;
  67578. this.scaleLines = scaleLines;
  67579. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67580. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67581. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67582. this._xmesh.renderingGroupId = 2;
  67583. this._ymesh.renderingGroupId = 2;
  67584. this._zmesh.renderingGroupId = 2;
  67585. this._xmesh.material.checkReadyOnlyOnce = true;
  67586. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67587. this._ymesh.material.checkReadyOnlyOnce = true;
  67588. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67589. this._zmesh.material.checkReadyOnlyOnce = true;
  67590. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67591. this.scene = scene;
  67592. }
  67593. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67594. var scaleLines = this.scaleLines;
  67595. if (this._xmesh) {
  67596. this._xmesh.position.copyFrom(position);
  67597. }
  67598. if (this._ymesh) {
  67599. this._ymesh.position.copyFrom(position);
  67600. }
  67601. if (this._zmesh) {
  67602. this._zmesh.position.copyFrom(position);
  67603. }
  67604. var point2 = this._xline[1];
  67605. point2.x = xaxis.x * scaleLines;
  67606. point2.y = xaxis.y * scaleLines;
  67607. point2.z = xaxis.z * scaleLines;
  67608. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67609. point2 = this._yline[1];
  67610. point2.x = yaxis.x * scaleLines;
  67611. point2.y = yaxis.y * scaleLines;
  67612. point2.z = yaxis.z * scaleLines;
  67613. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67614. point2 = this._zline[1];
  67615. point2.x = zaxis.x * scaleLines;
  67616. point2.y = zaxis.y * scaleLines;
  67617. point2.z = zaxis.z * scaleLines;
  67618. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67619. };
  67620. AxesViewer.prototype.dispose = function () {
  67621. if (this._xmesh) {
  67622. this._xmesh.dispose();
  67623. }
  67624. if (this._ymesh) {
  67625. this._ymesh.dispose();
  67626. }
  67627. if (this._zmesh) {
  67628. this._zmesh.dispose();
  67629. }
  67630. this._xmesh = null;
  67631. this._ymesh = null;
  67632. this._zmesh = null;
  67633. this.scene = null;
  67634. };
  67635. return AxesViewer;
  67636. }());
  67637. Debug.AxesViewer = AxesViewer;
  67638. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67639. })(BABYLON || (BABYLON = {}));
  67640. //# sourceMappingURL=babylon.axesViewer.js.map
  67641. var BABYLON;
  67642. (function (BABYLON) {
  67643. var Debug;
  67644. (function (Debug) {
  67645. var BoneAxesViewer = /** @class */ (function (_super) {
  67646. __extends(BoneAxesViewer, _super);
  67647. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67648. if (scaleLines === void 0) { scaleLines = 1; }
  67649. var _this = _super.call(this, scene, scaleLines) || this;
  67650. _this.pos = BABYLON.Vector3.Zero();
  67651. _this.xaxis = BABYLON.Vector3.Zero();
  67652. _this.yaxis = BABYLON.Vector3.Zero();
  67653. _this.zaxis = BABYLON.Vector3.Zero();
  67654. _this.mesh = mesh;
  67655. _this.bone = bone;
  67656. return _this;
  67657. }
  67658. BoneAxesViewer.prototype.update = function () {
  67659. if (!this.mesh || !this.bone) {
  67660. return;
  67661. }
  67662. var bone = this.bone;
  67663. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67664. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67665. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67666. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67667. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67668. };
  67669. BoneAxesViewer.prototype.dispose = function () {
  67670. if (this.mesh) {
  67671. this.mesh = null;
  67672. this.bone = null;
  67673. _super.prototype.dispose.call(this);
  67674. }
  67675. };
  67676. return BoneAxesViewer;
  67677. }(Debug.AxesViewer));
  67678. Debug.BoneAxesViewer = BoneAxesViewer;
  67679. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67680. })(BABYLON || (BABYLON = {}));
  67681. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67682. var BABYLON;
  67683. (function (BABYLON) {
  67684. var RayHelper = /** @class */ (function () {
  67685. function RayHelper(ray) {
  67686. this.ray = ray;
  67687. }
  67688. RayHelper.CreateAndShow = function (ray, scene, color) {
  67689. var helper = new RayHelper(ray);
  67690. helper.show(scene, color);
  67691. return helper;
  67692. };
  67693. RayHelper.prototype.show = function (scene, color) {
  67694. if (!this._renderFunction && this.ray) {
  67695. var ray = this.ray;
  67696. this._renderFunction = this._render.bind(this);
  67697. this._scene = scene;
  67698. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67699. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67700. if (this._renderFunction) {
  67701. this._scene.registerBeforeRender(this._renderFunction);
  67702. }
  67703. }
  67704. if (color && this._renderLine) {
  67705. this._renderLine.color.copyFrom(color);
  67706. }
  67707. };
  67708. RayHelper.prototype.hide = function () {
  67709. if (this._renderFunction && this._scene) {
  67710. this._scene.unregisterBeforeRender(this._renderFunction);
  67711. this._scene = null;
  67712. this._renderFunction = null;
  67713. if (this._renderLine) {
  67714. this._renderLine.dispose();
  67715. this._renderLine = null;
  67716. }
  67717. this._renderPoints = [];
  67718. }
  67719. };
  67720. RayHelper.prototype._render = function () {
  67721. var ray = this.ray;
  67722. if (!ray) {
  67723. return;
  67724. }
  67725. var point = this._renderPoints[1];
  67726. var len = Math.min(ray.length, 1000000);
  67727. point.copyFrom(ray.direction);
  67728. point.scaleInPlace(len);
  67729. point.addInPlace(ray.origin);
  67730. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67731. };
  67732. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67733. this._attachedToMesh = mesh;
  67734. var ray = this.ray;
  67735. if (!ray) {
  67736. return;
  67737. }
  67738. if (!ray.direction) {
  67739. ray.direction = BABYLON.Vector3.Zero();
  67740. }
  67741. if (!ray.origin) {
  67742. ray.origin = BABYLON.Vector3.Zero();
  67743. }
  67744. if (length) {
  67745. ray.length = length;
  67746. }
  67747. if (!meshSpaceOrigin) {
  67748. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67749. }
  67750. if (!meshSpaceDirection) {
  67751. // -1 so that this will work with Mesh.lookAt
  67752. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67753. }
  67754. if (!this._meshSpaceDirection) {
  67755. this._meshSpaceDirection = meshSpaceDirection.clone();
  67756. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67757. }
  67758. else {
  67759. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67760. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67761. }
  67762. if (!this._updateToMeshFunction) {
  67763. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67764. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67765. }
  67766. this._updateToMesh();
  67767. };
  67768. RayHelper.prototype.detachFromMesh = function () {
  67769. if (this._attachedToMesh) {
  67770. if (this._updateToMeshFunction) {
  67771. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67772. }
  67773. this._attachedToMesh = null;
  67774. this._updateToMeshFunction = null;
  67775. }
  67776. };
  67777. RayHelper.prototype._updateToMesh = function () {
  67778. var ray = this.ray;
  67779. if (!this._attachedToMesh || !ray) {
  67780. return;
  67781. }
  67782. if (this._attachedToMesh._isDisposed) {
  67783. this.detachFromMesh();
  67784. return;
  67785. }
  67786. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67787. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67788. };
  67789. RayHelper.prototype.dispose = function () {
  67790. this.hide();
  67791. this.detachFromMesh();
  67792. this.ray = null;
  67793. };
  67794. return RayHelper;
  67795. }());
  67796. BABYLON.RayHelper = RayHelper;
  67797. })(BABYLON || (BABYLON = {}));
  67798. //# sourceMappingURL=babylon.rayHelper.js.map
  67799. var BABYLON;
  67800. (function (BABYLON) {
  67801. var DebugLayer = /** @class */ (function () {
  67802. function DebugLayer(scene) {
  67803. this._scene = scene;
  67804. }
  67805. /** Creates the inspector window. */
  67806. DebugLayer.prototype._createInspector = function (config) {
  67807. if (config === void 0) { config = {}; }
  67808. var popup = config.popup || false;
  67809. var initialTab = config.initialTab || 0;
  67810. var parentElement = config.parentElement || null;
  67811. if (!this._inspector) {
  67812. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67813. } // else nothing to do,; instance is already existing
  67814. };
  67815. DebugLayer.prototype.isVisible = function () {
  67816. if (!this._inspector) {
  67817. return false;
  67818. }
  67819. return true;
  67820. };
  67821. DebugLayer.prototype.hide = function () {
  67822. if (this._inspector) {
  67823. try {
  67824. this._inspector.dispose();
  67825. }
  67826. catch (e) {
  67827. // If the inspector has been removed directly from the inspector tool
  67828. }
  67829. this._inspector = null;
  67830. }
  67831. };
  67832. DebugLayer.prototype.show = function (config) {
  67833. if (config === void 0) { config = {}; }
  67834. if (typeof INSPECTOR == 'undefined') {
  67835. // Load inspector and add it to the DOM
  67836. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67837. }
  67838. else {
  67839. // Otherwise creates the inspector
  67840. this._createInspector(config);
  67841. }
  67842. };
  67843. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67844. return DebugLayer;
  67845. }());
  67846. BABYLON.DebugLayer = DebugLayer;
  67847. })(BABYLON || (BABYLON = {}));
  67848. //# sourceMappingURL=babylon.debugLayer.js.map
  67849. var BABYLON;
  67850. (function (BABYLON) {
  67851. var Debug;
  67852. (function (Debug) {
  67853. var PhysicsViewer = /** @class */ (function () {
  67854. function PhysicsViewer(scene) {
  67855. this._impostors = [];
  67856. this._meshes = [];
  67857. this._numMeshes = 0;
  67858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67859. var physicEngine = this._scene.getPhysicsEngine();
  67860. if (physicEngine) {
  67861. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67862. }
  67863. }
  67864. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67865. var plugin = this._physicsEnginePlugin;
  67866. for (var i = 0; i < this._numMeshes; i++) {
  67867. var impostor = this._impostors[i];
  67868. if (!impostor) {
  67869. continue;
  67870. }
  67871. if (impostor.isDisposed) {
  67872. this.hideImpostor(this._impostors[i--]);
  67873. }
  67874. else {
  67875. var mesh = this._meshes[i];
  67876. if (mesh && plugin) {
  67877. plugin.syncMeshWithImpostor(mesh, impostor);
  67878. }
  67879. }
  67880. }
  67881. };
  67882. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67883. if (!this._scene) {
  67884. return;
  67885. }
  67886. for (var i = 0; i < this._numMeshes; i++) {
  67887. if (this._impostors[i] == impostor) {
  67888. return;
  67889. }
  67890. }
  67891. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67892. if (debugMesh) {
  67893. this._impostors[this._numMeshes] = impostor;
  67894. this._meshes[this._numMeshes] = debugMesh;
  67895. if (this._numMeshes === 0) {
  67896. this._renderFunction = this._updateDebugMeshes.bind(this);
  67897. this._scene.registerBeforeRender(this._renderFunction);
  67898. }
  67899. this._numMeshes++;
  67900. }
  67901. };
  67902. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67903. if (!impostor || !this._scene) {
  67904. return;
  67905. }
  67906. var removed = false;
  67907. for (var i = 0; i < this._numMeshes; i++) {
  67908. if (this._impostors[i] == impostor) {
  67909. var mesh = this._meshes[i];
  67910. if (!mesh) {
  67911. continue;
  67912. }
  67913. this._scene.removeMesh(mesh);
  67914. mesh.dispose();
  67915. this._numMeshes--;
  67916. if (this._numMeshes > 0) {
  67917. this._meshes[i] = this._meshes[this._numMeshes];
  67918. this._impostors[i] = this._impostors[this._numMeshes];
  67919. this._meshes[this._numMeshes] = null;
  67920. this._impostors[this._numMeshes] = null;
  67921. }
  67922. else {
  67923. this._meshes[0] = null;
  67924. this._impostors[0] = null;
  67925. }
  67926. removed = true;
  67927. break;
  67928. }
  67929. }
  67930. if (removed && this._numMeshes === 0) {
  67931. this._scene.unregisterBeforeRender(this._renderFunction);
  67932. }
  67933. };
  67934. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  67935. if (!this._debugMaterial) {
  67936. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  67937. this._debugMaterial.wireframe = true;
  67938. }
  67939. return this._debugMaterial;
  67940. };
  67941. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67942. if (!this._debugBoxMesh) {
  67943. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67944. this._debugBoxMesh.renderingGroupId = 1;
  67945. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67946. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67947. scene.removeMesh(this._debugBoxMesh);
  67948. }
  67949. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67950. };
  67951. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67952. if (!this._debugSphereMesh) {
  67953. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67954. this._debugSphereMesh.renderingGroupId = 1;
  67955. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67956. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67957. scene.removeMesh(this._debugSphereMesh);
  67958. }
  67959. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67960. };
  67961. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67962. var mesh = null;
  67963. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67964. mesh = this._getDebugBoxMesh(scene);
  67965. impostor.getBoxSizeToRef(mesh.scaling);
  67966. }
  67967. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67968. mesh = this._getDebugSphereMesh(scene);
  67969. var radius = impostor.getRadius();
  67970. mesh.scaling.x = radius * 2;
  67971. mesh.scaling.y = radius * 2;
  67972. mesh.scaling.z = radius * 2;
  67973. }
  67974. return mesh;
  67975. };
  67976. PhysicsViewer.prototype.dispose = function () {
  67977. for (var i = 0; i < this._numMeshes; i++) {
  67978. this.hideImpostor(this._impostors[i]);
  67979. }
  67980. if (this._debugBoxMesh) {
  67981. this._debugBoxMesh.dispose();
  67982. }
  67983. if (this._debugSphereMesh) {
  67984. this._debugSphereMesh.dispose();
  67985. }
  67986. if (this._debugMaterial) {
  67987. this._debugMaterial.dispose();
  67988. }
  67989. this._impostors.length = 0;
  67990. this._scene = null;
  67991. this._physicsEnginePlugin = null;
  67992. };
  67993. return PhysicsViewer;
  67994. }());
  67995. Debug.PhysicsViewer = PhysicsViewer;
  67996. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67997. })(BABYLON || (BABYLON = {}));
  67998. //# sourceMappingURL=babylon.physicsViewer.js.map
  67999. var BABYLON;
  68000. (function (BABYLON) {
  68001. var BoundingBoxRenderer = /** @class */ (function () {
  68002. function BoundingBoxRenderer(scene) {
  68003. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68004. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68005. this.showBackLines = true;
  68006. this.renderList = new BABYLON.SmartArray(32);
  68007. this._vertexBuffers = {};
  68008. this._scene = scene;
  68009. }
  68010. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68011. if (this._colorShader) {
  68012. return;
  68013. }
  68014. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68015. attributes: [BABYLON.VertexBuffer.PositionKind],
  68016. uniforms: ["world", "viewProjection", "color"]
  68017. });
  68018. var engine = this._scene.getEngine();
  68019. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68021. this._createIndexBuffer();
  68022. };
  68023. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68024. var engine = this._scene.getEngine();
  68025. 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]);
  68026. };
  68027. BoundingBoxRenderer.prototype._rebuild = function () {
  68028. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68029. if (vb) {
  68030. vb._rebuild();
  68031. }
  68032. this._createIndexBuffer();
  68033. };
  68034. BoundingBoxRenderer.prototype.reset = function () {
  68035. this.renderList.reset();
  68036. };
  68037. BoundingBoxRenderer.prototype.render = function () {
  68038. if (this.renderList.length === 0) {
  68039. return;
  68040. }
  68041. this._prepareRessources();
  68042. if (!this._colorShader.isReady()) {
  68043. return;
  68044. }
  68045. var engine = this._scene.getEngine();
  68046. engine.setDepthWrite(false);
  68047. this._colorShader._preBind();
  68048. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68049. var boundingBox = this.renderList.data[boundingBoxIndex];
  68050. var min = boundingBox.minimum;
  68051. var max = boundingBox.maximum;
  68052. var diff = max.subtract(min);
  68053. var median = min.add(diff.scale(0.5));
  68054. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68055. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68056. .multiply(boundingBox.getWorldMatrix());
  68057. // VBOs
  68058. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68059. if (this.showBackLines) {
  68060. // Back
  68061. engine.setDepthFunctionToGreaterOrEqual();
  68062. this._scene.resetCachedMaterial();
  68063. this._colorShader.setColor4("color", this.backColor.toColor4());
  68064. this._colorShader.bind(worldMatrix);
  68065. // Draw order
  68066. engine.draw(false, 0, 24);
  68067. }
  68068. // Front
  68069. engine.setDepthFunctionToLess();
  68070. this._scene.resetCachedMaterial();
  68071. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68072. this._colorShader.bind(worldMatrix);
  68073. // Draw order
  68074. engine.draw(false, 0, 24);
  68075. }
  68076. this._colorShader.unbind();
  68077. engine.setDepthFunctionToLessOrEqual();
  68078. engine.setDepthWrite(true);
  68079. };
  68080. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68081. this._prepareRessources();
  68082. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68083. return;
  68084. }
  68085. var engine = this._scene.getEngine();
  68086. engine.setDepthWrite(false);
  68087. engine.setColorWrite(false);
  68088. this._colorShader._preBind();
  68089. var boundingBox = mesh._boundingInfo.boundingBox;
  68090. var min = boundingBox.minimum;
  68091. var max = boundingBox.maximum;
  68092. var diff = max.subtract(min);
  68093. var median = min.add(diff.scale(0.5));
  68094. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68095. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68096. .multiply(boundingBox.getWorldMatrix());
  68097. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68098. engine.setDepthFunctionToLess();
  68099. this._scene.resetCachedMaterial();
  68100. this._colorShader.bind(worldMatrix);
  68101. engine.draw(false, 0, 24);
  68102. this._colorShader.unbind();
  68103. engine.setDepthFunctionToLessOrEqual();
  68104. engine.setDepthWrite(true);
  68105. engine.setColorWrite(true);
  68106. };
  68107. BoundingBoxRenderer.prototype.dispose = function () {
  68108. if (!this._colorShader) {
  68109. return;
  68110. }
  68111. this.renderList.dispose();
  68112. this._colorShader.dispose();
  68113. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68114. if (buffer) {
  68115. buffer.dispose();
  68116. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68117. }
  68118. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68119. };
  68120. return BoundingBoxRenderer;
  68121. }());
  68122. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68123. })(BABYLON || (BABYLON = {}));
  68124. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68125. var BABYLON;
  68126. (function (BABYLON) {
  68127. var MorphTarget = /** @class */ (function () {
  68128. function MorphTarget(name, influence) {
  68129. if (influence === void 0) { influence = 0; }
  68130. this.name = name;
  68131. this.animations = new Array();
  68132. this._positions = null;
  68133. this._normals = null;
  68134. this._tangents = null;
  68135. this.onInfluenceChanged = new BABYLON.Observable();
  68136. this.influence = influence;
  68137. }
  68138. Object.defineProperty(MorphTarget.prototype, "influence", {
  68139. get: function () {
  68140. return this._influence;
  68141. },
  68142. set: function (influence) {
  68143. if (this._influence === influence) {
  68144. return;
  68145. }
  68146. var previous = this._influence;
  68147. this._influence = influence;
  68148. if (this.onInfluenceChanged.hasObservers) {
  68149. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68150. }
  68151. },
  68152. enumerable: true,
  68153. configurable: true
  68154. });
  68155. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68156. get: function () {
  68157. return !!this._positions;
  68158. },
  68159. enumerable: true,
  68160. configurable: true
  68161. });
  68162. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68163. get: function () {
  68164. return !!this._normals;
  68165. },
  68166. enumerable: true,
  68167. configurable: true
  68168. });
  68169. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68170. get: function () {
  68171. return !!this._tangents;
  68172. },
  68173. enumerable: true,
  68174. configurable: true
  68175. });
  68176. MorphTarget.prototype.setPositions = function (data) {
  68177. this._positions = data;
  68178. };
  68179. MorphTarget.prototype.getPositions = function () {
  68180. return this._positions;
  68181. };
  68182. MorphTarget.prototype.setNormals = function (data) {
  68183. this._normals = data;
  68184. };
  68185. MorphTarget.prototype.getNormals = function () {
  68186. return this._normals;
  68187. };
  68188. MorphTarget.prototype.setTangents = function (data) {
  68189. this._tangents = data;
  68190. };
  68191. MorphTarget.prototype.getTangents = function () {
  68192. return this._tangents;
  68193. };
  68194. /**
  68195. * Serializes the current target into a Serialization object.
  68196. * Returns the serialized object.
  68197. */
  68198. MorphTarget.prototype.serialize = function () {
  68199. var serializationObject = {};
  68200. serializationObject.name = this.name;
  68201. serializationObject.influence = this.influence;
  68202. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68203. if (this.hasNormals) {
  68204. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68205. }
  68206. if (this.hasTangents) {
  68207. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68208. }
  68209. // Animations
  68210. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68211. return serializationObject;
  68212. };
  68213. // Statics
  68214. MorphTarget.Parse = function (serializationObject) {
  68215. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68216. result.setPositions(serializationObject.positions);
  68217. if (serializationObject.normals) {
  68218. result.setNormals(serializationObject.normals);
  68219. }
  68220. if (serializationObject.tangents) {
  68221. result.setTangents(serializationObject.tangents);
  68222. }
  68223. // Animations
  68224. if (serializationObject.animations) {
  68225. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68226. var parsedAnimation = serializationObject.animations[animationIndex];
  68227. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68228. }
  68229. }
  68230. return result;
  68231. };
  68232. MorphTarget.FromMesh = function (mesh, name, influence) {
  68233. if (!name) {
  68234. name = mesh.name;
  68235. }
  68236. var result = new MorphTarget(name, influence);
  68237. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68239. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68240. }
  68241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68242. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68243. }
  68244. return result;
  68245. };
  68246. return MorphTarget;
  68247. }());
  68248. BABYLON.MorphTarget = MorphTarget;
  68249. })(BABYLON || (BABYLON = {}));
  68250. //# sourceMappingURL=babylon.morphTarget.js.map
  68251. var BABYLON;
  68252. (function (BABYLON) {
  68253. var MorphTargetManager = /** @class */ (function () {
  68254. function MorphTargetManager(scene) {
  68255. if (scene === void 0) { scene = null; }
  68256. this._targets = new Array();
  68257. this._targetObservable = new Array();
  68258. this._activeTargets = new BABYLON.SmartArray(16);
  68259. this._supportsNormals = false;
  68260. this._supportsTangents = false;
  68261. this._vertexCount = 0;
  68262. this._uniqueId = 0;
  68263. this._tempInfluences = new Array();
  68264. if (!scene) {
  68265. scene = BABYLON.Engine.LastCreatedScene;
  68266. }
  68267. this._scene = scene;
  68268. if (this._scene) {
  68269. this._scene.morphTargetManagers.push(this);
  68270. this._uniqueId = this._scene.getUniqueId();
  68271. }
  68272. }
  68273. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68274. get: function () {
  68275. return this._uniqueId;
  68276. },
  68277. enumerable: true,
  68278. configurable: true
  68279. });
  68280. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68281. get: function () {
  68282. return this._vertexCount;
  68283. },
  68284. enumerable: true,
  68285. configurable: true
  68286. });
  68287. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68288. get: function () {
  68289. return this._supportsNormals;
  68290. },
  68291. enumerable: true,
  68292. configurable: true
  68293. });
  68294. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68295. get: function () {
  68296. return this._supportsTangents;
  68297. },
  68298. enumerable: true,
  68299. configurable: true
  68300. });
  68301. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68302. get: function () {
  68303. return this._targets.length;
  68304. },
  68305. enumerable: true,
  68306. configurable: true
  68307. });
  68308. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68309. get: function () {
  68310. return this._activeTargets.length;
  68311. },
  68312. enumerable: true,
  68313. configurable: true
  68314. });
  68315. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68316. get: function () {
  68317. return this._influences;
  68318. },
  68319. enumerable: true,
  68320. configurable: true
  68321. });
  68322. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68323. return this._activeTargets.data[index];
  68324. };
  68325. MorphTargetManager.prototype.getTarget = function (index) {
  68326. return this._targets[index];
  68327. };
  68328. MorphTargetManager.prototype.addTarget = function (target) {
  68329. var _this = this;
  68330. this._targets.push(target);
  68331. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68332. _this._syncActiveTargets(needUpdate);
  68333. }));
  68334. this._syncActiveTargets(true);
  68335. };
  68336. MorphTargetManager.prototype.removeTarget = function (target) {
  68337. var index = this._targets.indexOf(target);
  68338. if (index >= 0) {
  68339. this._targets.splice(index, 1);
  68340. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68341. this._syncActiveTargets(true);
  68342. }
  68343. };
  68344. /**
  68345. * Serializes the current manager into a Serialization object.
  68346. * Returns the serialized object.
  68347. */
  68348. MorphTargetManager.prototype.serialize = function () {
  68349. var serializationObject = {};
  68350. serializationObject.id = this.uniqueId;
  68351. serializationObject.targets = [];
  68352. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68353. var target = _a[_i];
  68354. serializationObject.targets.push(target.serialize());
  68355. }
  68356. return serializationObject;
  68357. };
  68358. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68359. var influenceCount = 0;
  68360. this._activeTargets.reset();
  68361. this._supportsNormals = true;
  68362. this._supportsTangents = true;
  68363. this._vertexCount = 0;
  68364. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68365. var target = _a[_i];
  68366. if (target.influence > 0) {
  68367. this._activeTargets.push(target);
  68368. this._tempInfluences[influenceCount++] = target.influence;
  68369. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68370. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68371. var positions = target.getPositions();
  68372. if (!positions) {
  68373. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68374. return;
  68375. }
  68376. var vertexCount = positions.length / 3;
  68377. if (this._vertexCount === 0) {
  68378. this._vertexCount = vertexCount;
  68379. }
  68380. else if (this._vertexCount !== vertexCount) {
  68381. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68382. return;
  68383. }
  68384. }
  68385. }
  68386. if (!this._influences || this._influences.length !== influenceCount) {
  68387. this._influences = new Float32Array(influenceCount);
  68388. }
  68389. for (var index = 0; index < influenceCount; index++) {
  68390. this._influences[index] = this._tempInfluences[index];
  68391. }
  68392. if (needUpdate && this._scene) {
  68393. // Flag meshes as dirty to resync with the active targets
  68394. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68395. var mesh = _c[_b];
  68396. if (mesh.morphTargetManager === this) {
  68397. mesh._syncGeometryWithMorphTargetManager();
  68398. }
  68399. }
  68400. }
  68401. };
  68402. // Statics
  68403. MorphTargetManager.Parse = function (serializationObject, scene) {
  68404. var result = new MorphTargetManager(scene);
  68405. result._uniqueId = serializationObject.id;
  68406. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68407. var targetData = _a[_i];
  68408. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68409. }
  68410. return result;
  68411. };
  68412. return MorphTargetManager;
  68413. }());
  68414. BABYLON.MorphTargetManager = MorphTargetManager;
  68415. })(BABYLON || (BABYLON = {}));
  68416. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68417. var BABYLON;
  68418. (function (BABYLON) {
  68419. var Octree = /** @class */ (function () {
  68420. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68421. if (maxDepth === void 0) { maxDepth = 2; }
  68422. this.maxDepth = maxDepth;
  68423. this.dynamicContent = new Array();
  68424. this._maxBlockCapacity = maxBlockCapacity || 64;
  68425. this._selectionContent = new BABYLON.SmartArray(1024);
  68426. this._creationFunc = creationFunc;
  68427. }
  68428. // Methods
  68429. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68430. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68431. };
  68432. Octree.prototype.addMesh = function (entry) {
  68433. for (var index = 0; index < this.blocks.length; index++) {
  68434. var block = this.blocks[index];
  68435. block.addEntry(entry);
  68436. }
  68437. };
  68438. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68439. this._selectionContent.reset();
  68440. for (var index = 0; index < this.blocks.length; index++) {
  68441. var block = this.blocks[index];
  68442. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68443. }
  68444. if (allowDuplicate) {
  68445. this._selectionContent.concat(this.dynamicContent);
  68446. }
  68447. else {
  68448. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68449. }
  68450. return this._selectionContent;
  68451. };
  68452. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68453. this._selectionContent.reset();
  68454. for (var index = 0; index < this.blocks.length; index++) {
  68455. var block = this.blocks[index];
  68456. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68457. }
  68458. if (allowDuplicate) {
  68459. this._selectionContent.concat(this.dynamicContent);
  68460. }
  68461. else {
  68462. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68463. }
  68464. return this._selectionContent;
  68465. };
  68466. Octree.prototype.intersectsRay = function (ray) {
  68467. this._selectionContent.reset();
  68468. for (var index = 0; index < this.blocks.length; index++) {
  68469. var block = this.blocks[index];
  68470. block.intersectsRay(ray, this._selectionContent);
  68471. }
  68472. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68473. return this._selectionContent;
  68474. };
  68475. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68476. target.blocks = new Array();
  68477. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68478. // Segmenting space
  68479. for (var x = 0; x < 2; x++) {
  68480. for (var y = 0; y < 2; y++) {
  68481. for (var z = 0; z < 2; z++) {
  68482. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68483. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68484. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68485. block.addEntries(entries);
  68486. target.blocks.push(block);
  68487. }
  68488. }
  68489. }
  68490. };
  68491. Octree.CreationFuncForMeshes = function (entry, block) {
  68492. var boundingInfo = entry.getBoundingInfo();
  68493. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68494. block.entries.push(entry);
  68495. }
  68496. };
  68497. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68498. var boundingInfo = entry.getBoundingInfo();
  68499. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68500. block.entries.push(entry);
  68501. }
  68502. };
  68503. return Octree;
  68504. }());
  68505. BABYLON.Octree = Octree;
  68506. })(BABYLON || (BABYLON = {}));
  68507. //# sourceMappingURL=babylon.octree.js.map
  68508. var BABYLON;
  68509. (function (BABYLON) {
  68510. var OctreeBlock = /** @class */ (function () {
  68511. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68512. this.entries = new Array();
  68513. this._boundingVectors = new Array();
  68514. this._capacity = capacity;
  68515. this._depth = depth;
  68516. this._maxDepth = maxDepth;
  68517. this._creationFunc = creationFunc;
  68518. this._minPoint = minPoint;
  68519. this._maxPoint = maxPoint;
  68520. this._boundingVectors.push(minPoint.clone());
  68521. this._boundingVectors.push(maxPoint.clone());
  68522. this._boundingVectors.push(minPoint.clone());
  68523. this._boundingVectors[2].x = maxPoint.x;
  68524. this._boundingVectors.push(minPoint.clone());
  68525. this._boundingVectors[3].y = maxPoint.y;
  68526. this._boundingVectors.push(minPoint.clone());
  68527. this._boundingVectors[4].z = maxPoint.z;
  68528. this._boundingVectors.push(maxPoint.clone());
  68529. this._boundingVectors[5].z = minPoint.z;
  68530. this._boundingVectors.push(maxPoint.clone());
  68531. this._boundingVectors[6].x = minPoint.x;
  68532. this._boundingVectors.push(maxPoint.clone());
  68533. this._boundingVectors[7].y = minPoint.y;
  68534. }
  68535. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68536. // Property
  68537. get: function () {
  68538. return this._capacity;
  68539. },
  68540. enumerable: true,
  68541. configurable: true
  68542. });
  68543. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68544. get: function () {
  68545. return this._minPoint;
  68546. },
  68547. enumerable: true,
  68548. configurable: true
  68549. });
  68550. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68551. get: function () {
  68552. return this._maxPoint;
  68553. },
  68554. enumerable: true,
  68555. configurable: true
  68556. });
  68557. // Methods
  68558. OctreeBlock.prototype.addEntry = function (entry) {
  68559. if (this.blocks) {
  68560. for (var index = 0; index < this.blocks.length; index++) {
  68561. var block = this.blocks[index];
  68562. block.addEntry(entry);
  68563. }
  68564. return;
  68565. }
  68566. this._creationFunc(entry, this);
  68567. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68568. this.createInnerBlocks();
  68569. }
  68570. };
  68571. OctreeBlock.prototype.addEntries = function (entries) {
  68572. for (var index = 0; index < entries.length; index++) {
  68573. var mesh = entries[index];
  68574. this.addEntry(mesh);
  68575. }
  68576. };
  68577. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68578. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68579. if (this.blocks) {
  68580. for (var index = 0; index < this.blocks.length; index++) {
  68581. var block = this.blocks[index];
  68582. block.select(frustumPlanes, selection, allowDuplicate);
  68583. }
  68584. return;
  68585. }
  68586. if (allowDuplicate) {
  68587. selection.concat(this.entries);
  68588. }
  68589. else {
  68590. selection.concatWithNoDuplicate(this.entries);
  68591. }
  68592. }
  68593. };
  68594. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68595. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68596. if (this.blocks) {
  68597. for (var index = 0; index < this.blocks.length; index++) {
  68598. var block = this.blocks[index];
  68599. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68600. }
  68601. return;
  68602. }
  68603. if (allowDuplicate) {
  68604. selection.concat(this.entries);
  68605. }
  68606. else {
  68607. selection.concatWithNoDuplicate(this.entries);
  68608. }
  68609. }
  68610. };
  68611. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68612. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68613. if (this.blocks) {
  68614. for (var index = 0; index < this.blocks.length; index++) {
  68615. var block = this.blocks[index];
  68616. block.intersectsRay(ray, selection);
  68617. }
  68618. return;
  68619. }
  68620. selection.concatWithNoDuplicate(this.entries);
  68621. }
  68622. };
  68623. OctreeBlock.prototype.createInnerBlocks = function () {
  68624. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68625. };
  68626. return OctreeBlock;
  68627. }());
  68628. BABYLON.OctreeBlock = OctreeBlock;
  68629. })(BABYLON || (BABYLON = {}));
  68630. //# sourceMappingURL=babylon.octreeBlock.js.map
  68631. var BABYLON;
  68632. (function (BABYLON) {
  68633. var SIMDVector3 = /** @class */ (function () {
  68634. function SIMDVector3() {
  68635. }
  68636. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68637. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68638. };
  68639. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68640. var m = transformation.m;
  68641. var m0 = SIMD.Float32x4.load(m, 0);
  68642. var m1 = SIMD.Float32x4.load(m, 4);
  68643. var m2 = SIMD.Float32x4.load(m, 8);
  68644. var m3 = SIMD.Float32x4.load(m, 12);
  68645. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  68646. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68647. result.x = SIMD.Float32x4.extractLane(r, 0);
  68648. result.y = SIMD.Float32x4.extractLane(r, 1);
  68649. result.z = SIMD.Float32x4.extractLane(r, 2);
  68650. };
  68651. return SIMDVector3;
  68652. }());
  68653. var SIMDMatrix = /** @class */ (function () {
  68654. function SIMDMatrix() {
  68655. }
  68656. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68657. var tm = this.m;
  68658. var om = other.m;
  68659. var m0 = SIMD.Float32x4.load(om, 0);
  68660. var m1 = SIMD.Float32x4.load(om, 4);
  68661. var m2 = SIMD.Float32x4.load(om, 8);
  68662. var m3 = SIMD.Float32x4.load(om, 12);
  68663. for (var i = 0; i < 16; i += 4) {
  68664. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  68665. }
  68666. return this;
  68667. };
  68668. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68669. var src = this.m;
  68670. var dest = other.m;
  68671. // Load the 4 rows
  68672. var src0 = SIMD.Float32x4.load(src, 0);
  68673. var src1 = SIMD.Float32x4.load(src, 4);
  68674. var src2 = SIMD.Float32x4.load(src, 8);
  68675. var src3 = SIMD.Float32x4.load(src, 12);
  68676. // Transpose the source matrix. Sort of. Not a true transpose operation
  68677. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68678. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68679. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68680. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68681. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68682. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68683. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68684. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68685. // This is a true transposition, but it will lead to an incorrect result
  68686. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68687. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68688. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68689. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68690. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68691. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68692. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68693. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68694. // ----
  68695. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68696. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68697. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68698. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68699. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68700. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68701. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68702. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68703. // ----
  68704. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68705. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68706. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68707. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68708. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68709. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68710. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68711. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68712. // ----
  68713. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68714. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68715. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68716. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68717. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68718. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68719. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68720. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68721. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68722. // ----
  68723. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68724. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68725. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68726. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68727. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68728. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68729. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68730. // ----
  68731. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68732. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68733. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68734. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68735. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68736. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68737. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68738. // ----
  68739. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68740. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68741. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68742. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68743. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68744. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68745. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68746. // Compute determinant
  68747. var det = SIMD.Float32x4.mul(row0, minor0);
  68748. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68749. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68750. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68751. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68752. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68753. // These shuffles aren't necessary if the faulty transposition is done
  68754. // up at the top of this function.
  68755. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68756. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68757. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68758. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68759. // Compute final values by multiplying with 1/det
  68760. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68761. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68762. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68763. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68764. return this;
  68765. };
  68766. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68767. var out = result.m;
  68768. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68769. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68770. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68771. // cc.kmVec3Subtract(f, pCenter, pEye);
  68772. var f = SIMD.Float32x4.sub(center, eye);
  68773. // cc.kmVec3Normalize(f, f);
  68774. var tmp = SIMD.Float32x4.mul(f, f);
  68775. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68776. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68777. // cc.kmVec3Assign(up, pUp);
  68778. // cc.kmVec3Normalize(up, up);
  68779. tmp = SIMD.Float32x4.mul(up, up);
  68780. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68781. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68782. // cc.kmVec3Cross(s, f, up);
  68783. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  68784. // cc.kmVec3Normalize(s, s);
  68785. tmp = SIMD.Float32x4.mul(s, s);
  68786. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68787. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68788. // cc.kmVec3Cross(u, s, f);
  68789. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  68790. // cc.kmVec3Normalize(s, s);
  68791. tmp = SIMD.Float32x4.mul(s, s);
  68792. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68793. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68794. var zero = SIMD.Float32x4.splat(0.0);
  68795. s = SIMD.Float32x4.neg(s);
  68796. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68797. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68798. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68799. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68800. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  68801. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68802. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68803. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68804. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68805. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68806. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68807. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68808. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68809. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68810. };
  68811. return SIMDMatrix;
  68812. }());
  68813. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68814. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68815. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68816. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68817. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68818. var SIMDHelper = /** @class */ (function () {
  68819. function SIMDHelper() {
  68820. }
  68821. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68822. get: function () {
  68823. return SIMDHelper._isEnabled;
  68824. },
  68825. enumerable: true,
  68826. configurable: true
  68827. });
  68828. SIMDHelper.DisableSIMD = function () {
  68829. // Replace functions
  68830. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68831. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68832. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68833. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68835. SIMDHelper._isEnabled = false;
  68836. };
  68837. SIMDHelper.EnableSIMD = function () {
  68838. if (self.SIMD === undefined) {
  68839. return;
  68840. }
  68841. // check if polyfills needed
  68842. if (!self.Math.fround) {
  68843. self.Math.fround = (function (array) { return function (x) {
  68844. return array[0] = x, array[0];
  68845. }; })(new Float32Array(1));
  68846. }
  68847. if (!self.Math.imul) {
  68848. self.Math.imul = function (a, b) {
  68849. var ah = (a >>> 16) & 0xffff;
  68850. var al = a & 0xffff;
  68851. var bh = (b >>> 16) & 0xffff;
  68852. var bl = b & 0xffff;
  68853. // the shift by 0 fixes the sign on the high part
  68854. // the final |0 converts the unsigned value into a signed value
  68855. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68856. };
  68857. }
  68858. // Replace functions
  68859. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68860. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68861. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68862. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68863. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68864. SIMDHelper._isEnabled = true;
  68865. };
  68866. SIMDHelper._isEnabled = false;
  68867. return SIMDHelper;
  68868. }());
  68869. BABYLON.SIMDHelper = SIMDHelper;
  68870. })(BABYLON || (BABYLON = {}));
  68871. //# sourceMappingURL=babylon.math.SIMD.js.map
  68872. var BABYLON;
  68873. (function (BABYLON) {
  68874. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68875. __extends(VRDistortionCorrectionPostProcess, _super);
  68876. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68877. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68878. 'LensCenter',
  68879. 'Scale',
  68880. 'ScaleIn',
  68881. 'HmdWarpParam'
  68882. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68883. _this._isRightEye = isRightEye;
  68884. _this._distortionFactors = vrMetrics.distortionK;
  68885. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68886. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68887. _this.adaptScaleToCurrentViewport = true;
  68888. _this.onSizeChangedObservable.add(function () {
  68889. _this.aspectRatio = _this.width * .5 / _this.height;
  68890. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68891. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68892. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68893. });
  68894. _this.onApplyObservable.add(function (effect) {
  68895. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68896. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68897. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68898. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68899. });
  68900. return _this;
  68901. }
  68902. return VRDistortionCorrectionPostProcess;
  68903. }(BABYLON.PostProcess));
  68904. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68905. })(BABYLON || (BABYLON = {}));
  68906. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68907. var BABYLON;
  68908. (function (BABYLON) {
  68909. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68910. __extends(AnaglyphPostProcess, _super);
  68911. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68912. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  68913. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68914. _this.onApplyObservable.add(function (effect) {
  68915. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  68916. });
  68917. return _this;
  68918. }
  68919. return AnaglyphPostProcess;
  68920. }(BABYLON.PostProcess));
  68921. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  68922. })(BABYLON || (BABYLON = {}));
  68923. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  68924. var BABYLON;
  68925. (function (BABYLON) {
  68926. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  68927. __extends(StereoscopicInterlacePostProcess, _super);
  68928. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  68929. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  68930. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68931. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68932. _this.onSizeChangedObservable.add(function () {
  68933. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68934. });
  68935. _this.onApplyObservable.add(function (effect) {
  68936. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  68937. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  68938. });
  68939. return _this;
  68940. }
  68941. return StereoscopicInterlacePostProcess;
  68942. }(BABYLON.PostProcess));
  68943. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  68944. })(BABYLON || (BABYLON = {}));
  68945. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  68946. var BABYLON;
  68947. (function (BABYLON) {
  68948. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  68949. function FreeCameraDeviceOrientationInput() {
  68950. var _this = this;
  68951. this._screenOrientationAngle = 0;
  68952. this._screenQuaternion = new BABYLON.Quaternion();
  68953. this._alpha = 0;
  68954. this._beta = 0;
  68955. this._gamma = 0;
  68956. this._orientationChanged = function () {
  68957. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  68958. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  68959. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  68960. };
  68961. this._deviceOrientation = function (evt) {
  68962. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  68963. _this._beta = evt.beta !== null ? evt.beta : 0;
  68964. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68965. };
  68966. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68967. this._orientationChanged();
  68968. }
  68969. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68970. get: function () {
  68971. return this._camera;
  68972. },
  68973. set: function (camera) {
  68974. this._camera = camera;
  68975. if (this._camera != null && !this._camera.rotationQuaternion) {
  68976. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68977. }
  68978. },
  68979. enumerable: true,
  68980. configurable: true
  68981. });
  68982. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68983. window.addEventListener("orientationchange", this._orientationChanged);
  68984. window.addEventListener("deviceorientation", this._deviceOrientation);
  68985. //In certain cases, the attach control is called AFTER orientation was changed,
  68986. //So this is needed.
  68987. this._orientationChanged();
  68988. };
  68989. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68990. window.removeEventListener("orientationchange", this._orientationChanged);
  68991. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68992. };
  68993. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68994. //if no device orientation provided, don't update the rotation.
  68995. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68996. if (!this._alpha)
  68997. return;
  68998. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68999. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69000. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69001. //Mirror on XY Plane
  69002. this._camera.rotationQuaternion.z *= -1;
  69003. this._camera.rotationQuaternion.w *= -1;
  69004. };
  69005. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69006. return "FreeCameraDeviceOrientationInput";
  69007. };
  69008. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69009. return "deviceOrientation";
  69010. };
  69011. return FreeCameraDeviceOrientationInput;
  69012. }());
  69013. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69014. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69015. })(BABYLON || (BABYLON = {}));
  69016. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69017. var BABYLON;
  69018. (function (BABYLON) {
  69019. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69020. function ArcRotateCameraVRDeviceOrientationInput() {
  69021. this.alphaCorrection = 1;
  69022. this.betaCorrection = 1;
  69023. this.gammaCorrection = 1;
  69024. this._alpha = 0;
  69025. this._beta = 0;
  69026. this._gamma = 0;
  69027. this._dirty = false;
  69028. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69029. }
  69030. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69031. this.camera.attachControl(element, noPreventDefault);
  69032. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69033. };
  69034. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69035. if (evt.alpha !== null) {
  69036. this._alpha = +evt.alpha | 0;
  69037. }
  69038. if (evt.beta !== null) {
  69039. this._beta = +evt.beta | 0;
  69040. }
  69041. if (evt.gamma !== null) {
  69042. this._gamma = +evt.gamma | 0;
  69043. }
  69044. this._dirty = true;
  69045. };
  69046. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69047. if (this._dirty) {
  69048. this._dirty = false;
  69049. if (this._gamma < 0) {
  69050. this._gamma = 180 + this._gamma;
  69051. }
  69052. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69053. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69054. }
  69055. };
  69056. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69057. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69058. };
  69059. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69060. return "ArcRotateCameraVRDeviceOrientationInput";
  69061. };
  69062. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69063. return "VRDeviceOrientation";
  69064. };
  69065. return ArcRotateCameraVRDeviceOrientationInput;
  69066. }());
  69067. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69068. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69069. })(BABYLON || (BABYLON = {}));
  69070. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69071. var BABYLON;
  69072. (function (BABYLON) {
  69073. var VRCameraMetrics = /** @class */ (function () {
  69074. function VRCameraMetrics() {
  69075. this.compensateDistortion = true;
  69076. }
  69077. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69078. get: function () {
  69079. return this.hResolution / (2 * this.vResolution);
  69080. },
  69081. enumerable: true,
  69082. configurable: true
  69083. });
  69084. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69085. get: function () {
  69086. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69087. },
  69088. enumerable: true,
  69089. configurable: true
  69090. });
  69091. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69092. get: function () {
  69093. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69094. var h = (4 * meters) / this.hScreenSize;
  69095. return BABYLON.Matrix.Translation(h, 0, 0);
  69096. },
  69097. enumerable: true,
  69098. configurable: true
  69099. });
  69100. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69101. get: function () {
  69102. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69103. var h = (4 * meters) / this.hScreenSize;
  69104. return BABYLON.Matrix.Translation(-h, 0, 0);
  69105. },
  69106. enumerable: true,
  69107. configurable: true
  69108. });
  69109. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69110. get: function () {
  69111. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69112. },
  69113. enumerable: true,
  69114. configurable: true
  69115. });
  69116. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69117. get: function () {
  69118. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69119. },
  69120. enumerable: true,
  69121. configurable: true
  69122. });
  69123. VRCameraMetrics.GetDefault = function () {
  69124. var result = new VRCameraMetrics();
  69125. result.hResolution = 1280;
  69126. result.vResolution = 800;
  69127. result.hScreenSize = 0.149759993;
  69128. result.vScreenSize = 0.0935999975;
  69129. result.vScreenCenter = 0.0467999987;
  69130. result.eyeToScreenDistance = 0.0410000011;
  69131. result.lensSeparationDistance = 0.0635000020;
  69132. result.interpupillaryDistance = 0.0640000030;
  69133. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69134. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69135. result.postProcessScaleFactor = 1.714605507808412;
  69136. result.lensCenterOffset = 0.151976421;
  69137. return result;
  69138. };
  69139. return VRCameraMetrics;
  69140. }());
  69141. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69142. })(BABYLON || (BABYLON = {}));
  69143. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69144. var BABYLON;
  69145. (function (BABYLON) {
  69146. var WebVRFreeCamera = /** @class */ (function (_super) {
  69147. __extends(WebVRFreeCamera, _super);
  69148. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69149. if (webVROptions === void 0) { webVROptions = {}; }
  69150. var _this = _super.call(this, name, position, scene) || this;
  69151. _this.webVROptions = webVROptions;
  69152. _this._vrDevice = null;
  69153. _this.rawPose = null;
  69154. _this._specsVersion = "1.1";
  69155. _this._attached = false;
  69156. _this._descendants = [];
  69157. _this.devicePosition = BABYLON.Vector3.Zero();
  69158. _this.deviceScaleFactor = 1;
  69159. _this.controllers = [];
  69160. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69161. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69162. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69163. _this.minZ = 0.1;
  69164. //legacy support - the compensation boolean was removed.
  69165. if (arguments.length === 5) {
  69166. _this.webVROptions = arguments[4];
  69167. }
  69168. // default webVR options
  69169. if (_this.webVROptions.trackPosition == undefined) {
  69170. _this.webVROptions.trackPosition = true;
  69171. }
  69172. if (_this.webVROptions.controllerMeshes == undefined) {
  69173. _this.webVROptions.controllerMeshes = true;
  69174. }
  69175. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69176. _this.webVROptions.defaultLightingOnControllers = true;
  69177. }
  69178. _this.rotationQuaternion = new BABYLON.Quaternion();
  69179. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69180. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69181. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69182. }
  69183. //enable VR
  69184. var engine = _this.getEngine();
  69185. _this._onVREnabled = function (success) { if (success) {
  69186. _this.initControllers();
  69187. } };
  69188. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69189. engine.initWebVR().add(function (event) {
  69190. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69191. return;
  69192. }
  69193. _this._vrDevice = event.vrDisplay;
  69194. //reset the rig parameters.
  69195. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69196. if (_this._attached) {
  69197. _this.getEngine().enableVR();
  69198. }
  69199. });
  69200. if (typeof (VRFrameData) !== "undefined")
  69201. _this._frameData = new VRFrameData();
  69202. /**
  69203. * The idea behind the following lines:
  69204. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69205. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69206. * the second will not show it correctly.
  69207. *
  69208. * To solve this - each object that has the camera as parent will be added to a protected array.
  69209. * When the rig camera renders, it will take this array and set all of those to be its children.
  69210. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69211. * Amazing!
  69212. */
  69213. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69214. if (camera.parent === _this && _this.rigParenting) {
  69215. _this._descendants = _this.getDescendants(true, function (n) {
  69216. // don't take the cameras or the controllers!
  69217. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69218. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69219. return !isController && !isRigCamera;
  69220. });
  69221. _this._descendants.forEach(function (node) {
  69222. node.parent = camera;
  69223. });
  69224. }
  69225. });
  69226. scene.onAfterCameraRenderObservable.add(function (camera) {
  69227. if (camera.parent === _this && _this.rigParenting) {
  69228. _this._descendants.forEach(function (node) {
  69229. node.parent = _this;
  69230. });
  69231. }
  69232. });
  69233. return _this;
  69234. }
  69235. WebVRFreeCamera.prototype.dispose = function () {
  69236. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69237. _super.prototype.dispose.call(this);
  69238. };
  69239. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69240. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69241. var gp = _a[_i];
  69242. if (gp.hand === name) {
  69243. return gp;
  69244. }
  69245. }
  69246. return null;
  69247. };
  69248. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69249. get: function () {
  69250. if (!this._leftController) {
  69251. this._leftController = this.getControllerByName("left");
  69252. }
  69253. return this._leftController;
  69254. },
  69255. enumerable: true,
  69256. configurable: true
  69257. });
  69258. ;
  69259. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69260. get: function () {
  69261. if (!this._rightController) {
  69262. this._rightController = this.getControllerByName("right");
  69263. }
  69264. return this._rightController;
  69265. },
  69266. enumerable: true,
  69267. configurable: true
  69268. });
  69269. ;
  69270. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69271. if (length === void 0) { length = 100; }
  69272. if (this.leftCamera) {
  69273. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69274. }
  69275. else {
  69276. return _super.prototype.getForwardRay.call(this, length);
  69277. }
  69278. };
  69279. WebVRFreeCamera.prototype._checkInputs = function () {
  69280. if (this._vrDevice && this._vrDevice.isPresenting) {
  69281. this._vrDevice.getFrameData(this._frameData);
  69282. this.updateFromDevice(this._frameData.pose);
  69283. }
  69284. _super.prototype._checkInputs.call(this);
  69285. };
  69286. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69287. if (poseData && poseData.orientation) {
  69288. this.rawPose = poseData;
  69289. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69290. if (this.getScene().useRightHandedSystem) {
  69291. this.deviceRotationQuaternion.z *= -1;
  69292. this.deviceRotationQuaternion.w *= -1;
  69293. }
  69294. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69295. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69296. if (this.getScene().useRightHandedSystem) {
  69297. this.devicePosition.z *= -1;
  69298. }
  69299. }
  69300. }
  69301. };
  69302. /**
  69303. * WebVR's attach control will start broadcasting frames to the device.
  69304. * Note that in certain browsers (chrome for example) this function must be called
  69305. * within a user-interaction callback. Example:
  69306. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69307. *
  69308. * @param {HTMLElement} element
  69309. * @param {boolean} [noPreventDefault]
  69310. *
  69311. * @memberOf WebVRFreeCamera
  69312. */
  69313. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69314. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69315. this._attached = true;
  69316. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69317. if (this._vrDevice) {
  69318. this.getEngine().enableVR();
  69319. }
  69320. };
  69321. WebVRFreeCamera.prototype.detachControl = function (element) {
  69322. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69323. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69324. _super.prototype.detachControl.call(this, element);
  69325. this._attached = false;
  69326. this.getEngine().disableVR();
  69327. };
  69328. WebVRFreeCamera.prototype.getClassName = function () {
  69329. return "WebVRFreeCamera";
  69330. };
  69331. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69332. //uses the vrDisplay's "resetPose()".
  69333. //pitch and roll won't be affected.
  69334. this._vrDevice.resetPose();
  69335. };
  69336. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69337. var camLeft = this._rigCameras[0];
  69338. var camRight = this._rigCameras[1];
  69339. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69340. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69341. camLeft.position.copyFrom(this.devicePosition);
  69342. camRight.position.copyFrom(this.devicePosition);
  69343. };
  69344. /**
  69345. * This function is called by the two RIG cameras.
  69346. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69347. */
  69348. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69349. var _this = this;
  69350. //WebVR 1.1
  69351. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69352. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69353. if (!this.getScene().useRightHandedSystem) {
  69354. [2, 6, 8, 9, 14].forEach(function (num) {
  69355. _this._webvrViewMatrix.m[num] *= -1;
  69356. });
  69357. }
  69358. // update the camera rotation matrix
  69359. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69360. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69361. // Computing target and final matrix
  69362. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69363. var parentCamera = this._cameraRigParams["parentCamera"];
  69364. // should the view matrix be updated with scale and position offset?
  69365. if (parentCamera.deviceScaleFactor !== 1) {
  69366. this._webvrViewMatrix.invert();
  69367. // scale the position, if set
  69368. if (parentCamera.deviceScaleFactor) {
  69369. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69370. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69371. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69372. }
  69373. this._webvrViewMatrix.invert();
  69374. }
  69375. return this._webvrViewMatrix;
  69376. };
  69377. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69378. var _this = this;
  69379. var parentCamera = this.parent;
  69380. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69381. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69382. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69383. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69384. //babylon compatible matrix
  69385. if (!this.getScene().useRightHandedSystem) {
  69386. [8, 9, 10, 11].forEach(function (num) {
  69387. _this._projectionMatrix.m[num] *= -1;
  69388. });
  69389. }
  69390. return this._projectionMatrix;
  69391. };
  69392. WebVRFreeCamera.prototype.initControllers = function () {
  69393. var _this = this;
  69394. this.controllers = [];
  69395. var manager = this.getScene().gamepadManager;
  69396. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69397. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69398. var webVrController = gamepad;
  69399. if (webVrController.defaultModel) {
  69400. webVrController.defaultModel.setEnabled(false);
  69401. }
  69402. }
  69403. });
  69404. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69405. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69406. var webVrController_1 = gamepad;
  69407. if (_this.webVROptions.controllerMeshes) {
  69408. if (webVrController_1.defaultModel) {
  69409. webVrController_1.defaultModel.setEnabled(true);
  69410. }
  69411. else {
  69412. // Load the meshes
  69413. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69414. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69415. if (_this.webVROptions.defaultLightingOnControllers) {
  69416. if (!_this._lightOnControllers) {
  69417. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69418. }
  69419. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69420. var children = mesh.getChildren();
  69421. if (children.length !== 0) {
  69422. children.forEach(function (mesh) {
  69423. light.includedOnlyMeshes.push(mesh);
  69424. activateLightOnSubMeshes_1(mesh, light);
  69425. });
  69426. }
  69427. };
  69428. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69429. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69430. }
  69431. });
  69432. }
  69433. }
  69434. webVrController_1.attachToPoseControlledCamera(_this);
  69435. // since this is async - sanity check. Is the controller already stored?
  69436. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69437. //add to the controllers array
  69438. _this.controllers.push(webVrController_1);
  69439. //did we find enough controllers? Great! let the developer know.
  69440. if (_this.controllers.length >= 2) {
  69441. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69442. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69443. // So we're overriding setting left & right manually to be sure
  69444. var firstViveWandDetected = false;
  69445. for (var i = 0; i < _this.controllers.length; i++) {
  69446. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69447. if (!firstViveWandDetected) {
  69448. firstViveWandDetected = true;
  69449. _this.controllers[i].hand = "left";
  69450. }
  69451. else {
  69452. _this.controllers[i].hand = "right";
  69453. }
  69454. }
  69455. }
  69456. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69457. }
  69458. }
  69459. }
  69460. });
  69461. };
  69462. return WebVRFreeCamera;
  69463. }(BABYLON.FreeCamera));
  69464. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69465. })(BABYLON || (BABYLON = {}));
  69466. //# sourceMappingURL=babylon.webVRCamera.js.map
  69467. var BABYLON;
  69468. (function (BABYLON) {
  69469. // We're mainly based on the logic defined into the FreeCamera code
  69470. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69471. __extends(DeviceOrientationCamera, _super);
  69472. function DeviceOrientationCamera(name, position, scene) {
  69473. var _this = _super.call(this, name, position, scene) || this;
  69474. _this._quaternionCache = new BABYLON.Quaternion();
  69475. _this.inputs.addDeviceOrientation();
  69476. return _this;
  69477. }
  69478. DeviceOrientationCamera.prototype.getClassName = function () {
  69479. return "DeviceOrientationCamera";
  69480. };
  69481. DeviceOrientationCamera.prototype._checkInputs = function () {
  69482. _super.prototype._checkInputs.call(this);
  69483. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69484. if (this._initialQuaternion) {
  69485. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69486. }
  69487. };
  69488. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69489. var _this = this;
  69490. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69491. //can only work if this camera has a rotation quaternion already.
  69492. if (!this.rotationQuaternion)
  69493. return;
  69494. if (!this._initialQuaternion) {
  69495. this._initialQuaternion = new BABYLON.Quaternion();
  69496. }
  69497. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69498. ['x', 'y', 'z'].forEach(function (axisName) {
  69499. if (!axis[axisName]) {
  69500. _this._initialQuaternion[axisName] = 0;
  69501. }
  69502. else {
  69503. _this._initialQuaternion[axisName] *= -1;
  69504. }
  69505. });
  69506. this._initialQuaternion.normalize();
  69507. //force rotation update
  69508. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69509. };
  69510. return DeviceOrientationCamera;
  69511. }(BABYLON.FreeCamera));
  69512. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69513. })(BABYLON || (BABYLON = {}));
  69514. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69515. var BABYLON;
  69516. (function (BABYLON) {
  69517. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69518. __extends(VRDeviceOrientationFreeCamera, _super);
  69519. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69520. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69521. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69522. var _this = _super.call(this, name, position, scene) || this;
  69523. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69524. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69525. return _this;
  69526. }
  69527. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69528. return "VRDeviceOrientationFreeCamera";
  69529. };
  69530. return VRDeviceOrientationFreeCamera;
  69531. }(BABYLON.DeviceOrientationCamera));
  69532. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69533. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69534. __extends(VRDeviceOrientationGamepadCamera, _super);
  69535. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69536. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69537. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69538. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69539. _this.inputs.addGamepad();
  69540. return _this;
  69541. }
  69542. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69543. return "VRDeviceOrientationGamepadCamera";
  69544. };
  69545. return VRDeviceOrientationGamepadCamera;
  69546. }(VRDeviceOrientationFreeCamera));
  69547. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69548. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69549. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69550. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69551. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69552. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69553. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69554. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69555. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69556. _this.inputs.addVRDeviceOrientation();
  69557. return _this;
  69558. }
  69559. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69560. return "VRDeviceOrientationArcRotateCamera";
  69561. };
  69562. return VRDeviceOrientationArcRotateCamera;
  69563. }(BABYLON.ArcRotateCamera));
  69564. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69565. })(BABYLON || (BABYLON = {}));
  69566. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69567. var BABYLON;
  69568. (function (BABYLON) {
  69569. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69570. __extends(AnaglyphFreeCamera, _super);
  69571. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69572. var _this = _super.call(this, name, position, scene) || this;
  69573. _this.interaxialDistance = interaxialDistance;
  69574. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69575. return _this;
  69576. }
  69577. AnaglyphFreeCamera.prototype.getClassName = function () {
  69578. return "AnaglyphFreeCamera";
  69579. };
  69580. return AnaglyphFreeCamera;
  69581. }(BABYLON.FreeCamera));
  69582. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69583. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69584. __extends(AnaglyphArcRotateCamera, _super);
  69585. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69586. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69587. _this.interaxialDistance = interaxialDistance;
  69588. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69589. return _this;
  69590. }
  69591. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69592. return "AnaglyphArcRotateCamera";
  69593. };
  69594. return AnaglyphArcRotateCamera;
  69595. }(BABYLON.ArcRotateCamera));
  69596. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69597. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69598. __extends(AnaglyphGamepadCamera, _super);
  69599. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69600. var _this = _super.call(this, name, position, scene) || this;
  69601. _this.interaxialDistance = interaxialDistance;
  69602. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69603. return _this;
  69604. }
  69605. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69606. return "AnaglyphGamepadCamera";
  69607. };
  69608. return AnaglyphGamepadCamera;
  69609. }(BABYLON.GamepadCamera));
  69610. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69611. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69612. __extends(AnaglyphUniversalCamera, _super);
  69613. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69614. var _this = _super.call(this, name, position, scene) || this;
  69615. _this.interaxialDistance = interaxialDistance;
  69616. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69617. return _this;
  69618. }
  69619. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69620. return "AnaglyphUniversalCamera";
  69621. };
  69622. return AnaglyphUniversalCamera;
  69623. }(BABYLON.UniversalCamera));
  69624. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69625. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69626. __extends(StereoscopicFreeCamera, _super);
  69627. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69628. var _this = _super.call(this, name, position, scene) || this;
  69629. _this.interaxialDistance = interaxialDistance;
  69630. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69631. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69632. return _this;
  69633. }
  69634. StereoscopicFreeCamera.prototype.getClassName = function () {
  69635. return "StereoscopicFreeCamera";
  69636. };
  69637. return StereoscopicFreeCamera;
  69638. }(BABYLON.FreeCamera));
  69639. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69640. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69641. __extends(StereoscopicArcRotateCamera, _super);
  69642. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69643. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69644. _this.interaxialDistance = interaxialDistance;
  69645. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69646. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69647. return _this;
  69648. }
  69649. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69650. return "StereoscopicArcRotateCamera";
  69651. };
  69652. return StereoscopicArcRotateCamera;
  69653. }(BABYLON.ArcRotateCamera));
  69654. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69655. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69656. __extends(StereoscopicGamepadCamera, _super);
  69657. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69658. var _this = _super.call(this, name, position, scene) || this;
  69659. _this.interaxialDistance = interaxialDistance;
  69660. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69661. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69662. return _this;
  69663. }
  69664. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69665. return "StereoscopicGamepadCamera";
  69666. };
  69667. return StereoscopicGamepadCamera;
  69668. }(BABYLON.GamepadCamera));
  69669. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69670. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69671. __extends(StereoscopicUniversalCamera, _super);
  69672. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69673. var _this = _super.call(this, name, position, scene) || this;
  69674. _this.interaxialDistance = interaxialDistance;
  69675. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69676. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69677. return _this;
  69678. }
  69679. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69680. return "StereoscopicUniversalCamera";
  69681. };
  69682. return StereoscopicUniversalCamera;
  69683. }(BABYLON.UniversalCamera));
  69684. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69685. })(BABYLON || (BABYLON = {}));
  69686. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69687. var BABYLON;
  69688. (function (BABYLON) {
  69689. var VRExperienceHelper = /** @class */ (function () {
  69690. function VRExperienceHelper(scene, webVROptions) {
  69691. if (webVROptions === void 0) { webVROptions = {}; }
  69692. var _this = this;
  69693. this.webVROptions = webVROptions;
  69694. // Can the system support WebVR, even if a headset isn't plugged in?
  69695. this._webVRsupported = false;
  69696. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69697. this._webVRready = false;
  69698. // Are we waiting for the requestPresent callback to complete?
  69699. this._webVRrequesting = false;
  69700. // Are we presenting to the headset right now?
  69701. this._webVRpresenting = false;
  69702. // Are we presenting in the fullscreen fallback?
  69703. this._fullscreenVRpresenting = false;
  69704. this._scene = scene;
  69705. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69706. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69707. }
  69708. else {
  69709. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69710. if (scene.activeCamera.rotation) {
  69711. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69712. }
  69713. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69714. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69715. }
  69716. this._scene.activeCamera = this._deviceOrientationCamera;
  69717. this._position = this._scene.activeCamera.position;
  69718. this._canvas = scene.getEngine().getRenderingCanvas();
  69719. if (this._canvas) {
  69720. this._scene.activeCamera.attachControl(this._canvas);
  69721. }
  69722. this._btnVR = document.createElement("BUTTON");
  69723. this._btnVR.className = "babylonVRicon";
  69724. this._btnVR.id = "babylonVRiconbtn";
  69725. this._btnVR.title = "Click to switch to VR";
  69726. 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) }";
  69727. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69728. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69729. // css += ".babylonVRicon.vrdisplaysupported { }";
  69730. // css += ".babylonVRicon.vrdisplayready { }";
  69731. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69732. var style = document.createElement('style');
  69733. style.appendChild(document.createTextNode(css));
  69734. document.getElementsByTagName('head')[0].appendChild(style);
  69735. if (this._canvas) {
  69736. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69737. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69738. this._btnVR.addEventListener("click", function () {
  69739. _this.enterVR();
  69740. });
  69741. window.addEventListener("resize", function () {
  69742. if (_this._canvas) {
  69743. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69744. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69745. }
  69746. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69747. _this.exitVR();
  69748. }
  69749. });
  69750. }
  69751. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69752. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69753. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69754. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69755. document.body.appendChild(this._btnVR);
  69756. // Exiting VR mode using 'ESC' key on desktop
  69757. this._onKeyDown = function (event) {
  69758. if (event.keyCode === 27 && _this.isInVRMode()) {
  69759. _this.exitVR();
  69760. }
  69761. };
  69762. document.addEventListener("keydown", this._onKeyDown);
  69763. // Exiting VR mode double tapping the touch screen
  69764. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69765. if (_this.isInVRMode()) {
  69766. _this.exitVR();
  69767. if (_this._fullscreenVRpresenting) {
  69768. _this._scene.getEngine().switchFullscreen(true);
  69769. }
  69770. }
  69771. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69772. // Listen for WebVR display changes
  69773. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69774. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69775. this._onVRRequestPresentStart = function () {
  69776. _this._webVRrequesting = true;
  69777. _this.updateButtonVisibility();
  69778. };
  69779. this._onVRRequestPresentComplete = function (success) {
  69780. _this._webVRrequesting = false;
  69781. _this.updateButtonVisibility();
  69782. };
  69783. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69784. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69785. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69786. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69787. // Create the cameras
  69788. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69789. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69790. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69791. this.updateButtonVisibility();
  69792. }
  69793. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69794. if (this.onControllerMeshLoaded) {
  69795. this.onControllerMeshLoaded(webVRController);
  69796. }
  69797. };
  69798. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69799. if (document.fullscreen !== undefined) {
  69800. this._fullscreenVRpresenting = document.fullscreen;
  69801. }
  69802. else if (document.mozFullScreen !== undefined) {
  69803. this._fullscreenVRpresenting = document.mozFullScreen;
  69804. }
  69805. else if (document.webkitIsFullScreen !== undefined) {
  69806. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69807. }
  69808. else if (document.msIsFullScreen !== undefined) {
  69809. this._fullscreenVRpresenting = document.msIsFullScreen;
  69810. }
  69811. if (!this._fullscreenVRpresenting && this._canvas) {
  69812. this.exitVR();
  69813. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69814. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69815. }
  69816. };
  69817. VRExperienceHelper.prototype.isInVRMode = function () {
  69818. return this._webVRpresenting || this._fullscreenVRpresenting;
  69819. };
  69820. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69821. var vrDisplay = this._scene.getEngine().getVRDevice();
  69822. if (vrDisplay) {
  69823. var wasPresenting = this._webVRpresenting;
  69824. // A VR display is connected
  69825. this._webVRpresenting = vrDisplay.isPresenting;
  69826. if (wasPresenting && !this._webVRpresenting)
  69827. this.exitVR();
  69828. }
  69829. else {
  69830. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69831. }
  69832. this.updateButtonVisibility();
  69833. };
  69834. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69835. this._webVRsupported = eventArgs.vrSupported;
  69836. this._webVRready = !!eventArgs.vrDisplay;
  69837. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69838. this.updateButtonVisibility();
  69839. };
  69840. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69841. if (!this._btnVR) {
  69842. return;
  69843. }
  69844. this._btnVR.className = "babylonVRicon";
  69845. if (this.isInVRMode()) {
  69846. this._btnVR.className += " vrdisplaypresenting";
  69847. }
  69848. else {
  69849. if (this._webVRready)
  69850. this._btnVR.className += " vrdisplayready";
  69851. if (this._webVRsupported)
  69852. this._btnVR.className += " vrdisplaysupported";
  69853. if (this._webVRrequesting)
  69854. this._btnVR.className += " vrdisplayrequesting";
  69855. }
  69856. };
  69857. /**
  69858. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69859. * Otherwise, will use the fullscreen API.
  69860. */
  69861. VRExperienceHelper.prototype.enterVR = function () {
  69862. if (this.onEnteringVR) {
  69863. this.onEnteringVR();
  69864. }
  69865. if (this._webVRrequesting)
  69866. return;
  69867. // If WebVR is supported and a headset is connected
  69868. if (this._webVRready) {
  69869. if (!this._webVRpresenting) {
  69870. this._webVRCamera.position = this._position;
  69871. this._scene.activeCamera = this._webVRCamera;
  69872. }
  69873. }
  69874. else {
  69875. this._vrDeviceOrientationCamera.position = this._position;
  69876. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69877. this._scene.getEngine().switchFullscreen(true);
  69878. this.updateButtonVisibility();
  69879. }
  69880. if (this._scene.activeCamera && this._canvas) {
  69881. this._scene.activeCamera.attachControl(this._canvas);
  69882. }
  69883. };
  69884. /**
  69885. * Attempt to exit VR, or fullscreen.
  69886. */
  69887. VRExperienceHelper.prototype.exitVR = function () {
  69888. if (this.onExitingVR) {
  69889. this.onExitingVR();
  69890. }
  69891. if (this._webVRpresenting) {
  69892. this._scene.getEngine().disableVR();
  69893. }
  69894. if (this._scene.activeCamera) {
  69895. this._position = this._scene.activeCamera.position;
  69896. }
  69897. this._deviceOrientationCamera.position = this._position;
  69898. this._scene.activeCamera = this._deviceOrientationCamera;
  69899. if (this._canvas) {
  69900. this._scene.activeCamera.attachControl(this._canvas);
  69901. }
  69902. this.updateButtonVisibility();
  69903. };
  69904. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69905. get: function () {
  69906. return this._position;
  69907. },
  69908. set: function (value) {
  69909. this._position = value;
  69910. if (this._scene.activeCamera) {
  69911. this._scene.activeCamera.position = value;
  69912. }
  69913. },
  69914. enumerable: true,
  69915. configurable: true
  69916. });
  69917. VRExperienceHelper.prototype.dispose = function () {
  69918. if (this.isInVRMode()) {
  69919. this.exitVR();
  69920. }
  69921. this._deviceOrientationCamera.dispose();
  69922. if (this._webVRCamera) {
  69923. this._webVRCamera.dispose();
  69924. }
  69925. if (this._vrDeviceOrientationCamera) {
  69926. this._vrDeviceOrientationCamera.dispose();
  69927. }
  69928. document.body.removeChild(this._btnVR);
  69929. document.removeEventListener("keydown", this._onKeyDown);
  69930. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69931. };
  69932. VRExperienceHelper.prototype.getClassName = function () {
  69933. return "VRExperienceHelper";
  69934. };
  69935. return VRExperienceHelper;
  69936. }());
  69937. BABYLON.VRExperienceHelper = VRExperienceHelper;
  69938. })(BABYLON || (BABYLON = {}));
  69939. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  69940. // Mainly based on these 2 articles :
  69941. // 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
  69942. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  69943. var BABYLON;
  69944. (function (BABYLON) {
  69945. var JoystickAxis;
  69946. (function (JoystickAxis) {
  69947. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  69948. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  69949. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  69950. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  69951. var VirtualJoystick = /** @class */ (function () {
  69952. function VirtualJoystick(leftJoystick) {
  69953. var _this = this;
  69954. if (leftJoystick) {
  69955. this._leftJoystick = true;
  69956. }
  69957. else {
  69958. this._leftJoystick = false;
  69959. }
  69960. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69961. VirtualJoystick._globalJoystickIndex++;
  69962. // By default left & right arrow keys are moving the X
  69963. // and up & down keys are moving the Y
  69964. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69965. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69966. this.reverseLeftRight = false;
  69967. this.reverseUpDown = false;
  69968. // collections of pointers
  69969. this._touches = new BABYLON.StringDictionary();
  69970. this.deltaPosition = BABYLON.Vector3.Zero();
  69971. this._joystickSensibility = 25;
  69972. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69973. this._rotationSpeed = 25;
  69974. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69975. this._rotateOnAxisRelativeToMesh = false;
  69976. this._onResize = function (evt) {
  69977. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69978. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69979. if (VirtualJoystick.vjCanvas) {
  69980. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69981. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69982. }
  69983. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69984. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69985. };
  69986. // injecting a canvas element on top of the canvas 3D game
  69987. if (!VirtualJoystick.vjCanvas) {
  69988. window.addEventListener("resize", this._onResize, false);
  69989. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69990. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69991. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69992. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69993. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69994. VirtualJoystick.vjCanvas.style.width = "100%";
  69995. VirtualJoystick.vjCanvas.style.height = "100%";
  69996. VirtualJoystick.vjCanvas.style.position = "absolute";
  69997. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69998. VirtualJoystick.vjCanvas.style.top = "0px";
  69999. VirtualJoystick.vjCanvas.style.left = "0px";
  70000. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70001. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70002. // Support for jQuery PEP polyfill
  70003. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70004. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70005. if (!context) {
  70006. throw new Error("Unable to create canvas for virtual joystick");
  70007. }
  70008. VirtualJoystick.vjCanvasContext = context;
  70009. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70010. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70011. document.body.appendChild(VirtualJoystick.vjCanvas);
  70012. }
  70013. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70014. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70015. this.pressed = false;
  70016. // default joystick color
  70017. this._joystickColor = "cyan";
  70018. this._joystickPointerID = -1;
  70019. // current joystick position
  70020. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70021. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70022. // origin joystick position
  70023. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70024. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70025. this._onPointerDownHandlerRef = function (evt) {
  70026. _this._onPointerDown(evt);
  70027. };
  70028. this._onPointerMoveHandlerRef = function (evt) {
  70029. _this._onPointerMove(evt);
  70030. };
  70031. this._onPointerOutHandlerRef = function (evt) {
  70032. _this._onPointerUp(evt);
  70033. };
  70034. this._onPointerUpHandlerRef = function (evt) {
  70035. _this._onPointerUp(evt);
  70036. };
  70037. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70038. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70039. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70040. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70041. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70042. evt.preventDefault(); // Disables system menu
  70043. }, false);
  70044. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70045. }
  70046. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70047. this._joystickSensibility = newJoystickSensibility;
  70048. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70049. };
  70050. VirtualJoystick.prototype._onPointerDown = function (e) {
  70051. var positionOnScreenCondition;
  70052. e.preventDefault();
  70053. if (this._leftJoystick === true) {
  70054. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70055. }
  70056. else {
  70057. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70058. }
  70059. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70060. // First contact will be dedicated to the virtual joystick
  70061. this._joystickPointerID = e.pointerId;
  70062. this._joystickPointerStartPos.x = e.clientX;
  70063. this._joystickPointerStartPos.y = e.clientY;
  70064. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70065. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70066. this._deltaJoystickVector.x = 0;
  70067. this._deltaJoystickVector.y = 0;
  70068. this.pressed = true;
  70069. this._touches.add(e.pointerId.toString(), e);
  70070. }
  70071. else {
  70072. // You can only trigger the action buttons with a joystick declared
  70073. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70074. this._action();
  70075. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70076. }
  70077. }
  70078. };
  70079. VirtualJoystick.prototype._onPointerMove = function (e) {
  70080. // If the current pointer is the one associated to the joystick (first touch contact)
  70081. if (this._joystickPointerID == e.pointerId) {
  70082. this._joystickPointerPos.x = e.clientX;
  70083. this._joystickPointerPos.y = e.clientY;
  70084. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70085. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70086. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70087. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70088. switch (this._axisTargetedByLeftAndRight) {
  70089. case JoystickAxis.X:
  70090. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70091. break;
  70092. case JoystickAxis.Y:
  70093. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70094. break;
  70095. case JoystickAxis.Z:
  70096. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70097. break;
  70098. }
  70099. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70100. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70101. switch (this._axisTargetedByUpAndDown) {
  70102. case JoystickAxis.X:
  70103. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70104. break;
  70105. case JoystickAxis.Y:
  70106. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70107. break;
  70108. case JoystickAxis.Z:
  70109. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70110. break;
  70111. }
  70112. }
  70113. else {
  70114. var data = this._touches.get(e.pointerId.toString());
  70115. if (data) {
  70116. data.x = e.clientX;
  70117. data.y = e.clientY;
  70118. }
  70119. }
  70120. };
  70121. VirtualJoystick.prototype._onPointerUp = function (e) {
  70122. if (this._joystickPointerID == e.pointerId) {
  70123. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70124. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70125. this._joystickPointerID = -1;
  70126. this.pressed = false;
  70127. }
  70128. else {
  70129. var touch = this._touches.get(e.pointerId.toString());
  70130. if (touch) {
  70131. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70132. }
  70133. }
  70134. this._deltaJoystickVector.x = 0;
  70135. this._deltaJoystickVector.y = 0;
  70136. this._touches.remove(e.pointerId.toString());
  70137. };
  70138. /**
  70139. * Change the color of the virtual joystick
  70140. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70141. */
  70142. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70143. this._joystickColor = newColor;
  70144. };
  70145. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70146. this._action = action;
  70147. };
  70148. // Define which axis you'd like to control for left & right
  70149. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70150. switch (axis) {
  70151. case JoystickAxis.X:
  70152. case JoystickAxis.Y:
  70153. case JoystickAxis.Z:
  70154. this._axisTargetedByLeftAndRight = axis;
  70155. break;
  70156. default:
  70157. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70158. break;
  70159. }
  70160. };
  70161. // Define which axis you'd like to control for up & down
  70162. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70163. switch (axis) {
  70164. case JoystickAxis.X:
  70165. case JoystickAxis.Y:
  70166. case JoystickAxis.Z:
  70167. this._axisTargetedByUpAndDown = axis;
  70168. break;
  70169. default:
  70170. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70171. break;
  70172. }
  70173. };
  70174. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70175. var _this = this;
  70176. if (this.pressed) {
  70177. this._touches.forEach(function (key, touch) {
  70178. if (touch.pointerId === _this._joystickPointerID) {
  70179. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70180. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70181. VirtualJoystick.vjCanvasContext.beginPath();
  70182. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70183. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70184. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70185. VirtualJoystick.vjCanvasContext.stroke();
  70186. VirtualJoystick.vjCanvasContext.closePath();
  70187. VirtualJoystick.vjCanvasContext.beginPath();
  70188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70189. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70190. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70191. VirtualJoystick.vjCanvasContext.stroke();
  70192. VirtualJoystick.vjCanvasContext.closePath();
  70193. VirtualJoystick.vjCanvasContext.beginPath();
  70194. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70195. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70196. VirtualJoystick.vjCanvasContext.stroke();
  70197. VirtualJoystick.vjCanvasContext.closePath();
  70198. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70199. }
  70200. else {
  70201. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70202. VirtualJoystick.vjCanvasContext.beginPath();
  70203. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70204. VirtualJoystick.vjCanvasContext.beginPath();
  70205. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70206. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70207. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70208. VirtualJoystick.vjCanvasContext.stroke();
  70209. VirtualJoystick.vjCanvasContext.closePath();
  70210. touch.prevX = touch.x;
  70211. touch.prevY = touch.y;
  70212. }
  70213. ;
  70214. });
  70215. }
  70216. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70217. };
  70218. VirtualJoystick.prototype.releaseCanvas = function () {
  70219. if (VirtualJoystick.vjCanvas) {
  70220. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70221. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70222. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70223. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70224. window.removeEventListener("resize", this._onResize);
  70225. document.body.removeChild(VirtualJoystick.vjCanvas);
  70226. VirtualJoystick.vjCanvas = null;
  70227. }
  70228. };
  70229. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70230. VirtualJoystick._globalJoystickIndex = 0;
  70231. return VirtualJoystick;
  70232. }());
  70233. BABYLON.VirtualJoystick = VirtualJoystick;
  70234. })(BABYLON || (BABYLON = {}));
  70235. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70236. var BABYLON;
  70237. (function (BABYLON) {
  70238. // We're mainly based on the logic defined into the FreeCamera code
  70239. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70240. __extends(VirtualJoysticksCamera, _super);
  70241. function VirtualJoysticksCamera(name, position, scene) {
  70242. var _this = _super.call(this, name, position, scene) || this;
  70243. _this.inputs.addVirtualJoystick();
  70244. return _this;
  70245. }
  70246. VirtualJoysticksCamera.prototype.getClassName = function () {
  70247. return "VirtualJoysticksCamera";
  70248. };
  70249. return VirtualJoysticksCamera;
  70250. }(BABYLON.FreeCamera));
  70251. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70252. })(BABYLON || (BABYLON = {}));
  70253. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70254. var BABYLON;
  70255. (function (BABYLON) {
  70256. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70257. function FreeCameraVirtualJoystickInput() {
  70258. }
  70259. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70260. return this._leftjoystick;
  70261. };
  70262. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70263. return this._rightjoystick;
  70264. };
  70265. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70266. if (this._leftjoystick) {
  70267. var camera = this.camera;
  70268. var speed = camera._computeLocalCameraSpeed() * 50;
  70269. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70270. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70271. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70272. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70273. if (!this._leftjoystick.pressed) {
  70274. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70275. }
  70276. if (!this._rightjoystick.pressed) {
  70277. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70278. }
  70279. }
  70280. };
  70281. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70282. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70283. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70284. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70285. this._leftjoystick.setJoystickSensibility(0.15);
  70286. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70287. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70288. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70289. this._rightjoystick.reverseUpDown = true;
  70290. this._rightjoystick.setJoystickSensibility(0.05);
  70291. this._rightjoystick.setJoystickColor("yellow");
  70292. };
  70293. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70294. this._leftjoystick.releaseCanvas();
  70295. this._rightjoystick.releaseCanvas();
  70296. };
  70297. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70298. return "FreeCameraVirtualJoystickInput";
  70299. };
  70300. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70301. return "virtualJoystick";
  70302. };
  70303. return FreeCameraVirtualJoystickInput;
  70304. }());
  70305. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70306. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70307. })(BABYLON || (BABYLON = {}));
  70308. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70309. var BABYLON;
  70310. (function (BABYLON) {
  70311. var SimplificationSettings = /** @class */ (function () {
  70312. function SimplificationSettings(quality, distance, optimizeMesh) {
  70313. this.quality = quality;
  70314. this.distance = distance;
  70315. this.optimizeMesh = optimizeMesh;
  70316. }
  70317. return SimplificationSettings;
  70318. }());
  70319. BABYLON.SimplificationSettings = SimplificationSettings;
  70320. var SimplificationQueue = /** @class */ (function () {
  70321. function SimplificationQueue() {
  70322. this.running = false;
  70323. this._simplificationArray = [];
  70324. }
  70325. SimplificationQueue.prototype.addTask = function (task) {
  70326. this._simplificationArray.push(task);
  70327. };
  70328. SimplificationQueue.prototype.executeNext = function () {
  70329. var task = this._simplificationArray.pop();
  70330. if (task) {
  70331. this.running = true;
  70332. this.runSimplification(task);
  70333. }
  70334. else {
  70335. this.running = false;
  70336. }
  70337. };
  70338. SimplificationQueue.prototype.runSimplification = function (task) {
  70339. var _this = this;
  70340. if (task.parallelProcessing) {
  70341. //parallel simplifier
  70342. task.settings.forEach(function (setting) {
  70343. var simplifier = _this.getSimplifier(task);
  70344. simplifier.simplify(setting, function (newMesh) {
  70345. task.mesh.addLODLevel(setting.distance, newMesh);
  70346. newMesh.isVisible = true;
  70347. //check if it is the last
  70348. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70349. //all done, run the success callback.
  70350. task.successCallback();
  70351. }
  70352. _this.executeNext();
  70353. });
  70354. });
  70355. }
  70356. else {
  70357. //single simplifier.
  70358. var simplifier = this.getSimplifier(task);
  70359. var runDecimation = function (setting, callback) {
  70360. simplifier.simplify(setting, function (newMesh) {
  70361. task.mesh.addLODLevel(setting.distance, newMesh);
  70362. newMesh.isVisible = true;
  70363. //run the next quality level
  70364. callback();
  70365. });
  70366. };
  70367. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70368. runDecimation(task.settings[loop.index], function () {
  70369. loop.executeNext();
  70370. });
  70371. }, function () {
  70372. //execution ended, run the success callback.
  70373. if (task.successCallback) {
  70374. task.successCallback();
  70375. }
  70376. _this.executeNext();
  70377. });
  70378. }
  70379. };
  70380. SimplificationQueue.prototype.getSimplifier = function (task) {
  70381. switch (task.simplificationType) {
  70382. case SimplificationType.QUADRATIC:
  70383. default:
  70384. return new QuadraticErrorSimplification(task.mesh);
  70385. }
  70386. };
  70387. return SimplificationQueue;
  70388. }());
  70389. BABYLON.SimplificationQueue = SimplificationQueue;
  70390. /**
  70391. * The implemented types of simplification.
  70392. * At the moment only Quadratic Error Decimation is implemented.
  70393. */
  70394. var SimplificationType;
  70395. (function (SimplificationType) {
  70396. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70397. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70398. var DecimationTriangle = /** @class */ (function () {
  70399. function DecimationTriangle(vertices) {
  70400. this.vertices = vertices;
  70401. this.error = new Array(4);
  70402. this.deleted = false;
  70403. this.isDirty = false;
  70404. this.deletePending = false;
  70405. this.borderFactor = 0;
  70406. }
  70407. return DecimationTriangle;
  70408. }());
  70409. BABYLON.DecimationTriangle = DecimationTriangle;
  70410. var DecimationVertex = /** @class */ (function () {
  70411. function DecimationVertex(position, id) {
  70412. this.position = position;
  70413. this.id = id;
  70414. this.isBorder = true;
  70415. this.q = new QuadraticMatrix();
  70416. this.triangleCount = 0;
  70417. this.triangleStart = 0;
  70418. this.originalOffsets = [];
  70419. }
  70420. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70421. this.position.copyFrom(newPosition);
  70422. };
  70423. return DecimationVertex;
  70424. }());
  70425. BABYLON.DecimationVertex = DecimationVertex;
  70426. var QuadraticMatrix = /** @class */ (function () {
  70427. function QuadraticMatrix(data) {
  70428. this.data = new Array(10);
  70429. for (var i = 0; i < 10; ++i) {
  70430. if (data && data[i]) {
  70431. this.data[i] = data[i];
  70432. }
  70433. else {
  70434. this.data[i] = 0;
  70435. }
  70436. }
  70437. }
  70438. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70439. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70440. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70441. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70442. return det;
  70443. };
  70444. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70445. for (var i = 0; i < 10; ++i) {
  70446. this.data[i] += matrix.data[i];
  70447. }
  70448. };
  70449. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70450. for (var i = 0; i < 10; ++i) {
  70451. this.data[i] += data[i];
  70452. }
  70453. };
  70454. QuadraticMatrix.prototype.add = function (matrix) {
  70455. var m = new QuadraticMatrix();
  70456. for (var i = 0; i < 10; ++i) {
  70457. m.data[i] = this.data[i] + matrix.data[i];
  70458. }
  70459. return m;
  70460. };
  70461. QuadraticMatrix.FromData = function (a, b, c, d) {
  70462. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70463. };
  70464. //returning an array to avoid garbage collection
  70465. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70466. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70467. };
  70468. return QuadraticMatrix;
  70469. }());
  70470. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70471. var Reference = /** @class */ (function () {
  70472. function Reference(vertexId, triangleId) {
  70473. this.vertexId = vertexId;
  70474. this.triangleId = triangleId;
  70475. }
  70476. return Reference;
  70477. }());
  70478. BABYLON.Reference = Reference;
  70479. /**
  70480. * An implementation of the Quadratic Error simplification algorithm.
  70481. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70482. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70483. * @author RaananW
  70484. */
  70485. var QuadraticErrorSimplification = /** @class */ (function () {
  70486. function QuadraticErrorSimplification(_mesh) {
  70487. this._mesh = _mesh;
  70488. this.initialized = false;
  70489. this.syncIterations = 5000;
  70490. this.aggressiveness = 7;
  70491. this.decimationIterations = 100;
  70492. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70493. }
  70494. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70495. var _this = this;
  70496. this.initDecimatedMesh();
  70497. //iterating through the submeshes array, one after the other.
  70498. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70499. _this.initWithMesh(loop.index, function () {
  70500. _this.runDecimation(settings, loop.index, function () {
  70501. loop.executeNext();
  70502. });
  70503. }, settings.optimizeMesh);
  70504. }, function () {
  70505. setTimeout(function () {
  70506. successCallback(_this._reconstructedMesh);
  70507. }, 0);
  70508. });
  70509. };
  70510. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70511. var _this = this;
  70512. var targetCount = ~~(this.triangles.length * settings.quality);
  70513. var deletedTriangles = 0;
  70514. var triangleCount = this.triangles.length;
  70515. var iterationFunction = function (iteration, callback) {
  70516. setTimeout(function () {
  70517. if (iteration % 5 === 0) {
  70518. _this.updateMesh(iteration === 0);
  70519. }
  70520. for (var i = 0; i < _this.triangles.length; ++i) {
  70521. _this.triangles[i].isDirty = false;
  70522. }
  70523. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70524. var trianglesIterator = function (i) {
  70525. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70526. var t = _this.triangles[tIdx];
  70527. if (!t)
  70528. return;
  70529. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70530. return;
  70531. }
  70532. for (var j = 0; j < 3; ++j) {
  70533. if (t.error[j] < threshold) {
  70534. var deleted0 = [];
  70535. var deleted1 = [];
  70536. var v0 = t.vertices[j];
  70537. var v1 = t.vertices[(j + 1) % 3];
  70538. if (v0.isBorder || v1.isBorder)
  70539. continue;
  70540. var p = BABYLON.Vector3.Zero();
  70541. var n = BABYLON.Vector3.Zero();
  70542. var uv = BABYLON.Vector2.Zero();
  70543. var color = new BABYLON.Color4(0, 0, 0, 1);
  70544. _this.calculateError(v0, v1, p, n, uv, color);
  70545. var delTr = new Array();
  70546. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70547. continue;
  70548. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70549. continue;
  70550. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70551. continue;
  70552. var uniqueArray = new Array();
  70553. delTr.forEach(function (deletedT) {
  70554. if (uniqueArray.indexOf(deletedT) === -1) {
  70555. deletedT.deletePending = true;
  70556. uniqueArray.push(deletedT);
  70557. }
  70558. });
  70559. if (uniqueArray.length % 2 !== 0) {
  70560. continue;
  70561. }
  70562. v0.q = v1.q.add(v0.q);
  70563. v0.updatePosition(p);
  70564. var tStart = _this.references.length;
  70565. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70566. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70567. var tCount = _this.references.length - tStart;
  70568. if (tCount <= v0.triangleCount) {
  70569. if (tCount) {
  70570. for (var c = 0; c < tCount; c++) {
  70571. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70572. }
  70573. }
  70574. }
  70575. else {
  70576. v0.triangleStart = tStart;
  70577. }
  70578. v0.triangleCount = tCount;
  70579. break;
  70580. }
  70581. }
  70582. };
  70583. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70584. }, 0);
  70585. };
  70586. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70587. if (triangleCount - deletedTriangles <= targetCount)
  70588. loop.breakLoop();
  70589. else {
  70590. iterationFunction(loop.index, function () {
  70591. loop.executeNext();
  70592. });
  70593. }
  70594. }, function () {
  70595. setTimeout(function () {
  70596. //reconstruct this part of the mesh
  70597. _this.reconstructMesh(submeshIndex);
  70598. successCallback();
  70599. }, 0);
  70600. });
  70601. };
  70602. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70603. var _this = this;
  70604. this.vertices = [];
  70605. this.triangles = [];
  70606. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70607. var indices = this._mesh.getIndices();
  70608. var submesh = this._mesh.subMeshes[submeshIndex];
  70609. var findInVertices = function (positionToSearch) {
  70610. if (optimizeMesh) {
  70611. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70612. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70613. return _this.vertices[ii];
  70614. }
  70615. }
  70616. }
  70617. return null;
  70618. };
  70619. var vertexReferences = [];
  70620. var vertexInit = function (i) {
  70621. if (!positionData) {
  70622. return;
  70623. }
  70624. var offset = i + submesh.verticesStart;
  70625. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70626. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70627. vertex.originalOffsets.push(offset);
  70628. if (vertex.id === _this.vertices.length) {
  70629. _this.vertices.push(vertex);
  70630. }
  70631. vertexReferences.push(vertex.id);
  70632. };
  70633. //var totalVertices = mesh.getTotalVertices();
  70634. var totalVertices = submesh.verticesCount;
  70635. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70636. var indicesInit = function (i) {
  70637. if (!indices) {
  70638. return;
  70639. }
  70640. var offset = (submesh.indexStart / 3) + i;
  70641. var pos = (offset * 3);
  70642. var i0 = indices[pos + 0];
  70643. var i1 = indices[pos + 1];
  70644. var i2 = indices[pos + 2];
  70645. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70646. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70647. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70648. var triangle = new DecimationTriangle([v0, v1, v2]);
  70649. triangle.originalOffset = pos;
  70650. _this.triangles.push(triangle);
  70651. };
  70652. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70653. _this.init(callback);
  70654. });
  70655. });
  70656. };
  70657. QuadraticErrorSimplification.prototype.init = function (callback) {
  70658. var _this = this;
  70659. var triangleInit1 = function (i) {
  70660. var t = _this.triangles[i];
  70661. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70662. for (var j = 0; j < 3; j++) {
  70663. 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))));
  70664. }
  70665. };
  70666. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70667. var triangleInit2 = function (i) {
  70668. var t = _this.triangles[i];
  70669. for (var j = 0; j < 3; ++j) {
  70670. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70671. }
  70672. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70673. };
  70674. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70675. _this.initialized = true;
  70676. callback();
  70677. });
  70678. });
  70679. };
  70680. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70681. var newTriangles = [];
  70682. var i;
  70683. for (i = 0; i < this.vertices.length; ++i) {
  70684. this.vertices[i].triangleCount = 0;
  70685. }
  70686. var t;
  70687. var j;
  70688. for (i = 0; i < this.triangles.length; ++i) {
  70689. if (!this.triangles[i].deleted) {
  70690. t = this.triangles[i];
  70691. for (j = 0; j < 3; ++j) {
  70692. t.vertices[j].triangleCount = 1;
  70693. }
  70694. newTriangles.push(t);
  70695. }
  70696. }
  70697. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70698. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70699. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70700. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70701. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70702. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70703. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70704. var vertexCount = 0;
  70705. for (i = 0; i < this.vertices.length; ++i) {
  70706. var vertex = this.vertices[i];
  70707. vertex.id = vertexCount;
  70708. if (vertex.triangleCount) {
  70709. vertex.originalOffsets.forEach(function (originalOffset) {
  70710. if (!normalData) {
  70711. return;
  70712. }
  70713. newPositionData.push(vertex.position.x);
  70714. newPositionData.push(vertex.position.y);
  70715. newPositionData.push(vertex.position.z);
  70716. newNormalData.push(normalData[originalOffset * 3]);
  70717. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70718. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70719. if (uvs && uvs.length) {
  70720. newUVsData.push(uvs[(originalOffset * 2)]);
  70721. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70722. }
  70723. else if (colorsData && colorsData.length) {
  70724. newColorsData.push(colorsData[(originalOffset * 4)]);
  70725. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70726. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70727. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70728. }
  70729. ++vertexCount;
  70730. });
  70731. }
  70732. }
  70733. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70734. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70735. var submeshesArray = this._reconstructedMesh.subMeshes;
  70736. this._reconstructedMesh.subMeshes = [];
  70737. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70738. var originalIndices = this._mesh.getIndices();
  70739. for (i = 0; i < newTriangles.length; ++i) {
  70740. t = newTriangles[i]; //now get the new referencing point for each vertex
  70741. [0, 1, 2].forEach(function (idx) {
  70742. var id = originalIndices[t.originalOffset + idx];
  70743. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70744. if (offset < 0)
  70745. offset = 0;
  70746. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70747. });
  70748. }
  70749. //overwriting the old vertex buffers and indices.
  70750. this._reconstructedMesh.setIndices(newIndicesArray);
  70751. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70752. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70753. if (newUVsData.length > 0)
  70754. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70755. if (newColorsData.length > 0)
  70756. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70757. //create submesh
  70758. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70759. if (submeshIndex > 0) {
  70760. this._reconstructedMesh.subMeshes = [];
  70761. submeshesArray.forEach(function (submesh) {
  70762. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70763. });
  70764. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70765. }
  70766. };
  70767. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70768. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70769. this._reconstructedMesh.material = this._mesh.material;
  70770. this._reconstructedMesh.parent = this._mesh.parent;
  70771. this._reconstructedMesh.isVisible = false;
  70772. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70773. };
  70774. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70775. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70776. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70777. if (t.deleted)
  70778. continue;
  70779. var s = this.references[vertex1.triangleStart + i].vertexId;
  70780. var v1 = t.vertices[(s + 1) % 3];
  70781. var v2 = t.vertices[(s + 2) % 3];
  70782. if ((v1 === vertex2 || v2 === vertex2)) {
  70783. deletedArray[i] = true;
  70784. delTr.push(t);
  70785. continue;
  70786. }
  70787. var d1 = v1.position.subtract(point);
  70788. d1 = d1.normalize();
  70789. var d2 = v2.position.subtract(point);
  70790. d2 = d2.normalize();
  70791. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70792. return true;
  70793. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70794. deletedArray[i] = false;
  70795. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70796. return true;
  70797. }
  70798. return false;
  70799. };
  70800. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70801. var newDeleted = deletedTriangles;
  70802. for (var i = 0; i < vertex.triangleCount; ++i) {
  70803. var ref = this.references[vertex.triangleStart + i];
  70804. var t = this.triangles[ref.triangleId];
  70805. if (t.deleted)
  70806. continue;
  70807. if (deletedArray[i] && t.deletePending) {
  70808. t.deleted = true;
  70809. newDeleted++;
  70810. continue;
  70811. }
  70812. t.vertices[ref.vertexId] = origVertex;
  70813. t.isDirty = true;
  70814. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70815. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70816. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70817. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70818. this.references.push(ref);
  70819. }
  70820. return newDeleted;
  70821. };
  70822. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70823. for (var i = 0; i < this.vertices.length; ++i) {
  70824. var vCount = [];
  70825. var vId = [];
  70826. var v = this.vertices[i];
  70827. var j;
  70828. for (j = 0; j < v.triangleCount; ++j) {
  70829. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70830. for (var ii = 0; ii < 3; ii++) {
  70831. var ofs = 0;
  70832. var vv = triangle.vertices[ii];
  70833. while (ofs < vCount.length) {
  70834. if (vId[ofs] === vv.id)
  70835. break;
  70836. ++ofs;
  70837. }
  70838. if (ofs === vCount.length) {
  70839. vCount.push(1);
  70840. vId.push(vv.id);
  70841. }
  70842. else {
  70843. vCount[ofs]++;
  70844. }
  70845. }
  70846. }
  70847. for (j = 0; j < vCount.length; ++j) {
  70848. if (vCount[j] === 1) {
  70849. this.vertices[vId[j]].isBorder = true;
  70850. }
  70851. else {
  70852. this.vertices[vId[j]].isBorder = false;
  70853. }
  70854. }
  70855. }
  70856. };
  70857. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70858. if (identifyBorders === void 0) { identifyBorders = false; }
  70859. var i;
  70860. if (!identifyBorders) {
  70861. var newTrianglesVector = [];
  70862. for (i = 0; i < this.triangles.length; ++i) {
  70863. if (!this.triangles[i].deleted) {
  70864. newTrianglesVector.push(this.triangles[i]);
  70865. }
  70866. }
  70867. this.triangles = newTrianglesVector;
  70868. }
  70869. for (i = 0; i < this.vertices.length; ++i) {
  70870. this.vertices[i].triangleCount = 0;
  70871. this.vertices[i].triangleStart = 0;
  70872. }
  70873. var t;
  70874. var j;
  70875. var v;
  70876. for (i = 0; i < this.triangles.length; ++i) {
  70877. t = this.triangles[i];
  70878. for (j = 0; j < 3; ++j) {
  70879. v = t.vertices[j];
  70880. v.triangleCount++;
  70881. }
  70882. }
  70883. var tStart = 0;
  70884. for (i = 0; i < this.vertices.length; ++i) {
  70885. this.vertices[i].triangleStart = tStart;
  70886. tStart += this.vertices[i].triangleCount;
  70887. this.vertices[i].triangleCount = 0;
  70888. }
  70889. var newReferences = new Array(this.triangles.length * 3);
  70890. for (i = 0; i < this.triangles.length; ++i) {
  70891. t = this.triangles[i];
  70892. for (j = 0; j < 3; ++j) {
  70893. v = t.vertices[j];
  70894. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70895. v.triangleCount++;
  70896. }
  70897. }
  70898. this.references = newReferences;
  70899. if (identifyBorders) {
  70900. this.identifyBorder();
  70901. }
  70902. };
  70903. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70904. var x = point.x;
  70905. var y = point.y;
  70906. var z = point.z;
  70907. 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
  70908. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70909. };
  70910. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70911. var q = vertex1.q.add(vertex2.q);
  70912. var border = vertex1.isBorder && vertex2.isBorder;
  70913. var error = 0;
  70914. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  70915. if (qDet !== 0 && !border) {
  70916. if (!pointResult) {
  70917. pointResult = BABYLON.Vector3.Zero();
  70918. }
  70919. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  70920. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  70921. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  70922. error = this.vertexError(q, pointResult);
  70923. }
  70924. else {
  70925. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  70926. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  70927. var error1 = this.vertexError(q, vertex1.position);
  70928. var error2 = this.vertexError(q, vertex2.position);
  70929. var error3 = this.vertexError(q, p3);
  70930. error = Math.min(error1, error2, error3);
  70931. if (error === error1) {
  70932. if (pointResult) {
  70933. pointResult.copyFrom(vertex1.position);
  70934. }
  70935. }
  70936. else if (error === error2) {
  70937. if (pointResult) {
  70938. pointResult.copyFrom(vertex2.position);
  70939. }
  70940. }
  70941. else {
  70942. if (pointResult) {
  70943. pointResult.copyFrom(p3);
  70944. }
  70945. }
  70946. }
  70947. return error;
  70948. };
  70949. return QuadraticErrorSimplification;
  70950. }());
  70951. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  70952. })(BABYLON || (BABYLON = {}));
  70953. //# sourceMappingURL=babylon.meshSimplification.js.map
  70954. var BABYLON;
  70955. (function (BABYLON) {
  70956. var Internals;
  70957. (function (Internals) {
  70958. var MeshLODLevel = /** @class */ (function () {
  70959. function MeshLODLevel(distance, mesh) {
  70960. this.distance = distance;
  70961. this.mesh = mesh;
  70962. }
  70963. return MeshLODLevel;
  70964. }());
  70965. Internals.MeshLODLevel = MeshLODLevel;
  70966. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70967. })(BABYLON || (BABYLON = {}));
  70968. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70969. var BABYLON;
  70970. (function (BABYLON) {
  70971. // Standard optimizations
  70972. var SceneOptimization = /** @class */ (function () {
  70973. function SceneOptimization(priority) {
  70974. if (priority === void 0) { priority = 0; }
  70975. this.priority = priority;
  70976. this.apply = function (scene) {
  70977. return true; // Return true if everything that can be done was applied
  70978. };
  70979. }
  70980. return SceneOptimization;
  70981. }());
  70982. BABYLON.SceneOptimization = SceneOptimization;
  70983. var TextureOptimization = /** @class */ (function (_super) {
  70984. __extends(TextureOptimization, _super);
  70985. function TextureOptimization(priority, maximumSize) {
  70986. if (priority === void 0) { priority = 0; }
  70987. if (maximumSize === void 0) { maximumSize = 1024; }
  70988. var _this = _super.call(this, priority) || this;
  70989. _this.priority = priority;
  70990. _this.maximumSize = maximumSize;
  70991. _this.apply = function (scene) {
  70992. var allDone = true;
  70993. for (var index = 0; index < scene.textures.length; index++) {
  70994. var texture = scene.textures[index];
  70995. if (!texture.canRescale || texture.getContext) {
  70996. continue;
  70997. }
  70998. var currentSize = texture.getSize();
  70999. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71000. if (maxDimension > _this.maximumSize) {
  71001. texture.scale(0.5);
  71002. allDone = false;
  71003. }
  71004. }
  71005. return allDone;
  71006. };
  71007. return _this;
  71008. }
  71009. return TextureOptimization;
  71010. }(SceneOptimization));
  71011. BABYLON.TextureOptimization = TextureOptimization;
  71012. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71013. __extends(HardwareScalingOptimization, _super);
  71014. function HardwareScalingOptimization(priority, maximumScale) {
  71015. if (priority === void 0) { priority = 0; }
  71016. if (maximumScale === void 0) { maximumScale = 2; }
  71017. var _this = _super.call(this, priority) || this;
  71018. _this.priority = priority;
  71019. _this.maximumScale = maximumScale;
  71020. _this._currentScale = 1;
  71021. _this.apply = function (scene) {
  71022. _this._currentScale++;
  71023. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71024. return _this._currentScale >= _this.maximumScale;
  71025. };
  71026. return _this;
  71027. }
  71028. return HardwareScalingOptimization;
  71029. }(SceneOptimization));
  71030. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71031. var ShadowsOptimization = /** @class */ (function (_super) {
  71032. __extends(ShadowsOptimization, _super);
  71033. function ShadowsOptimization() {
  71034. var _this = _super !== null && _super.apply(this, arguments) || this;
  71035. _this.apply = function (scene) {
  71036. scene.shadowsEnabled = false;
  71037. return true;
  71038. };
  71039. return _this;
  71040. }
  71041. return ShadowsOptimization;
  71042. }(SceneOptimization));
  71043. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71044. var PostProcessesOptimization = /** @class */ (function (_super) {
  71045. __extends(PostProcessesOptimization, _super);
  71046. function PostProcessesOptimization() {
  71047. var _this = _super !== null && _super.apply(this, arguments) || this;
  71048. _this.apply = function (scene) {
  71049. scene.postProcessesEnabled = false;
  71050. return true;
  71051. };
  71052. return _this;
  71053. }
  71054. return PostProcessesOptimization;
  71055. }(SceneOptimization));
  71056. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71057. var LensFlaresOptimization = /** @class */ (function (_super) {
  71058. __extends(LensFlaresOptimization, _super);
  71059. function LensFlaresOptimization() {
  71060. var _this = _super !== null && _super.apply(this, arguments) || this;
  71061. _this.apply = function (scene) {
  71062. scene.lensFlaresEnabled = false;
  71063. return true;
  71064. };
  71065. return _this;
  71066. }
  71067. return LensFlaresOptimization;
  71068. }(SceneOptimization));
  71069. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71070. var ParticlesOptimization = /** @class */ (function (_super) {
  71071. __extends(ParticlesOptimization, _super);
  71072. function ParticlesOptimization() {
  71073. var _this = _super !== null && _super.apply(this, arguments) || this;
  71074. _this.apply = function (scene) {
  71075. scene.particlesEnabled = false;
  71076. return true;
  71077. };
  71078. return _this;
  71079. }
  71080. return ParticlesOptimization;
  71081. }(SceneOptimization));
  71082. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71083. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71084. __extends(RenderTargetsOptimization, _super);
  71085. function RenderTargetsOptimization() {
  71086. var _this = _super !== null && _super.apply(this, arguments) || this;
  71087. _this.apply = function (scene) {
  71088. scene.renderTargetsEnabled = false;
  71089. return true;
  71090. };
  71091. return _this;
  71092. }
  71093. return RenderTargetsOptimization;
  71094. }(SceneOptimization));
  71095. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71096. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71097. __extends(MergeMeshesOptimization, _super);
  71098. function MergeMeshesOptimization() {
  71099. var _this = _super !== null && _super.apply(this, arguments) || this;
  71100. _this._canBeMerged = function (abstractMesh) {
  71101. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71102. return false;
  71103. }
  71104. var mesh = abstractMesh;
  71105. if (!mesh.isVisible || !mesh.isEnabled()) {
  71106. return false;
  71107. }
  71108. if (mesh.instances.length > 0) {
  71109. return false;
  71110. }
  71111. if (mesh.skeleton || mesh.hasLODLevels) {
  71112. return false;
  71113. }
  71114. if (mesh.parent) {
  71115. return false;
  71116. }
  71117. return true;
  71118. };
  71119. _this.apply = function (scene, updateSelectionTree) {
  71120. var globalPool = scene.meshes.slice(0);
  71121. var globalLength = globalPool.length;
  71122. for (var index = 0; index < globalLength; index++) {
  71123. var currentPool = new Array();
  71124. var current = globalPool[index];
  71125. // Checks
  71126. if (!_this._canBeMerged(current)) {
  71127. continue;
  71128. }
  71129. currentPool.push(current);
  71130. // Find compatible meshes
  71131. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71132. var otherMesh = globalPool[subIndex];
  71133. if (!_this._canBeMerged(otherMesh)) {
  71134. continue;
  71135. }
  71136. if (otherMesh.material !== current.material) {
  71137. continue;
  71138. }
  71139. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71140. continue;
  71141. }
  71142. currentPool.push(otherMesh);
  71143. globalLength--;
  71144. globalPool.splice(subIndex, 1);
  71145. subIndex--;
  71146. }
  71147. if (currentPool.length < 2) {
  71148. continue;
  71149. }
  71150. // Merge meshes
  71151. BABYLON.Mesh.MergeMeshes(currentPool);
  71152. }
  71153. if (updateSelectionTree != undefined) {
  71154. if (updateSelectionTree) {
  71155. scene.createOrUpdateSelectionOctree();
  71156. }
  71157. }
  71158. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71159. scene.createOrUpdateSelectionOctree();
  71160. }
  71161. return true;
  71162. };
  71163. return _this;
  71164. }
  71165. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71166. get: function () {
  71167. return MergeMeshesOptimization._UpdateSelectionTree;
  71168. },
  71169. set: function (value) {
  71170. MergeMeshesOptimization._UpdateSelectionTree = value;
  71171. },
  71172. enumerable: true,
  71173. configurable: true
  71174. });
  71175. MergeMeshesOptimization._UpdateSelectionTree = false;
  71176. return MergeMeshesOptimization;
  71177. }(SceneOptimization));
  71178. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71179. // Options
  71180. var SceneOptimizerOptions = /** @class */ (function () {
  71181. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71182. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71183. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71184. this.targetFrameRate = targetFrameRate;
  71185. this.trackerDuration = trackerDuration;
  71186. this.optimizations = new Array();
  71187. }
  71188. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71189. var result = new SceneOptimizerOptions(targetFrameRate);
  71190. var priority = 0;
  71191. result.optimizations.push(new MergeMeshesOptimization(priority));
  71192. result.optimizations.push(new ShadowsOptimization(priority));
  71193. result.optimizations.push(new LensFlaresOptimization(priority));
  71194. // Next priority
  71195. priority++;
  71196. result.optimizations.push(new PostProcessesOptimization(priority));
  71197. result.optimizations.push(new ParticlesOptimization(priority));
  71198. // Next priority
  71199. priority++;
  71200. result.optimizations.push(new TextureOptimization(priority, 1024));
  71201. return result;
  71202. };
  71203. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71204. var result = new SceneOptimizerOptions(targetFrameRate);
  71205. var priority = 0;
  71206. result.optimizations.push(new MergeMeshesOptimization(priority));
  71207. result.optimizations.push(new ShadowsOptimization(priority));
  71208. result.optimizations.push(new LensFlaresOptimization(priority));
  71209. // Next priority
  71210. priority++;
  71211. result.optimizations.push(new PostProcessesOptimization(priority));
  71212. result.optimizations.push(new ParticlesOptimization(priority));
  71213. // Next priority
  71214. priority++;
  71215. result.optimizations.push(new TextureOptimization(priority, 512));
  71216. // Next priority
  71217. priority++;
  71218. result.optimizations.push(new RenderTargetsOptimization(priority));
  71219. // Next priority
  71220. priority++;
  71221. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71222. return result;
  71223. };
  71224. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71225. var result = new SceneOptimizerOptions(targetFrameRate);
  71226. var priority = 0;
  71227. result.optimizations.push(new MergeMeshesOptimization(priority));
  71228. result.optimizations.push(new ShadowsOptimization(priority));
  71229. result.optimizations.push(new LensFlaresOptimization(priority));
  71230. // Next priority
  71231. priority++;
  71232. result.optimizations.push(new PostProcessesOptimization(priority));
  71233. result.optimizations.push(new ParticlesOptimization(priority));
  71234. // Next priority
  71235. priority++;
  71236. result.optimizations.push(new TextureOptimization(priority, 256));
  71237. // Next priority
  71238. priority++;
  71239. result.optimizations.push(new RenderTargetsOptimization(priority));
  71240. // Next priority
  71241. priority++;
  71242. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71243. return result;
  71244. };
  71245. return SceneOptimizerOptions;
  71246. }());
  71247. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71248. // Scene optimizer tool
  71249. var SceneOptimizer = /** @class */ (function () {
  71250. function SceneOptimizer() {
  71251. }
  71252. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71253. // TODO: add an epsilon
  71254. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71255. if (onSuccess) {
  71256. onSuccess();
  71257. }
  71258. return;
  71259. }
  71260. // Apply current level of optimizations
  71261. var allDone = true;
  71262. var noOptimizationApplied = true;
  71263. for (var index = 0; index < options.optimizations.length; index++) {
  71264. var optimization = options.optimizations[index];
  71265. if (optimization.priority === currentPriorityLevel) {
  71266. noOptimizationApplied = false;
  71267. allDone = allDone && optimization.apply(scene);
  71268. }
  71269. }
  71270. // If no optimization was applied, this is a failure :(
  71271. if (noOptimizationApplied) {
  71272. if (onFailure) {
  71273. onFailure();
  71274. }
  71275. return;
  71276. }
  71277. // If all optimizations were done, move to next level
  71278. if (allDone) {
  71279. currentPriorityLevel++;
  71280. }
  71281. // Let's the system running for a specific amount of time before checking FPS
  71282. scene.executeWhenReady(function () {
  71283. setTimeout(function () {
  71284. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71285. }, options.trackerDuration);
  71286. });
  71287. };
  71288. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71289. if (!options) {
  71290. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71291. }
  71292. // Let's the system running for a specific amount of time before checking FPS
  71293. scene.executeWhenReady(function () {
  71294. setTimeout(function () {
  71295. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71296. }, options.trackerDuration);
  71297. });
  71298. };
  71299. return SceneOptimizer;
  71300. }());
  71301. BABYLON.SceneOptimizer = SceneOptimizer;
  71302. })(BABYLON || (BABYLON = {}));
  71303. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71304. var BABYLON;
  71305. (function (BABYLON) {
  71306. var OutlineRenderer = /** @class */ (function () {
  71307. function OutlineRenderer(scene) {
  71308. this.zOffset = 1;
  71309. this._scene = scene;
  71310. }
  71311. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71312. var _this = this;
  71313. if (useOverlay === void 0) { useOverlay = false; }
  71314. var scene = this._scene;
  71315. var engine = this._scene.getEngine();
  71316. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71317. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71318. return;
  71319. }
  71320. var mesh = subMesh.getRenderingMesh();
  71321. var material = subMesh.getMaterial();
  71322. if (!material || !scene.activeCamera) {
  71323. return;
  71324. }
  71325. engine.enableEffect(this._effect);
  71326. // Logarithmic depth
  71327. if (material.useLogarithmicDepth) {
  71328. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71329. }
  71330. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71331. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71332. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71333. // Bones
  71334. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71335. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71336. }
  71337. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71338. // Alpha test
  71339. if (material && material.needAlphaTesting()) {
  71340. var alphaTexture = material.getAlphaTestTexture();
  71341. if (alphaTexture) {
  71342. this._effect.setTexture("diffuseSampler", alphaTexture);
  71343. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71344. }
  71345. }
  71346. engine.setZOffset(-this.zOffset);
  71347. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71348. engine.setZOffset(0);
  71349. };
  71350. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71351. var defines = [];
  71352. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71353. var mesh = subMesh.getMesh();
  71354. var material = subMesh.getMaterial();
  71355. if (material) {
  71356. // Alpha test
  71357. if (material.needAlphaTesting()) {
  71358. defines.push("#define ALPHATEST");
  71359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71360. attribs.push(BABYLON.VertexBuffer.UVKind);
  71361. defines.push("#define UV1");
  71362. }
  71363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71365. defines.push("#define UV2");
  71366. }
  71367. }
  71368. //Logarithmic depth
  71369. if (material.useLogarithmicDepth) {
  71370. defines.push("#define LOGARITHMICDEPTH");
  71371. }
  71372. }
  71373. // Bones
  71374. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71377. if (mesh.numBoneInfluencers > 4) {
  71378. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71379. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71380. }
  71381. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71382. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71383. }
  71384. else {
  71385. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71386. }
  71387. // Instances
  71388. if (useInstances) {
  71389. defines.push("#define INSTANCES");
  71390. attribs.push("world0");
  71391. attribs.push("world1");
  71392. attribs.push("world2");
  71393. attribs.push("world3");
  71394. }
  71395. // Get correct effect
  71396. var join = defines.join("\n");
  71397. if (this._cachedDefines !== join) {
  71398. this._cachedDefines = join;
  71399. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71400. }
  71401. return this._effect.isReady();
  71402. };
  71403. return OutlineRenderer;
  71404. }());
  71405. BABYLON.OutlineRenderer = OutlineRenderer;
  71406. })(BABYLON || (BABYLON = {}));
  71407. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71408. var BABYLON;
  71409. (function (BABYLON) {
  71410. var FaceAdjacencies = /** @class */ (function () {
  71411. function FaceAdjacencies() {
  71412. this.edges = new Array();
  71413. this.edgesConnectedCount = 0;
  71414. }
  71415. return FaceAdjacencies;
  71416. }());
  71417. var EdgesRenderer = /** @class */ (function () {
  71418. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71419. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71420. if (epsilon === void 0) { epsilon = 0.95; }
  71421. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71422. this.edgesWidthScalerForOrthographic = 1000.0;
  71423. this.edgesWidthScalerForPerspective = 50.0;
  71424. this._linesPositions = new Array();
  71425. this._linesNormals = new Array();
  71426. this._linesIndices = new Array();
  71427. this._buffers = {};
  71428. this._checkVerticesInsteadOfIndices = false;
  71429. this._source = source;
  71430. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71431. this._epsilon = epsilon;
  71432. this._prepareRessources();
  71433. this._generateEdgesLines();
  71434. }
  71435. EdgesRenderer.prototype._prepareRessources = function () {
  71436. if (this._lineShader) {
  71437. return;
  71438. }
  71439. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71440. attributes: ["position", "normal"],
  71441. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71442. });
  71443. this._lineShader.disableDepthWrite = true;
  71444. this._lineShader.backFaceCulling = false;
  71445. };
  71446. EdgesRenderer.prototype._rebuild = function () {
  71447. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71448. if (buffer) {
  71449. buffer._rebuild();
  71450. }
  71451. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71452. if (buffer) {
  71453. buffer._rebuild();
  71454. }
  71455. var scene = this._source.getScene();
  71456. var engine = scene.getEngine();
  71457. this._ib = engine.createIndexBuffer(this._linesIndices);
  71458. };
  71459. EdgesRenderer.prototype.dispose = function () {
  71460. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71461. if (buffer) {
  71462. buffer.dispose();
  71463. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71464. }
  71465. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71466. if (buffer) {
  71467. buffer.dispose();
  71468. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71469. }
  71470. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71471. this._lineShader.dispose();
  71472. };
  71473. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71474. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71475. return 0;
  71476. }
  71477. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71478. return 1;
  71479. }
  71480. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71481. return 2;
  71482. }
  71483. return -1;
  71484. };
  71485. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71486. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71487. return 0;
  71488. }
  71489. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71490. return 1;
  71491. }
  71492. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71493. return 2;
  71494. }
  71495. return -1;
  71496. };
  71497. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71498. var needToCreateLine;
  71499. if (edge === undefined) {
  71500. needToCreateLine = true;
  71501. }
  71502. else {
  71503. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71504. needToCreateLine = dotProduct < this._epsilon;
  71505. }
  71506. if (needToCreateLine) {
  71507. var offset = this._linesPositions.length / 3;
  71508. var normal = p0.subtract(p1);
  71509. normal.normalize();
  71510. // Positions
  71511. this._linesPositions.push(p0.x);
  71512. this._linesPositions.push(p0.y);
  71513. this._linesPositions.push(p0.z);
  71514. this._linesPositions.push(p0.x);
  71515. this._linesPositions.push(p0.y);
  71516. this._linesPositions.push(p0.z);
  71517. this._linesPositions.push(p1.x);
  71518. this._linesPositions.push(p1.y);
  71519. this._linesPositions.push(p1.z);
  71520. this._linesPositions.push(p1.x);
  71521. this._linesPositions.push(p1.y);
  71522. this._linesPositions.push(p1.z);
  71523. // Normals
  71524. this._linesNormals.push(p1.x);
  71525. this._linesNormals.push(p1.y);
  71526. this._linesNormals.push(p1.z);
  71527. this._linesNormals.push(-1);
  71528. this._linesNormals.push(p1.x);
  71529. this._linesNormals.push(p1.y);
  71530. this._linesNormals.push(p1.z);
  71531. this._linesNormals.push(1);
  71532. this._linesNormals.push(p0.x);
  71533. this._linesNormals.push(p0.y);
  71534. this._linesNormals.push(p0.z);
  71535. this._linesNormals.push(-1);
  71536. this._linesNormals.push(p0.x);
  71537. this._linesNormals.push(p0.y);
  71538. this._linesNormals.push(p0.z);
  71539. this._linesNormals.push(1);
  71540. // Indices
  71541. this._linesIndices.push(offset);
  71542. this._linesIndices.push(offset + 1);
  71543. this._linesIndices.push(offset + 2);
  71544. this._linesIndices.push(offset);
  71545. this._linesIndices.push(offset + 2);
  71546. this._linesIndices.push(offset + 3);
  71547. }
  71548. };
  71549. EdgesRenderer.prototype._generateEdgesLines = function () {
  71550. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71551. var indices = this._source.getIndices();
  71552. if (!indices || !positions) {
  71553. return;
  71554. }
  71555. // First let's find adjacencies
  71556. var adjacencies = new Array();
  71557. var faceNormals = new Array();
  71558. var index;
  71559. var faceAdjacencies;
  71560. // Prepare faces
  71561. for (index = 0; index < indices.length; index += 3) {
  71562. faceAdjacencies = new FaceAdjacencies();
  71563. var p0Index = indices[index];
  71564. var p1Index = indices[index + 1];
  71565. var p2Index = indices[index + 2];
  71566. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71567. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71568. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71569. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71570. faceNormal.normalize();
  71571. faceNormals.push(faceNormal);
  71572. adjacencies.push(faceAdjacencies);
  71573. }
  71574. // Scan
  71575. for (index = 0; index < adjacencies.length; index++) {
  71576. faceAdjacencies = adjacencies[index];
  71577. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71578. var otherFaceAdjacencies = adjacencies[otherIndex];
  71579. if (faceAdjacencies.edgesConnectedCount === 3) {
  71580. break;
  71581. }
  71582. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71583. continue;
  71584. }
  71585. var otherP0 = indices[otherIndex * 3];
  71586. var otherP1 = indices[otherIndex * 3 + 1];
  71587. var otherP2 = indices[otherIndex * 3 + 2];
  71588. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71589. var otherEdgeIndex = 0;
  71590. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71591. continue;
  71592. }
  71593. switch (edgeIndex) {
  71594. case 0:
  71595. if (this._checkVerticesInsteadOfIndices) {
  71596. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71597. }
  71598. else {
  71599. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71600. }
  71601. break;
  71602. case 1:
  71603. if (this._checkVerticesInsteadOfIndices) {
  71604. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71605. }
  71606. else {
  71607. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71608. }
  71609. break;
  71610. case 2:
  71611. if (this._checkVerticesInsteadOfIndices) {
  71612. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71613. }
  71614. else {
  71615. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71616. }
  71617. break;
  71618. }
  71619. if (otherEdgeIndex === -1) {
  71620. continue;
  71621. }
  71622. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71623. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71624. faceAdjacencies.edgesConnectedCount++;
  71625. otherFaceAdjacencies.edgesConnectedCount++;
  71626. if (faceAdjacencies.edgesConnectedCount === 3) {
  71627. break;
  71628. }
  71629. }
  71630. }
  71631. }
  71632. // Create lines
  71633. for (index = 0; index < adjacencies.length; index++) {
  71634. // 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
  71635. var current = adjacencies[index];
  71636. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71637. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71638. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71639. }
  71640. // Merge into a single mesh
  71641. var engine = this._source.getScene().getEngine();
  71642. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71643. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71644. this._ib = engine.createIndexBuffer(this._linesIndices);
  71645. this._indicesCount = this._linesIndices.length;
  71646. };
  71647. EdgesRenderer.prototype.render = function () {
  71648. var scene = this._source.getScene();
  71649. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71650. return;
  71651. }
  71652. var engine = scene.getEngine();
  71653. this._lineShader._preBind();
  71654. // VBOs
  71655. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71656. scene.resetCachedMaterial();
  71657. this._lineShader.setColor4("color", this._source.edgesColor);
  71658. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71659. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71660. }
  71661. else {
  71662. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71663. }
  71664. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71665. this._lineShader.bind(this._source.getWorldMatrix());
  71666. // Draw order
  71667. engine.draw(true, 0, this._indicesCount);
  71668. this._lineShader.unbind();
  71669. engine.setDepthWrite(true);
  71670. };
  71671. return EdgesRenderer;
  71672. }());
  71673. BABYLON.EdgesRenderer = EdgesRenderer;
  71674. })(BABYLON || (BABYLON = {}));
  71675. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71676. var BABYLON;
  71677. (function (BABYLON) {
  71678. /**
  71679. * Special Glow Blur post process only blurring the alpha channel
  71680. * It enforces keeping the most luminous color in the color channel.
  71681. */
  71682. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71683. __extends(GlowBlurPostProcess, _super);
  71684. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71686. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71687. _this.direction = direction;
  71688. _this.kernel = kernel;
  71689. _this.onApplyObservable.add(function (effect) {
  71690. effect.setFloat2("screenSize", _this.width, _this.height);
  71691. effect.setVector2("direction", _this.direction);
  71692. effect.setFloat("blurWidth", _this.kernel);
  71693. });
  71694. return _this;
  71695. }
  71696. return GlowBlurPostProcess;
  71697. }(BABYLON.PostProcess));
  71698. /**
  71699. * The highlight layer Helps adding a glow effect around a mesh.
  71700. *
  71701. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71702. * glowy meshes to your scene.
  71703. *
  71704. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71705. */
  71706. var HighlightLayer = /** @class */ (function () {
  71707. /**
  71708. * Instantiates a new highlight Layer and references it to the scene..
  71709. * @param name The name of the layer
  71710. * @param scene The scene to use the layer in
  71711. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71712. */
  71713. function HighlightLayer(name, scene, options) {
  71714. this.name = name;
  71715. this._vertexBuffers = {};
  71716. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71717. this._meshes = {};
  71718. this._maxSize = 0;
  71719. this._shouldRender = false;
  71720. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71721. this._excludedMeshes = {};
  71722. /**
  71723. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71724. */
  71725. this.innerGlow = true;
  71726. /**
  71727. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71728. */
  71729. this.outerGlow = true;
  71730. /**
  71731. * Specifies wether the highlight layer is enabled or not.
  71732. */
  71733. this.isEnabled = true;
  71734. /**
  71735. * An event triggered when the highlight layer has been disposed.
  71736. * @type {BABYLON.Observable}
  71737. */
  71738. this.onDisposeObservable = new BABYLON.Observable();
  71739. /**
  71740. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71741. * @type {BABYLON.Observable}
  71742. */
  71743. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71744. /**
  71745. * An event triggered when the highlight layer is being blurred.
  71746. * @type {BABYLON.Observable}
  71747. */
  71748. this.onBeforeBlurObservable = new BABYLON.Observable();
  71749. /**
  71750. * An event triggered when the highlight layer has been blurred.
  71751. * @type {BABYLON.Observable}
  71752. */
  71753. this.onAfterBlurObservable = new BABYLON.Observable();
  71754. /**
  71755. * An event triggered when the glowing blurred texture is being merged in the scene.
  71756. * @type {BABYLON.Observable}
  71757. */
  71758. this.onBeforeComposeObservable = new BABYLON.Observable();
  71759. /**
  71760. * An event triggered when the glowing blurred texture has been merged in the scene.
  71761. * @type {BABYLON.Observable}
  71762. */
  71763. this.onAfterComposeObservable = new BABYLON.Observable();
  71764. /**
  71765. * An event triggered when the highlight layer changes its size.
  71766. * @type {BABYLON.Observable}
  71767. */
  71768. this.onSizeChangedObservable = new BABYLON.Observable();
  71769. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71770. var engine = scene.getEngine();
  71771. this._engine = engine;
  71772. this._maxSize = this._engine.getCaps().maxTextureSize;
  71773. this._scene.highlightLayers.push(this);
  71774. // Warn on stencil.
  71775. if (!this._engine.isStencilEnable) {
  71776. 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 }");
  71777. }
  71778. // Adapt options
  71779. this._options = options || {
  71780. mainTextureRatio: 0.5,
  71781. blurTextureSizeRatio: 0.5,
  71782. blurHorizontalSize: 1.0,
  71783. blurVerticalSize: 1.0,
  71784. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71785. camera: null
  71786. };
  71787. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71788. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71789. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71790. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71791. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71792. // VBO
  71793. var vertices = [];
  71794. vertices.push(1, 1);
  71795. vertices.push(-1, 1);
  71796. vertices.push(-1, -1);
  71797. vertices.push(1, -1);
  71798. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71800. this._createIndexBuffer();
  71801. // Effect
  71802. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71803. // Render target
  71804. this.setMainTextureSize();
  71805. // Create Textures and post processes
  71806. this.createTextureAndPostProcesses();
  71807. }
  71808. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71809. /**
  71810. * Gets the horizontal size of the blur.
  71811. */
  71812. get: function () {
  71813. return this._horizontalBlurPostprocess.kernel;
  71814. },
  71815. /**
  71816. * Specifies the horizontal size of the blur.
  71817. */
  71818. set: function (value) {
  71819. this._horizontalBlurPostprocess.kernel = value;
  71820. },
  71821. enumerable: true,
  71822. configurable: true
  71823. });
  71824. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71825. /**
  71826. * Gets the vertical size of the blur.
  71827. */
  71828. get: function () {
  71829. return this._verticalBlurPostprocess.kernel;
  71830. },
  71831. /**
  71832. * Specifies the vertical size of the blur.
  71833. */
  71834. set: function (value) {
  71835. this._verticalBlurPostprocess.kernel = value;
  71836. },
  71837. enumerable: true,
  71838. configurable: true
  71839. });
  71840. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71841. /**
  71842. * Gets the camera attached to the layer.
  71843. */
  71844. get: function () {
  71845. return this._options.camera;
  71846. },
  71847. enumerable: true,
  71848. configurable: true
  71849. });
  71850. HighlightLayer.prototype._createIndexBuffer = function () {
  71851. var engine = this._scene.getEngine();
  71852. // Indices
  71853. var indices = [];
  71854. indices.push(0);
  71855. indices.push(1);
  71856. indices.push(2);
  71857. indices.push(0);
  71858. indices.push(2);
  71859. indices.push(3);
  71860. this._indexBuffer = engine.createIndexBuffer(indices);
  71861. };
  71862. HighlightLayer.prototype._rebuild = function () {
  71863. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71864. if (vb) {
  71865. vb._rebuild();
  71866. }
  71867. this._createIndexBuffer();
  71868. };
  71869. /**
  71870. * Creates the render target textures and post processes used in the highlight layer.
  71871. */
  71872. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71873. var _this = this;
  71874. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71875. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71876. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71877. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71878. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71879. width: this._mainTextureDesiredSize.width,
  71880. height: this._mainTextureDesiredSize.height
  71881. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71882. this._mainTexture.activeCamera = this._options.camera;
  71883. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71884. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71885. this._mainTexture.anisotropicFilteringLevel = 1;
  71886. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71887. this._mainTexture.renderParticles = false;
  71888. this._mainTexture.renderList = null;
  71889. this._mainTexture.ignoreCameraViewport = true;
  71890. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71891. width: blurTextureWidth,
  71892. height: blurTextureHeight
  71893. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71894. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71895. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71896. this._blurTexture.anisotropicFilteringLevel = 16;
  71897. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71898. this._blurTexture.renderParticles = false;
  71899. this._blurTexture.ignoreCameraViewport = true;
  71900. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71901. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71902. effect.setTexture("textureSampler", _this._mainTexture);
  71903. });
  71904. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71905. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71906. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71907. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71908. });
  71909. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71910. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71911. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71912. });
  71913. }
  71914. else {
  71915. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71916. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71917. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71918. });
  71919. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71920. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71921. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71922. });
  71923. }
  71924. this._mainTexture.onAfterUnbindObservable.add(function () {
  71925. _this.onBeforeBlurObservable.notifyObservers(_this);
  71926. var internalTexture = _this._blurTexture.getInternalTexture();
  71927. if (internalTexture) {
  71928. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  71929. }
  71930. _this.onAfterBlurObservable.notifyObservers(_this);
  71931. });
  71932. // Custom render function
  71933. var renderSubMesh = function (subMesh) {
  71934. if (!_this._meshes) {
  71935. return;
  71936. }
  71937. var material = subMesh.getMaterial();
  71938. var mesh = subMesh.getRenderingMesh();
  71939. var scene = _this._scene;
  71940. var engine = scene.getEngine();
  71941. if (!material) {
  71942. return;
  71943. }
  71944. // Culling
  71945. engine.setState(material.backFaceCulling);
  71946. // Managing instances
  71947. var batch = mesh._getInstancesRenderList(subMesh._id);
  71948. if (batch.mustReturn) {
  71949. return;
  71950. }
  71951. // Excluded Mesh
  71952. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71953. return;
  71954. }
  71955. ;
  71956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71957. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  71958. var emissiveTexture = null;
  71959. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  71960. emissiveTexture = material.emissiveTexture;
  71961. }
  71962. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  71963. engine.enableEffect(_this._glowMapGenerationEffect);
  71964. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  71965. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  71966. if (highlightLayerMesh) {
  71967. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  71968. }
  71969. else {
  71970. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  71971. }
  71972. // Alpha test
  71973. if (material && material.needAlphaTesting()) {
  71974. var alphaTexture = material.getAlphaTestTexture();
  71975. if (alphaTexture) {
  71976. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71977. var textureMatrix = alphaTexture.getTextureMatrix();
  71978. if (textureMatrix) {
  71979. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71980. }
  71981. }
  71982. }
  71983. // Glow emissive only
  71984. if (emissiveTexture) {
  71985. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71986. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71987. }
  71988. // Bones
  71989. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71990. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71991. }
  71992. // Draw
  71993. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71994. }
  71995. else {
  71996. // Need to reset refresh rate of the shadowMap
  71997. _this._mainTexture.resetRefreshCounter();
  71998. }
  71999. };
  72000. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72001. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72002. var index;
  72003. var engine = _this._scene.getEngine();
  72004. if (depthOnlySubMeshes.length) {
  72005. engine.setColorWrite(false);
  72006. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72007. renderSubMesh(depthOnlySubMeshes.data[index]);
  72008. }
  72009. engine.setColorWrite(true);
  72010. }
  72011. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72012. renderSubMesh(opaqueSubMeshes.data[index]);
  72013. }
  72014. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72015. renderSubMesh(alphaTestSubMeshes.data[index]);
  72016. }
  72017. for (index = 0; index < transparentSubMeshes.length; index++) {
  72018. renderSubMesh(transparentSubMeshes.data[index]);
  72019. }
  72020. };
  72021. this._mainTexture.onClearObservable.add(function (engine) {
  72022. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72023. });
  72024. };
  72025. /**
  72026. * Checks for the readiness of the element composing the layer.
  72027. * @param subMesh the mesh to check for
  72028. * @param useInstances specify wether or not to use instances to render the mesh
  72029. * @param emissiveTexture the associated emissive texture used to generate the glow
  72030. * @return true if ready otherwise, false
  72031. */
  72032. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72033. var material = subMesh.getMaterial();
  72034. if (!material) {
  72035. return false;
  72036. }
  72037. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72038. return false;
  72039. }
  72040. var defines = [];
  72041. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72042. var mesh = subMesh.getMesh();
  72043. var uv1 = false;
  72044. var uv2 = false;
  72045. // Alpha test
  72046. if (material && material.needAlphaTesting()) {
  72047. var alphaTexture = material.getAlphaTestTexture();
  72048. if (alphaTexture) {
  72049. defines.push("#define ALPHATEST");
  72050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72051. alphaTexture.coordinatesIndex === 1) {
  72052. defines.push("#define DIFFUSEUV2");
  72053. uv2 = true;
  72054. }
  72055. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72056. defines.push("#define DIFFUSEUV1");
  72057. uv1 = true;
  72058. }
  72059. }
  72060. }
  72061. // Emissive
  72062. if (emissiveTexture) {
  72063. defines.push("#define EMISSIVE");
  72064. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72065. emissiveTexture.coordinatesIndex === 1) {
  72066. defines.push("#define EMISSIVEUV2");
  72067. uv2 = true;
  72068. }
  72069. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72070. defines.push("#define EMISSIVEUV1");
  72071. uv1 = true;
  72072. }
  72073. }
  72074. if (uv1) {
  72075. attribs.push(BABYLON.VertexBuffer.UVKind);
  72076. defines.push("#define UV1");
  72077. }
  72078. if (uv2) {
  72079. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72080. defines.push("#define UV2");
  72081. }
  72082. // Bones
  72083. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72086. if (mesh.numBoneInfluencers > 4) {
  72087. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72088. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72089. }
  72090. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72091. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72092. }
  72093. else {
  72094. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72095. }
  72096. // Instances
  72097. if (useInstances) {
  72098. defines.push("#define INSTANCES");
  72099. attribs.push("world0");
  72100. attribs.push("world1");
  72101. attribs.push("world2");
  72102. attribs.push("world3");
  72103. }
  72104. // Get correct effect
  72105. var join = defines.join("\n");
  72106. if (this._cachedDefines !== join) {
  72107. this._cachedDefines = join;
  72108. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72109. }
  72110. return this._glowMapGenerationEffect.isReady();
  72111. };
  72112. /**
  72113. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72114. */
  72115. HighlightLayer.prototype.render = function () {
  72116. var currentEffect = this._glowMapMergeEffect;
  72117. // Check
  72118. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72119. return;
  72120. var engine = this._scene.getEngine();
  72121. this.onBeforeComposeObservable.notifyObservers(this);
  72122. // Render
  72123. engine.enableEffect(currentEffect);
  72124. engine.setState(false);
  72125. // Cache
  72126. var previousStencilBuffer = engine.getStencilBuffer();
  72127. var previousStencilFunction = engine.getStencilFunction();
  72128. var previousStencilMask = engine.getStencilMask();
  72129. var previousStencilOperationPass = engine.getStencilOperationPass();
  72130. var previousStencilOperationFail = engine.getStencilOperationFail();
  72131. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72132. var previousAlphaMode = engine.getAlphaMode();
  72133. // Texture
  72134. currentEffect.setTexture("textureSampler", this._blurTexture);
  72135. // VBOs
  72136. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72137. // Stencil operations
  72138. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72139. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72140. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72141. // Draw order
  72142. engine.setAlphaMode(this._options.alphaBlendingMode);
  72143. engine.setStencilMask(0x00);
  72144. engine.setStencilBuffer(true);
  72145. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72146. if (this.outerGlow) {
  72147. currentEffect.setFloat("offset", 0);
  72148. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72149. engine.draw(true, 0, 6);
  72150. }
  72151. if (this.innerGlow) {
  72152. currentEffect.setFloat("offset", 1);
  72153. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72154. engine.draw(true, 0, 6);
  72155. }
  72156. // Restore Cache
  72157. engine.setStencilFunction(previousStencilFunction);
  72158. engine.setStencilMask(previousStencilMask);
  72159. engine.setAlphaMode(previousAlphaMode);
  72160. engine.setStencilBuffer(previousStencilBuffer);
  72161. engine.setStencilOperationPass(previousStencilOperationPass);
  72162. engine.setStencilOperationFail(previousStencilOperationFail);
  72163. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72164. engine._stencilState.reset();
  72165. this.onAfterComposeObservable.notifyObservers(this);
  72166. // Handle size changes.
  72167. var size = this._mainTexture.getSize();
  72168. this.setMainTextureSize();
  72169. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72170. // Recreate RTT and post processes on size change.
  72171. this.onSizeChangedObservable.notifyObservers(this);
  72172. this.disposeTextureAndPostProcesses();
  72173. this.createTextureAndPostProcesses();
  72174. }
  72175. };
  72176. /**
  72177. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72178. * @param mesh The mesh to exclude from the highlight layer
  72179. */
  72180. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72181. if (!this._excludedMeshes) {
  72182. return;
  72183. }
  72184. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72185. if (!meshExcluded) {
  72186. this._excludedMeshes[mesh.uniqueId] = {
  72187. mesh: mesh,
  72188. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72189. mesh.getEngine().setStencilBuffer(false);
  72190. }),
  72191. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72192. mesh.getEngine().setStencilBuffer(true);
  72193. }),
  72194. };
  72195. }
  72196. };
  72197. /**
  72198. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72199. * @param mesh The mesh to highlight
  72200. */
  72201. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72202. if (!this._excludedMeshes) {
  72203. return;
  72204. }
  72205. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72206. if (meshExcluded) {
  72207. if (meshExcluded.beforeRender) {
  72208. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72209. }
  72210. if (meshExcluded.afterRender) {
  72211. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72212. }
  72213. }
  72214. this._excludedMeshes[mesh.uniqueId] = null;
  72215. };
  72216. /**
  72217. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72218. * @param mesh The mesh to highlight
  72219. * @param color The color of the highlight
  72220. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72221. */
  72222. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72223. var _this = this;
  72224. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72225. if (!this._meshes) {
  72226. return;
  72227. }
  72228. var meshHighlight = this._meshes[mesh.uniqueId];
  72229. if (meshHighlight) {
  72230. meshHighlight.color = color;
  72231. }
  72232. else {
  72233. this._meshes[mesh.uniqueId] = {
  72234. mesh: mesh,
  72235. color: color,
  72236. // Lambda required for capture due to Observable this context
  72237. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72238. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72239. _this.defaultStencilReference(mesh);
  72240. }
  72241. else {
  72242. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72243. }
  72244. }),
  72245. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72246. glowEmissiveOnly: glowEmissiveOnly
  72247. };
  72248. }
  72249. this._shouldRender = true;
  72250. };
  72251. /**
  72252. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72253. * @param mesh The mesh to highlight
  72254. */
  72255. HighlightLayer.prototype.removeMesh = function (mesh) {
  72256. if (!this._meshes) {
  72257. return;
  72258. }
  72259. var meshHighlight = this._meshes[mesh.uniqueId];
  72260. if (meshHighlight) {
  72261. if (meshHighlight.observerHighlight) {
  72262. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72263. }
  72264. if (meshHighlight.observerDefault) {
  72265. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72266. }
  72267. }
  72268. this._meshes[mesh.uniqueId] = null;
  72269. this._shouldRender = false;
  72270. for (var meshHighlightToCheck in this._meshes) {
  72271. if (meshHighlightToCheck) {
  72272. this._shouldRender = true;
  72273. break;
  72274. }
  72275. }
  72276. };
  72277. /**
  72278. * Returns true if the layer contains information to display, otherwise false.
  72279. */
  72280. HighlightLayer.prototype.shouldRender = function () {
  72281. return this.isEnabled && this._shouldRender;
  72282. };
  72283. /**
  72284. * Sets the main texture desired size which is the closest power of two
  72285. * of the engine canvas size.
  72286. */
  72287. HighlightLayer.prototype.setMainTextureSize = function () {
  72288. if (this._options.mainTextureFixedSize) {
  72289. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72290. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72291. }
  72292. else {
  72293. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72294. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72295. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72296. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72297. }
  72298. };
  72299. /**
  72300. * Force the stencil to the normal expected value for none glowing parts
  72301. */
  72302. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72303. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72304. };
  72305. /**
  72306. * Dispose only the render target textures and post process.
  72307. */
  72308. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72309. this._blurTexture.dispose();
  72310. this._mainTexture.dispose();
  72311. this._downSamplePostprocess.dispose();
  72312. this._horizontalBlurPostprocess.dispose();
  72313. this._verticalBlurPostprocess.dispose();
  72314. };
  72315. /**
  72316. * Dispose the highlight layer and free resources.
  72317. */
  72318. HighlightLayer.prototype.dispose = function () {
  72319. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72320. if (vertexBuffer) {
  72321. vertexBuffer.dispose();
  72322. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72323. }
  72324. if (this._indexBuffer) {
  72325. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72326. this._indexBuffer = null;
  72327. }
  72328. // Clean textures and post processes
  72329. this.disposeTextureAndPostProcesses();
  72330. if (this._meshes) {
  72331. // Clean mesh references
  72332. for (var id in this._meshes) {
  72333. var meshHighlight = this._meshes[id];
  72334. if (meshHighlight && meshHighlight.mesh) {
  72335. if (meshHighlight.observerHighlight) {
  72336. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72337. }
  72338. if (meshHighlight.observerDefault) {
  72339. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72340. }
  72341. }
  72342. }
  72343. this._meshes = null;
  72344. }
  72345. if (this._excludedMeshes) {
  72346. for (var id in this._excludedMeshes) {
  72347. var meshHighlight = this._excludedMeshes[id];
  72348. if (meshHighlight) {
  72349. if (meshHighlight.beforeRender) {
  72350. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72351. }
  72352. if (meshHighlight.afterRender) {
  72353. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72354. }
  72355. }
  72356. }
  72357. this._excludedMeshes = null;
  72358. }
  72359. // Remove from scene
  72360. var index = this._scene.highlightLayers.indexOf(this, 0);
  72361. if (index > -1) {
  72362. this._scene.highlightLayers.splice(index, 1);
  72363. }
  72364. // Callback
  72365. this.onDisposeObservable.notifyObservers(this);
  72366. this.onDisposeObservable.clear();
  72367. this.onBeforeRenderMainTextureObservable.clear();
  72368. this.onBeforeBlurObservable.clear();
  72369. this.onBeforeComposeObservable.clear();
  72370. this.onAfterComposeObservable.clear();
  72371. this.onSizeChangedObservable.clear();
  72372. };
  72373. /**
  72374. * The neutral color used during the preparation of the glow effect.
  72375. * This is black by default as the blend operation is a blend operation.
  72376. */
  72377. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72378. /**
  72379. * Stencil value used for glowing meshes.
  72380. */
  72381. HighlightLayer.glowingMeshStencilReference = 0x02;
  72382. /**
  72383. * Stencil value used for the other meshes in the scene.
  72384. */
  72385. HighlightLayer.normalMeshStencilReference = 0x01;
  72386. return HighlightLayer;
  72387. }());
  72388. BABYLON.HighlightLayer = HighlightLayer;
  72389. })(BABYLON || (BABYLON = {}));
  72390. //# sourceMappingURL=babylon.highlightlayer.js.map
  72391. var BABYLON;
  72392. (function (BABYLON) {
  72393. var AssetTaskState;
  72394. (function (AssetTaskState) {
  72395. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72396. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72397. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72398. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72399. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72400. var AbstractAssetTask = /** @class */ (function () {
  72401. function AbstractAssetTask(name) {
  72402. this.name = name;
  72403. this.isCompleted = false;
  72404. this.taskState = AssetTaskState.INIT;
  72405. }
  72406. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72407. var _this = this;
  72408. this.taskState = AssetTaskState.RUNNING;
  72409. this.runTask(scene, function () {
  72410. _this.onDoneCallback(onSuccess, onError);
  72411. }, function (msg, exception) {
  72412. _this.onErrorCallback(onError, msg, exception);
  72413. });
  72414. };
  72415. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72416. throw new Error("runTask is not implemented");
  72417. };
  72418. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72419. this.taskState = AssetTaskState.ERROR;
  72420. this.errorObject = {
  72421. message: message,
  72422. exception: exception
  72423. };
  72424. if (this.onError) {
  72425. this.onError(this, message, exception);
  72426. }
  72427. onError();
  72428. };
  72429. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72430. try {
  72431. this.taskState = AssetTaskState.DONE;
  72432. this.isCompleted = true;
  72433. if (this.onSuccess) {
  72434. this.onSuccess(this);
  72435. }
  72436. onSuccess();
  72437. }
  72438. catch (e) {
  72439. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72440. }
  72441. };
  72442. return AbstractAssetTask;
  72443. }());
  72444. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72445. var AssetsProgressEvent = /** @class */ (function () {
  72446. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72447. this.remainingCount = remainingCount;
  72448. this.totalCount = totalCount;
  72449. this.task = task;
  72450. }
  72451. return AssetsProgressEvent;
  72452. }());
  72453. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72454. var MeshAssetTask = /** @class */ (function (_super) {
  72455. __extends(MeshAssetTask, _super);
  72456. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72457. var _this = _super.call(this, name) || this;
  72458. _this.name = name;
  72459. _this.meshesNames = meshesNames;
  72460. _this.rootUrl = rootUrl;
  72461. _this.sceneFilename = sceneFilename;
  72462. return _this;
  72463. }
  72464. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72465. var _this = this;
  72466. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72467. _this.loadedMeshes = meshes;
  72468. _this.loadedParticleSystems = particleSystems;
  72469. _this.loadedSkeletons = skeletons;
  72470. onSuccess();
  72471. }, null, function (scene, message, exception) {
  72472. onError(message, exception);
  72473. });
  72474. };
  72475. return MeshAssetTask;
  72476. }(AbstractAssetTask));
  72477. BABYLON.MeshAssetTask = MeshAssetTask;
  72478. var TextFileAssetTask = /** @class */ (function (_super) {
  72479. __extends(TextFileAssetTask, _super);
  72480. function TextFileAssetTask(name, url) {
  72481. var _this = _super.call(this, name) || this;
  72482. _this.name = name;
  72483. _this.url = url;
  72484. return _this;
  72485. }
  72486. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72487. var _this = this;
  72488. BABYLON.Tools.LoadFile(this.url, function (data) {
  72489. _this.text = data;
  72490. onSuccess();
  72491. }, undefined, scene.database, false, function (request, exception) {
  72492. if (request) {
  72493. onError(request.status + " " + request.statusText, exception);
  72494. }
  72495. });
  72496. };
  72497. return TextFileAssetTask;
  72498. }(AbstractAssetTask));
  72499. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72500. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72501. __extends(BinaryFileAssetTask, _super);
  72502. function BinaryFileAssetTask(name, url) {
  72503. var _this = _super.call(this, name) || this;
  72504. _this.name = name;
  72505. _this.url = url;
  72506. return _this;
  72507. }
  72508. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72509. var _this = this;
  72510. BABYLON.Tools.LoadFile(this.url, function (data) {
  72511. _this.data = data;
  72512. onSuccess();
  72513. }, undefined, scene.database, true, function (request, exception) {
  72514. if (request) {
  72515. onError(request.status + " " + request.statusText, exception);
  72516. }
  72517. });
  72518. };
  72519. return BinaryFileAssetTask;
  72520. }(AbstractAssetTask));
  72521. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72522. var ImageAssetTask = /** @class */ (function (_super) {
  72523. __extends(ImageAssetTask, _super);
  72524. function ImageAssetTask(name, url) {
  72525. var _this = _super.call(this, name) || this;
  72526. _this.name = name;
  72527. _this.url = url;
  72528. return _this;
  72529. }
  72530. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72531. var _this = this;
  72532. var img = new Image();
  72533. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72534. img.onload = function () {
  72535. _this.image = img;
  72536. onSuccess();
  72537. };
  72538. img.onerror = function (err) {
  72539. onError("Error loading image", err);
  72540. };
  72541. img.src = this.url;
  72542. };
  72543. return ImageAssetTask;
  72544. }(AbstractAssetTask));
  72545. BABYLON.ImageAssetTask = ImageAssetTask;
  72546. var TextureAssetTask = /** @class */ (function (_super) {
  72547. __extends(TextureAssetTask, _super);
  72548. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72550. var _this = _super.call(this, name) || this;
  72551. _this.name = name;
  72552. _this.url = url;
  72553. _this.noMipmap = noMipmap;
  72554. _this.invertY = invertY;
  72555. _this.samplingMode = samplingMode;
  72556. return _this;
  72557. }
  72558. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72559. var onload = function () {
  72560. onSuccess();
  72561. };
  72562. var onerror = function (msg, exception) {
  72563. onError(msg, exception);
  72564. };
  72565. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72566. };
  72567. return TextureAssetTask;
  72568. }(AbstractAssetTask));
  72569. BABYLON.TextureAssetTask = TextureAssetTask;
  72570. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72571. __extends(CubeTextureAssetTask, _super);
  72572. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72573. var _this = _super.call(this, name) || this;
  72574. _this.name = name;
  72575. _this.url = url;
  72576. _this.extensions = extensions;
  72577. _this.noMipmap = noMipmap;
  72578. _this.files = files;
  72579. return _this;
  72580. }
  72581. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72582. var onload = function () {
  72583. onSuccess();
  72584. };
  72585. var onerror = function (msg, exception) {
  72586. onError(msg, exception);
  72587. };
  72588. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72589. };
  72590. return CubeTextureAssetTask;
  72591. }(AbstractAssetTask));
  72592. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72593. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72594. __extends(HDRCubeTextureAssetTask, _super);
  72595. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72596. if (noMipmap === void 0) { noMipmap = false; }
  72597. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72598. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72599. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72600. var _this = _super.call(this, name) || this;
  72601. _this.name = name;
  72602. _this.url = url;
  72603. _this.size = size;
  72604. _this.noMipmap = noMipmap;
  72605. _this.generateHarmonics = generateHarmonics;
  72606. _this.useInGammaSpace = useInGammaSpace;
  72607. _this.usePMREMGenerator = usePMREMGenerator;
  72608. return _this;
  72609. }
  72610. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72611. var onload = function () {
  72612. onSuccess();
  72613. };
  72614. var onerror = function (message, exception) {
  72615. onError(message, exception);
  72616. };
  72617. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72618. };
  72619. return HDRCubeTextureAssetTask;
  72620. }(AbstractAssetTask));
  72621. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72622. var AssetsManager = /** @class */ (function () {
  72623. function AssetsManager(scene) {
  72624. this.tasks = new Array();
  72625. this.waitingTasksCount = 0;
  72626. //Observables
  72627. this.onTaskSuccessObservable = new BABYLON.Observable();
  72628. this.onTaskErrorObservable = new BABYLON.Observable();
  72629. this.onTasksDoneObservable = new BABYLON.Observable();
  72630. this.onProgressObservable = new BABYLON.Observable();
  72631. this.useDefaultLoadingScreen = true;
  72632. this._scene = scene;
  72633. }
  72634. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72635. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72636. this.tasks.push(task);
  72637. return task;
  72638. };
  72639. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72640. var task = new TextFileAssetTask(taskName, url);
  72641. this.tasks.push(task);
  72642. return task;
  72643. };
  72644. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72645. var task = new BinaryFileAssetTask(taskName, url);
  72646. this.tasks.push(task);
  72647. return task;
  72648. };
  72649. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72650. var task = new ImageAssetTask(taskName, url);
  72651. this.tasks.push(task);
  72652. return task;
  72653. };
  72654. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72656. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72657. this.tasks.push(task);
  72658. return task;
  72659. };
  72660. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72661. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72662. this.tasks.push(task);
  72663. return task;
  72664. };
  72665. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72666. if (noMipmap === void 0) { noMipmap = false; }
  72667. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72668. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72669. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72670. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72671. this.tasks.push(task);
  72672. return task;
  72673. };
  72674. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72675. this.waitingTasksCount--;
  72676. try {
  72677. if (this.onProgress) {
  72678. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72679. }
  72680. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72681. }
  72682. catch (e) {
  72683. BABYLON.Tools.Error("Error running progress callbacks.");
  72684. console.log(e);
  72685. }
  72686. if (this.waitingTasksCount === 0) {
  72687. try {
  72688. if (this.onFinish) {
  72689. this.onFinish(this.tasks);
  72690. }
  72691. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72692. }
  72693. catch (e) {
  72694. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72695. console.log(e);
  72696. }
  72697. this._scene.getEngine().hideLoadingUI();
  72698. }
  72699. };
  72700. AssetsManager.prototype._runTask = function (task) {
  72701. var _this = this;
  72702. var done = function () {
  72703. try {
  72704. if (_this.onTaskSuccess) {
  72705. _this.onTaskSuccess(task);
  72706. }
  72707. _this.onTaskSuccessObservable.notifyObservers(task);
  72708. _this._decreaseWaitingTasksCount(task);
  72709. }
  72710. catch (e) {
  72711. error("Error executing task success callbacks", e);
  72712. }
  72713. };
  72714. var error = function (message, exception) {
  72715. task.errorObject = task.errorObject || {
  72716. message: message,
  72717. exception: exception
  72718. };
  72719. if (_this.onTaskError) {
  72720. _this.onTaskError(task);
  72721. }
  72722. _this.onTaskErrorObservable.notifyObservers(task);
  72723. _this._decreaseWaitingTasksCount(task);
  72724. };
  72725. task.run(this._scene, done, error);
  72726. };
  72727. AssetsManager.prototype.reset = function () {
  72728. this.tasks = new Array();
  72729. return this;
  72730. };
  72731. AssetsManager.prototype.load = function () {
  72732. this.waitingTasksCount = this.tasks.length;
  72733. if (this.waitingTasksCount === 0) {
  72734. if (this.onFinish) {
  72735. this.onFinish(this.tasks);
  72736. }
  72737. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72738. return this;
  72739. }
  72740. if (this.useDefaultLoadingScreen) {
  72741. this._scene.getEngine().displayLoadingUI();
  72742. }
  72743. for (var index = 0; index < this.tasks.length; index++) {
  72744. var task = this.tasks[index];
  72745. this._runTask(task);
  72746. }
  72747. return this;
  72748. };
  72749. return AssetsManager;
  72750. }());
  72751. BABYLON.AssetsManager = AssetsManager;
  72752. })(BABYLON || (BABYLON = {}));
  72753. //# sourceMappingURL=babylon.assetsManager.js.map
  72754. var BABYLON;
  72755. (function (BABYLON) {
  72756. var serializedGeometries = [];
  72757. var serializeGeometry = function (geometry, serializationGeometries) {
  72758. if (serializedGeometries[geometry.id]) {
  72759. return;
  72760. }
  72761. if (geometry.doNotSerialize) {
  72762. return;
  72763. }
  72764. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72765. serializationGeometries.boxes.push(geometry.serialize());
  72766. }
  72767. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72768. serializationGeometries.spheres.push(geometry.serialize());
  72769. }
  72770. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72771. serializationGeometries.cylinders.push(geometry.serialize());
  72772. }
  72773. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72774. serializationGeometries.toruses.push(geometry.serialize());
  72775. }
  72776. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72777. serializationGeometries.grounds.push(geometry.serialize());
  72778. }
  72779. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72780. serializationGeometries.planes.push(geometry.serialize());
  72781. }
  72782. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72783. serializationGeometries.torusKnots.push(geometry.serialize());
  72784. }
  72785. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72786. throw new Error("Unknown primitive type");
  72787. }
  72788. else {
  72789. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72790. }
  72791. serializedGeometries[geometry.id] = true;
  72792. };
  72793. var serializeMesh = function (mesh, serializationScene) {
  72794. var serializationObject = {};
  72795. // Geometry
  72796. var geometry = mesh._geometry;
  72797. if (geometry) {
  72798. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72799. // 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
  72800. serializeGeometry(geometry, serializationScene.geometries);
  72801. }
  72802. }
  72803. // Custom
  72804. if (mesh.serialize) {
  72805. mesh.serialize(serializationObject);
  72806. }
  72807. return serializationObject;
  72808. };
  72809. var finalizeSingleMesh = function (mesh, serializationObject) {
  72810. //only works if the mesh is already loaded
  72811. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72812. //serialize material
  72813. if (mesh.material) {
  72814. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72815. serializationObject.materials = serializationObject.materials || [];
  72816. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72817. serializationObject.materials.push(mesh.material.serialize());
  72818. }
  72819. }
  72820. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72821. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72822. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72823. serializationObject.multiMaterials.push(mesh.material.serialize());
  72824. }
  72825. }
  72826. }
  72827. //serialize geometry
  72828. var geometry = mesh._geometry;
  72829. if (geometry) {
  72830. if (!serializationObject.geometries) {
  72831. serializationObject.geometries = {};
  72832. serializationObject.geometries.boxes = [];
  72833. serializationObject.geometries.spheres = [];
  72834. serializationObject.geometries.cylinders = [];
  72835. serializationObject.geometries.toruses = [];
  72836. serializationObject.geometries.grounds = [];
  72837. serializationObject.geometries.planes = [];
  72838. serializationObject.geometries.torusKnots = [];
  72839. serializationObject.geometries.vertexData = [];
  72840. }
  72841. serializeGeometry(geometry, serializationObject.geometries);
  72842. }
  72843. // Skeletons
  72844. if (mesh.skeleton) {
  72845. serializationObject.skeletons = serializationObject.skeletons || [];
  72846. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72847. }
  72848. //serialize the actual mesh
  72849. serializationObject.meshes = serializationObject.meshes || [];
  72850. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72851. }
  72852. };
  72853. var SceneSerializer = /** @class */ (function () {
  72854. function SceneSerializer() {
  72855. }
  72856. SceneSerializer.ClearCache = function () {
  72857. serializedGeometries = [];
  72858. };
  72859. SceneSerializer.Serialize = function (scene) {
  72860. var serializationObject = {};
  72861. SceneSerializer.ClearCache();
  72862. // Scene
  72863. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72864. serializationObject.autoClear = scene.autoClear;
  72865. serializationObject.clearColor = scene.clearColor.asArray();
  72866. serializationObject.ambientColor = scene.ambientColor.asArray();
  72867. serializationObject.gravity = scene.gravity.asArray();
  72868. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72869. serializationObject.workerCollisions = scene.workerCollisions;
  72870. // Fog
  72871. if (scene.fogMode && scene.fogMode !== 0) {
  72872. serializationObject.fogMode = scene.fogMode;
  72873. serializationObject.fogColor = scene.fogColor.asArray();
  72874. serializationObject.fogStart = scene.fogStart;
  72875. serializationObject.fogEnd = scene.fogEnd;
  72876. serializationObject.fogDensity = scene.fogDensity;
  72877. }
  72878. //Physics
  72879. if (scene.isPhysicsEnabled()) {
  72880. var physicEngine = scene.getPhysicsEngine();
  72881. if (physicEngine) {
  72882. serializationObject.physicsEnabled = true;
  72883. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72884. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72885. }
  72886. }
  72887. // Metadata
  72888. if (scene.metadata) {
  72889. serializationObject.metadata = scene.metadata;
  72890. }
  72891. // Morph targets
  72892. serializationObject.morphTargetManagers = [];
  72893. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72894. var abstractMesh = _a[_i];
  72895. var manager = abstractMesh.morphTargetManager;
  72896. if (manager) {
  72897. serializationObject.morphTargetManagers.push(manager.serialize());
  72898. }
  72899. }
  72900. // Lights
  72901. serializationObject.lights = [];
  72902. var index;
  72903. var light;
  72904. for (index = 0; index < scene.lights.length; index++) {
  72905. light = scene.lights[index];
  72906. if (!light.doNotSerialize) {
  72907. serializationObject.lights.push(light.serialize());
  72908. }
  72909. }
  72910. // Cameras
  72911. serializationObject.cameras = [];
  72912. for (index = 0; index < scene.cameras.length; index++) {
  72913. var camera = scene.cameras[index];
  72914. if (!camera.doNotSerialize) {
  72915. serializationObject.cameras.push(camera.serialize());
  72916. }
  72917. }
  72918. if (scene.activeCamera) {
  72919. serializationObject.activeCameraID = scene.activeCamera.id;
  72920. }
  72921. // Animations
  72922. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  72923. // Materials
  72924. serializationObject.materials = [];
  72925. serializationObject.multiMaterials = [];
  72926. var material;
  72927. for (index = 0; index < scene.materials.length; index++) {
  72928. material = scene.materials[index];
  72929. if (!material.doNotSerialize) {
  72930. serializationObject.materials.push(material.serialize());
  72931. }
  72932. }
  72933. // MultiMaterials
  72934. serializationObject.multiMaterials = [];
  72935. for (index = 0; index < scene.multiMaterials.length; index++) {
  72936. var multiMaterial = scene.multiMaterials[index];
  72937. serializationObject.multiMaterials.push(multiMaterial.serialize());
  72938. }
  72939. // Skeletons
  72940. serializationObject.skeletons = [];
  72941. for (index = 0; index < scene.skeletons.length; index++) {
  72942. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  72943. }
  72944. // Geometries
  72945. serializationObject.geometries = {};
  72946. serializationObject.geometries.boxes = [];
  72947. serializationObject.geometries.spheres = [];
  72948. serializationObject.geometries.cylinders = [];
  72949. serializationObject.geometries.toruses = [];
  72950. serializationObject.geometries.grounds = [];
  72951. serializationObject.geometries.planes = [];
  72952. serializationObject.geometries.torusKnots = [];
  72953. serializationObject.geometries.vertexData = [];
  72954. serializedGeometries = [];
  72955. var geometries = scene.getGeometries();
  72956. for (index = 0; index < geometries.length; index++) {
  72957. var geometry = geometries[index];
  72958. if (geometry.isReady()) {
  72959. serializeGeometry(geometry, serializationObject.geometries);
  72960. }
  72961. }
  72962. // Meshes
  72963. serializationObject.meshes = [];
  72964. for (index = 0; index < scene.meshes.length; index++) {
  72965. var abstractMesh = scene.meshes[index];
  72966. if (abstractMesh instanceof BABYLON.Mesh) {
  72967. var mesh = abstractMesh;
  72968. if (!mesh.doNotSerialize) {
  72969. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72970. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72971. }
  72972. }
  72973. }
  72974. }
  72975. // Particles Systems
  72976. serializationObject.particleSystems = [];
  72977. for (index = 0; index < scene.particleSystems.length; index++) {
  72978. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  72979. }
  72980. // Lens flares
  72981. serializationObject.lensFlareSystems = [];
  72982. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  72983. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  72984. }
  72985. // Shadows
  72986. serializationObject.shadowGenerators = [];
  72987. for (index = 0; index < scene.lights.length; index++) {
  72988. light = scene.lights[index];
  72989. var shadowGenerator = light.getShadowGenerator();
  72990. if (shadowGenerator) {
  72991. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72992. }
  72993. }
  72994. // Action Manager
  72995. if (scene.actionManager) {
  72996. serializationObject.actions = scene.actionManager.serialize("scene");
  72997. }
  72998. // Audio
  72999. serializationObject.sounds = [];
  73000. for (index = 0; index < scene.soundTracks.length; index++) {
  73001. var soundtrack = scene.soundTracks[index];
  73002. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73003. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73004. }
  73005. }
  73006. return serializationObject;
  73007. };
  73008. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73009. if (withParents === void 0) { withParents = false; }
  73010. if (withChildren === void 0) { withChildren = false; }
  73011. var serializationObject = {};
  73012. SceneSerializer.ClearCache();
  73013. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73014. if (withParents || withChildren) {
  73015. //deliberate for loop! not for each, appended should be processed as well.
  73016. for (var i = 0; i < toSerialize.length; ++i) {
  73017. if (withChildren) {
  73018. toSerialize[i].getDescendants().forEach(function (node) {
  73019. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73020. toSerialize.push(node);
  73021. }
  73022. });
  73023. }
  73024. //make sure the array doesn't contain the object already
  73025. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73026. toSerialize.push(toSerialize[i].parent);
  73027. }
  73028. }
  73029. }
  73030. toSerialize.forEach(function (mesh) {
  73031. finalizeSingleMesh(mesh, serializationObject);
  73032. });
  73033. return serializationObject;
  73034. };
  73035. return SceneSerializer;
  73036. }());
  73037. BABYLON.SceneSerializer = SceneSerializer;
  73038. })(BABYLON || (BABYLON = {}));
  73039. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73040. var BABYLON;
  73041. (function (BABYLON) {
  73042. var ReflectionProbe = /** @class */ (function () {
  73043. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73044. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73045. var _this = this;
  73046. this.name = name;
  73047. this._viewMatrix = BABYLON.Matrix.Identity();
  73048. this._target = BABYLON.Vector3.Zero();
  73049. this._add = BABYLON.Vector3.Zero();
  73050. this.invertYAxis = false;
  73051. this.position = BABYLON.Vector3.Zero();
  73052. this._scene = scene;
  73053. this._scene.reflectionProbes.push(this);
  73054. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73055. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73056. switch (faceIndex) {
  73057. case 0:
  73058. _this._add.copyFromFloats(1, 0, 0);
  73059. break;
  73060. case 1:
  73061. _this._add.copyFromFloats(-1, 0, 0);
  73062. break;
  73063. case 2:
  73064. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73065. break;
  73066. case 3:
  73067. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73068. break;
  73069. case 4:
  73070. _this._add.copyFromFloats(0, 0, 1);
  73071. break;
  73072. case 5:
  73073. _this._add.copyFromFloats(0, 0, -1);
  73074. break;
  73075. }
  73076. if (_this._attachedMesh) {
  73077. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73078. }
  73079. _this.position.addToRef(_this._add, _this._target);
  73080. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73081. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73082. scene._forcedViewPosition = _this.position;
  73083. });
  73084. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73085. scene._forcedViewPosition = null;
  73086. scene.updateTransformMatrix(true);
  73087. });
  73088. if (scene.activeCamera) {
  73089. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73090. }
  73091. }
  73092. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73093. get: function () {
  73094. return this._renderTargetTexture.samples;
  73095. },
  73096. set: function (value) {
  73097. this._renderTargetTexture.samples = value;
  73098. },
  73099. enumerable: true,
  73100. configurable: true
  73101. });
  73102. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73103. get: function () {
  73104. return this._renderTargetTexture.refreshRate;
  73105. },
  73106. set: function (value) {
  73107. this._renderTargetTexture.refreshRate = value;
  73108. },
  73109. enumerable: true,
  73110. configurable: true
  73111. });
  73112. ReflectionProbe.prototype.getScene = function () {
  73113. return this._scene;
  73114. };
  73115. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73116. get: function () {
  73117. return this._renderTargetTexture;
  73118. },
  73119. enumerable: true,
  73120. configurable: true
  73121. });
  73122. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73123. get: function () {
  73124. return this._renderTargetTexture.renderList;
  73125. },
  73126. enumerable: true,
  73127. configurable: true
  73128. });
  73129. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73130. this._attachedMesh = mesh;
  73131. };
  73132. /**
  73133. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73134. *
  73135. * @param renderingGroupId The rendering group id corresponding to its index
  73136. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73137. */
  73138. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73139. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73140. };
  73141. ReflectionProbe.prototype.dispose = function () {
  73142. var index = this._scene.reflectionProbes.indexOf(this);
  73143. if (index !== -1) {
  73144. // Remove from the scene if found
  73145. this._scene.reflectionProbes.splice(index, 1);
  73146. }
  73147. if (this._renderTargetTexture) {
  73148. this._renderTargetTexture.dispose();
  73149. this._renderTargetTexture = null;
  73150. }
  73151. };
  73152. return ReflectionProbe;
  73153. }());
  73154. BABYLON.ReflectionProbe = ReflectionProbe;
  73155. })(BABYLON || (BABYLON = {}));
  73156. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73157. var BABYLON;
  73158. (function (BABYLON) {
  73159. var Layer = /** @class */ (function () {
  73160. function Layer(name, imgUrl, scene, isBackground, color) {
  73161. this.name = name;
  73162. this.scale = new BABYLON.Vector2(1, 1);
  73163. this.offset = new BABYLON.Vector2(0, 0);
  73164. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73165. this.layerMask = 0x0FFFFFFF;
  73166. this._vertexBuffers = {};
  73167. // Events
  73168. /**
  73169. * An event triggered when the layer is disposed.
  73170. * @type {BABYLON.Observable}
  73171. */
  73172. this.onDisposeObservable = new BABYLON.Observable();
  73173. /**
  73174. * An event triggered before rendering the scene
  73175. * @type {BABYLON.Observable}
  73176. */
  73177. this.onBeforeRenderObservable = new BABYLON.Observable();
  73178. /**
  73179. * An event triggered after rendering the scene
  73180. * @type {BABYLON.Observable}
  73181. */
  73182. this.onAfterRenderObservable = new BABYLON.Observable();
  73183. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73184. this.isBackground = isBackground === undefined ? true : isBackground;
  73185. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73186. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73187. this._scene.layers.push(this);
  73188. var engine = this._scene.getEngine();
  73189. // VBO
  73190. var vertices = [];
  73191. vertices.push(1, 1);
  73192. vertices.push(-1, 1);
  73193. vertices.push(-1, -1);
  73194. vertices.push(1, -1);
  73195. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73197. this._createIndexBuffer();
  73198. // Effects
  73199. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73200. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73201. }
  73202. Object.defineProperty(Layer.prototype, "onDispose", {
  73203. set: function (callback) {
  73204. if (this._onDisposeObserver) {
  73205. this.onDisposeObservable.remove(this._onDisposeObserver);
  73206. }
  73207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73208. },
  73209. enumerable: true,
  73210. configurable: true
  73211. });
  73212. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73213. set: function (callback) {
  73214. if (this._onBeforeRenderObserver) {
  73215. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73216. }
  73217. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73218. },
  73219. enumerable: true,
  73220. configurable: true
  73221. });
  73222. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73223. set: function (callback) {
  73224. if (this._onAfterRenderObserver) {
  73225. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73226. }
  73227. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73228. },
  73229. enumerable: true,
  73230. configurable: true
  73231. });
  73232. Layer.prototype._createIndexBuffer = function () {
  73233. var engine = this._scene.getEngine();
  73234. // Indices
  73235. var indices = [];
  73236. indices.push(0);
  73237. indices.push(1);
  73238. indices.push(2);
  73239. indices.push(0);
  73240. indices.push(2);
  73241. indices.push(3);
  73242. this._indexBuffer = engine.createIndexBuffer(indices);
  73243. };
  73244. Layer.prototype._rebuild = function () {
  73245. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73246. if (vb) {
  73247. vb._rebuild();
  73248. }
  73249. this._createIndexBuffer();
  73250. };
  73251. Layer.prototype.render = function () {
  73252. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73253. // Check
  73254. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73255. return;
  73256. var engine = this._scene.getEngine();
  73257. this.onBeforeRenderObservable.notifyObservers(this);
  73258. // Render
  73259. engine.enableEffect(currentEffect);
  73260. engine.setState(false);
  73261. // Texture
  73262. currentEffect.setTexture("textureSampler", this.texture);
  73263. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73264. // Color
  73265. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73266. // Scale / offset
  73267. currentEffect.setVector2("offset", this.offset);
  73268. currentEffect.setVector2("scale", this.scale);
  73269. // VBOs
  73270. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73271. // Draw order
  73272. if (!this.alphaTest) {
  73273. engine.setAlphaMode(this.alphaBlendingMode);
  73274. engine.draw(true, 0, 6);
  73275. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73276. }
  73277. else {
  73278. engine.draw(true, 0, 6);
  73279. }
  73280. this.onAfterRenderObservable.notifyObservers(this);
  73281. };
  73282. Layer.prototype.dispose = function () {
  73283. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73284. if (vertexBuffer) {
  73285. vertexBuffer.dispose();
  73286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73287. }
  73288. if (this._indexBuffer) {
  73289. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73290. this._indexBuffer = null;
  73291. }
  73292. if (this.texture) {
  73293. this.texture.dispose();
  73294. this.texture = null;
  73295. }
  73296. // Remove from scene
  73297. var index = this._scene.layers.indexOf(this);
  73298. this._scene.layers.splice(index, 1);
  73299. // Callback
  73300. this.onDisposeObservable.notifyObservers(this);
  73301. this.onDisposeObservable.clear();
  73302. this.onAfterRenderObservable.clear();
  73303. this.onBeforeRenderObservable.clear();
  73304. };
  73305. return Layer;
  73306. }());
  73307. BABYLON.Layer = Layer;
  73308. })(BABYLON || (BABYLON = {}));
  73309. //# sourceMappingURL=babylon.layer.js.map
  73310. var BABYLON;
  73311. (function (BABYLON) {
  73312. var TextureTools = /** @class */ (function () {
  73313. function TextureTools() {
  73314. }
  73315. /**
  73316. * Uses the GPU to create a copy texture rescaled at a given size
  73317. * @param texture Texture to copy from
  73318. * @param width Desired width
  73319. * @param height Desired height
  73320. * @return Generated texture
  73321. */
  73322. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73323. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73324. var scene = texture.getScene();
  73325. var engine = scene.getEngine();
  73326. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73327. rtt.wrapU = texture.wrapU;
  73328. rtt.wrapV = texture.wrapV;
  73329. rtt.uOffset = texture.uOffset;
  73330. rtt.vOffset = texture.vOffset;
  73331. rtt.uScale = texture.uScale;
  73332. rtt.vScale = texture.vScale;
  73333. rtt.uAng = texture.uAng;
  73334. rtt.vAng = texture.vAng;
  73335. rtt.wAng = texture.wAng;
  73336. rtt.coordinatesIndex = texture.coordinatesIndex;
  73337. rtt.level = texture.level;
  73338. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73339. rtt._texture.isReady = false;
  73340. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73341. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73342. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73343. passPostProcess.getEffect().executeWhenCompiled(function () {
  73344. passPostProcess.onApply = function (effect) {
  73345. effect.setTexture("textureSampler", texture);
  73346. };
  73347. var internalTexture = rtt.getInternalTexture();
  73348. if (internalTexture) {
  73349. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73350. engine.unBindFramebuffer(internalTexture);
  73351. rtt.disposeFramebufferObjects();
  73352. passPostProcess.dispose();
  73353. internalTexture.isReady = true;
  73354. }
  73355. });
  73356. return rtt;
  73357. };
  73358. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73359. if (!scene._environmentBRDFTexture) {
  73360. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73361. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73362. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73363. scene._environmentBRDFTexture = texture;
  73364. }
  73365. return scene._environmentBRDFTexture;
  73366. };
  73367. 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=";
  73368. return TextureTools;
  73369. }());
  73370. BABYLON.TextureTools = TextureTools;
  73371. })(BABYLON || (BABYLON = {}));
  73372. //# sourceMappingURL=babylon.textureTools.js.map
  73373. var BABYLON;
  73374. (function (BABYLON) {
  73375. var FramingBehavior = /** @class */ (function () {
  73376. function FramingBehavior() {
  73377. this._mode = FramingBehavior.FitFrustumSidesMode;
  73378. this._radiusScale = 1.0;
  73379. this._positionScale = 0.5;
  73380. this._defaultElevation = 0.3;
  73381. this._elevationReturnTime = 1500;
  73382. this._elevationReturnWaitTime = 1000;
  73383. this._zoomStopsAnimation = false;
  73384. this._framingTime = 1500;
  73385. this._isPointerDown = false;
  73386. this._lastInteractionTime = -Infinity;
  73387. // Framing control
  73388. this._animatables = new Array();
  73389. this._betaIsAnimating = false;
  73390. }
  73391. Object.defineProperty(FramingBehavior.prototype, "name", {
  73392. get: function () {
  73393. return "Framing";
  73394. },
  73395. enumerable: true,
  73396. configurable: true
  73397. });
  73398. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73399. /**
  73400. * Gets current mode used by the behavior.
  73401. */
  73402. get: function () {
  73403. return this._mode;
  73404. },
  73405. /**
  73406. * Sets the current mode used by the behavior
  73407. */
  73408. set: function (mode) {
  73409. this._mode = mode;
  73410. },
  73411. enumerable: true,
  73412. configurable: true
  73413. });
  73414. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73415. /**
  73416. * Gets the scale applied to the radius
  73417. */
  73418. get: function () {
  73419. return this._radiusScale;
  73420. },
  73421. /**
  73422. * Sets the scale applied to the radius (1 by default)
  73423. */
  73424. set: function (radius) {
  73425. this._radiusScale = radius;
  73426. },
  73427. enumerable: true,
  73428. configurable: true
  73429. });
  73430. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73431. /**
  73432. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73433. */
  73434. get: function () {
  73435. return this._positionScale;
  73436. },
  73437. /**
  73438. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73439. */
  73440. set: function (scale) {
  73441. this._positionScale = scale;
  73442. },
  73443. enumerable: true,
  73444. configurable: true
  73445. });
  73446. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73447. /**
  73448. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73449. * behaviour is triggered, in radians.
  73450. */
  73451. get: function () {
  73452. return this._defaultElevation;
  73453. },
  73454. /**
  73455. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73456. * behaviour is triggered, in radians.
  73457. */
  73458. set: function (elevation) {
  73459. this._defaultElevation = elevation;
  73460. },
  73461. enumerable: true,
  73462. configurable: true
  73463. });
  73464. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73465. /**
  73466. * Gets the time (in milliseconds) taken to return to the default beta position.
  73467. * Negative value indicates camera should not return to default.
  73468. */
  73469. get: function () {
  73470. return this._elevationReturnTime;
  73471. },
  73472. /**
  73473. * Sets the time (in milliseconds) taken to return to the default beta position.
  73474. * Negative value indicates camera should not return to default.
  73475. */
  73476. set: function (speed) {
  73477. this._elevationReturnTime = speed;
  73478. },
  73479. enumerable: true,
  73480. configurable: true
  73481. });
  73482. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73483. /**
  73484. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73485. */
  73486. get: function () {
  73487. return this._elevationReturnWaitTime;
  73488. },
  73489. /**
  73490. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73491. */
  73492. set: function (time) {
  73493. this._elevationReturnWaitTime = time;
  73494. },
  73495. enumerable: true,
  73496. configurable: true
  73497. });
  73498. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73499. /**
  73500. * Gets the flag that indicates if user zooming should stop animation.
  73501. */
  73502. get: function () {
  73503. return this._zoomStopsAnimation;
  73504. },
  73505. /**
  73506. * Sets the flag that indicates if user zooming should stop animation.
  73507. */
  73508. set: function (flag) {
  73509. this._zoomStopsAnimation = flag;
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73515. /**
  73516. * Gets the transition time when framing the mesh, in milliseconds
  73517. */
  73518. get: function () {
  73519. return this._framingTime;
  73520. },
  73521. /**
  73522. * Sets the transition time when framing the mesh, in milliseconds
  73523. */
  73524. set: function (time) {
  73525. this._framingTime = time;
  73526. },
  73527. enumerable: true,
  73528. configurable: true
  73529. });
  73530. FramingBehavior.prototype.attach = function (camera) {
  73531. var _this = this;
  73532. this._attachedCamera = camera;
  73533. var scene = this._attachedCamera.getScene();
  73534. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73535. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73536. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73537. _this._isPointerDown = true;
  73538. return;
  73539. }
  73540. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73541. _this._isPointerDown = false;
  73542. }
  73543. });
  73544. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73545. if (mesh) {
  73546. _this.zoomOnMesh(mesh);
  73547. }
  73548. });
  73549. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73550. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73551. _this._applyUserInteraction();
  73552. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73553. // back to the default position after a given timeout
  73554. _this._maintainCameraAboveGround();
  73555. });
  73556. };
  73557. FramingBehavior.prototype.detach = function () {
  73558. if (!this._attachedCamera) {
  73559. return;
  73560. }
  73561. var scene = this._attachedCamera.getScene();
  73562. if (this._onPrePointerObservableObserver) {
  73563. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73564. }
  73565. if (this._onAfterCheckInputsObserver) {
  73566. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73567. }
  73568. if (this._onMeshTargetChangedObserver) {
  73569. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73570. }
  73571. this._attachedCamera = null;
  73572. };
  73573. /**
  73574. * Targets the given mesh and updates zoom level accordingly.
  73575. * @param mesh The mesh to target.
  73576. * @param radius Optional. If a cached radius position already exists, overrides default.
  73577. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73578. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73579. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73580. */
  73581. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73582. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73583. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73584. mesh.computeWorldMatrix(true);
  73585. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73586. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73587. };
  73588. /**
  73589. * Targets the given mesh and updates zoom level accordingly.
  73590. * @param mesh The mesh to target.
  73591. * @param radius Optional. If a cached radius position already exists, overrides default.
  73592. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73593. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73594. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73595. */
  73596. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73597. var _this = this;
  73598. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73599. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73600. var zoomTarget;
  73601. if (!this._attachedCamera) {
  73602. return;
  73603. }
  73604. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73605. var bottom = minimumWorld.y;
  73606. var top = maximumWorld.y;
  73607. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73608. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73609. if (focusOnOriginXZ) {
  73610. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73611. }
  73612. else {
  73613. var centerWorld = minimumWorld.add(radiusWorld);
  73614. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73615. }
  73616. if (!this._vectorTransition) {
  73617. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73618. }
  73619. this._betaIsAnimating = true;
  73620. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73621. if (animatable) {
  73622. this._animatables.push(animatable);
  73623. }
  73624. // sets the radius and lower radius bounds
  73625. // Small delta ensures camera is not always at lower zoom limit.
  73626. var radius = 0;
  73627. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73628. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73629. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73630. radius = position;
  73631. }
  73632. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73633. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73634. if (this._attachedCamera.lowerRadiusLimit === null) {
  73635. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73636. }
  73637. }
  73638. // Set sensibilities
  73639. var extend = maximumWorld.subtract(minimumWorld).length();
  73640. this._attachedCamera.panningSensibility = 5000 / extend;
  73641. this._attachedCamera.wheelPrecision = 100 / radius;
  73642. // transition to new radius
  73643. if (!this._radiusTransition) {
  73644. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73645. }
  73646. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73647. if (onAnimationEnd) {
  73648. onAnimationEnd();
  73649. }
  73650. if (_this._attachedCamera) {
  73651. _this._attachedCamera.storeState();
  73652. }
  73653. });
  73654. if (animatable) {
  73655. this._animatables.push(animatable);
  73656. }
  73657. };
  73658. /**
  73659. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73660. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73661. * frustum width.
  73662. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73663. * to fully enclose the mesh in the viewing frustum.
  73664. */
  73665. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73666. var size = maximumWorld.subtract(minimumWorld);
  73667. var boxVectorGlobalDiagonal = size.length();
  73668. var frustumSlope = this._getFrustumSlope();
  73669. // Formula for setting distance
  73670. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73671. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73672. // Horizon distance
  73673. var radius = radiusWithoutFraming * this._radiusScale;
  73674. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73675. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73676. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73677. var camera = this._attachedCamera;
  73678. if (!camera) {
  73679. return 0;
  73680. }
  73681. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73682. // Don't exceed the requested limit
  73683. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73684. }
  73685. // Don't exceed the upper radius limit
  73686. if (camera.upperRadiusLimit) {
  73687. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73688. }
  73689. return distance;
  73690. };
  73691. /**
  73692. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73693. * is automatically returned to its default position (expected to be above ground plane).
  73694. */
  73695. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73696. var _this = this;
  73697. if (this._elevationReturnTime < 0) {
  73698. return;
  73699. }
  73700. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73701. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73702. var limitBeta = Math.PI * 0.5;
  73703. // Bring the camera back up if below the ground plane
  73704. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73705. this._betaIsAnimating = true;
  73706. //Transition to new position
  73707. this.stopAllAnimations();
  73708. if (!this._betaTransition) {
  73709. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73710. }
  73711. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73712. _this._clearAnimationLocks();
  73713. _this.stopAllAnimations();
  73714. });
  73715. if (animatabe) {
  73716. this._animatables.push(animatabe);
  73717. }
  73718. }
  73719. };
  73720. /**
  73721. * Returns the frustum slope based on the canvas ratio and camera FOV
  73722. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73723. */
  73724. FramingBehavior.prototype._getFrustumSlope = function () {
  73725. // Calculate the viewport ratio
  73726. // Aspect Ratio is Height/Width.
  73727. var camera = this._attachedCamera;
  73728. if (!camera) {
  73729. return BABYLON.Vector2.Zero();
  73730. }
  73731. var engine = camera.getScene().getEngine();
  73732. var aspectRatio = engine.getAspectRatio(camera);
  73733. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73734. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73735. var frustumSlopeY = Math.tan(camera.fov / 2);
  73736. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73737. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73738. // along the forward vector.
  73739. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73740. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73741. };
  73742. /**
  73743. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73744. */
  73745. FramingBehavior.prototype._clearAnimationLocks = function () {
  73746. this._betaIsAnimating = false;
  73747. };
  73748. /**
  73749. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73750. */
  73751. FramingBehavior.prototype._applyUserInteraction = function () {
  73752. if (this.isUserIsMoving) {
  73753. this._lastInteractionTime = BABYLON.Tools.Now;
  73754. this.stopAllAnimations();
  73755. this._clearAnimationLocks();
  73756. }
  73757. };
  73758. /**
  73759. * Stops and removes all animations that have been applied to the camera
  73760. */
  73761. FramingBehavior.prototype.stopAllAnimations = function () {
  73762. if (this._attachedCamera) {
  73763. this._attachedCamera.animations = [];
  73764. }
  73765. while (this._animatables.length) {
  73766. if (this._animatables[0]) {
  73767. this._animatables[0].onAnimationEnd = null;
  73768. this._animatables[0].stop();
  73769. }
  73770. this._animatables.shift();
  73771. }
  73772. };
  73773. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73774. /**
  73775. * Gets a value indicating if the user is moving the camera
  73776. */
  73777. get: function () {
  73778. if (!this._attachedCamera) {
  73779. return false;
  73780. }
  73781. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73782. this._attachedCamera.inertialBetaOffset !== 0 ||
  73783. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73784. this._attachedCamera.inertialPanningX !== 0 ||
  73785. this._attachedCamera.inertialPanningY !== 0 ||
  73786. this._isPointerDown;
  73787. },
  73788. enumerable: true,
  73789. configurable: true
  73790. });
  73791. /**
  73792. * The easing function used by animations
  73793. */
  73794. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73795. /**
  73796. * The easing mode used by animations
  73797. */
  73798. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73799. // Statics
  73800. /**
  73801. * The camera can move all the way towards the mesh.
  73802. */
  73803. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73804. /**
  73805. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73806. */
  73807. FramingBehavior.FitFrustumSidesMode = 1;
  73808. return FramingBehavior;
  73809. }());
  73810. BABYLON.FramingBehavior = FramingBehavior;
  73811. })(BABYLON || (BABYLON = {}));
  73812. //# sourceMappingURL=babylon.framingBehavior.js.map
  73813. var BABYLON;
  73814. (function (BABYLON) {
  73815. /**
  73816. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73817. */
  73818. var BouncingBehavior = /** @class */ (function () {
  73819. function BouncingBehavior() {
  73820. /**
  73821. * The duration of the animation, in milliseconds
  73822. */
  73823. this.transitionDuration = 450;
  73824. /**
  73825. * Length of the distance animated by the transition when lower radius is reached
  73826. */
  73827. this.lowerRadiusTransitionRange = 2;
  73828. /**
  73829. * Length of the distance animated by the transition when upper radius is reached
  73830. */
  73831. this.upperRadiusTransitionRange = -2;
  73832. this._autoTransitionRange = false;
  73833. // Animations
  73834. this._radiusIsAnimating = false;
  73835. this._radiusBounceTransition = null;
  73836. this._animatables = new Array();
  73837. }
  73838. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73839. get: function () {
  73840. return "Bouncing";
  73841. },
  73842. enumerable: true,
  73843. configurable: true
  73844. });
  73845. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73846. /**
  73847. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73848. */
  73849. get: function () {
  73850. return this._autoTransitionRange;
  73851. },
  73852. /**
  73853. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73854. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73855. */
  73856. set: function (value) {
  73857. var _this = this;
  73858. if (this._autoTransitionRange === value) {
  73859. return;
  73860. }
  73861. this._autoTransitionRange = value;
  73862. var camera = this._attachedCamera;
  73863. if (!camera) {
  73864. return;
  73865. }
  73866. if (value) {
  73867. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73868. if (!mesh) {
  73869. return;
  73870. }
  73871. mesh.computeWorldMatrix(true);
  73872. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73873. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73874. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73875. });
  73876. }
  73877. else if (this._onMeshTargetChangedObserver) {
  73878. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73879. }
  73880. },
  73881. enumerable: true,
  73882. configurable: true
  73883. });
  73884. BouncingBehavior.prototype.attach = function (camera) {
  73885. var _this = this;
  73886. this._attachedCamera = camera;
  73887. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73888. if (!_this._attachedCamera) {
  73889. return;
  73890. }
  73891. // Add the bounce animation to the lower radius limit
  73892. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73893. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73894. }
  73895. // Add the bounce animation to the upper radius limit
  73896. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73897. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73898. }
  73899. });
  73900. };
  73901. BouncingBehavior.prototype.detach = function () {
  73902. if (!this._attachedCamera) {
  73903. return;
  73904. }
  73905. if (this._onAfterCheckInputsObserver) {
  73906. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73907. }
  73908. if (this._onMeshTargetChangedObserver) {
  73909. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73910. }
  73911. this._attachedCamera = null;
  73912. };
  73913. /**
  73914. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  73915. * @param radiusLimit The limit to check against.
  73916. * @return Bool to indicate if at limit.
  73917. */
  73918. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  73919. if (!this._attachedCamera) {
  73920. return false;
  73921. }
  73922. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  73923. return true;
  73924. }
  73925. return false;
  73926. };
  73927. /**
  73928. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  73929. * @param radiusDelta The delta by which to animate to. Can be negative.
  73930. */
  73931. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  73932. var _this = this;
  73933. if (!this._attachedCamera) {
  73934. return;
  73935. }
  73936. if (!this._radiusBounceTransition) {
  73937. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  73938. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  73939. }
  73940. // Prevent zoom until bounce has completed
  73941. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  73942. this._attachedCamera.wheelPrecision = Infinity;
  73943. this._attachedCamera.inertialRadiusOffset = 0;
  73944. // Animate to the radius limit
  73945. this.stopAllAnimations();
  73946. this._radiusIsAnimating = true;
  73947. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  73948. if (animatable) {
  73949. this._animatables.push(animatable);
  73950. }
  73951. };
  73952. /**
  73953. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  73954. */
  73955. BouncingBehavior.prototype._clearAnimationLocks = function () {
  73956. this._radiusIsAnimating = false;
  73957. if (this._attachedCamera) {
  73958. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  73959. }
  73960. };
  73961. /**
  73962. * Stops and removes all animations that have been applied to the camera
  73963. */
  73964. BouncingBehavior.prototype.stopAllAnimations = function () {
  73965. if (this._attachedCamera) {
  73966. this._attachedCamera.animations = [];
  73967. }
  73968. while (this._animatables.length) {
  73969. this._animatables[0].onAnimationEnd = null;
  73970. this._animatables[0].stop();
  73971. this._animatables.shift();
  73972. }
  73973. };
  73974. /**
  73975. * The easing function used by animations
  73976. */
  73977. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  73978. /**
  73979. * The easing mode used by animations
  73980. */
  73981. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  73982. return BouncingBehavior;
  73983. }());
  73984. BABYLON.BouncingBehavior = BouncingBehavior;
  73985. })(BABYLON || (BABYLON = {}));
  73986. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  73987. var BABYLON;
  73988. (function (BABYLON) {
  73989. var AutoRotationBehavior = /** @class */ (function () {
  73990. function AutoRotationBehavior() {
  73991. this._zoomStopsAnimation = false;
  73992. this._idleRotationSpeed = 0.05;
  73993. this._idleRotationWaitTime = 2000;
  73994. this._idleRotationSpinupTime = 2000;
  73995. this._isPointerDown = false;
  73996. this._lastFrameTime = null;
  73997. this._lastInteractionTime = -Infinity;
  73998. this._cameraRotationSpeed = 0;
  73999. this._lastFrameRadius = 0;
  74000. }
  74001. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74002. get: function () {
  74003. return "AutoRotation";
  74004. },
  74005. enumerable: true,
  74006. configurable: true
  74007. });
  74008. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74009. /**
  74010. * Gets the flag that indicates if user zooming should stop animation.
  74011. */
  74012. get: function () {
  74013. return this._zoomStopsAnimation;
  74014. },
  74015. /**
  74016. * Sets the flag that indicates if user zooming should stop animation.
  74017. */
  74018. set: function (flag) {
  74019. this._zoomStopsAnimation = flag;
  74020. },
  74021. enumerable: true,
  74022. configurable: true
  74023. });
  74024. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74025. /**
  74026. * Gets the default speed at which the camera rotates around the model.
  74027. */
  74028. get: function () {
  74029. return this._idleRotationSpeed;
  74030. },
  74031. /**
  74032. * Sets the default speed at which the camera rotates around the model.
  74033. */
  74034. set: function (speed) {
  74035. this._idleRotationSpeed = speed;
  74036. },
  74037. enumerable: true,
  74038. configurable: true
  74039. });
  74040. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74041. /**
  74042. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74043. */
  74044. get: function () {
  74045. return this._idleRotationWaitTime;
  74046. },
  74047. /**
  74048. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74049. */
  74050. set: function (time) {
  74051. this._idleRotationWaitTime = time;
  74052. },
  74053. enumerable: true,
  74054. configurable: true
  74055. });
  74056. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74057. /**
  74058. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74059. */
  74060. get: function () {
  74061. return this._idleRotationSpinupTime;
  74062. },
  74063. /**
  74064. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74065. */
  74066. set: function (time) {
  74067. this._idleRotationSpinupTime = time;
  74068. },
  74069. enumerable: true,
  74070. configurable: true
  74071. });
  74072. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74073. /**
  74074. * Gets a value indicating if the camera is currently rotating because of this behavior
  74075. */
  74076. get: function () {
  74077. return Math.abs(this._cameraRotationSpeed) > 0;
  74078. },
  74079. enumerable: true,
  74080. configurable: true
  74081. });
  74082. AutoRotationBehavior.prototype.attach = function (camera) {
  74083. var _this = this;
  74084. this._attachedCamera = camera;
  74085. var scene = this._attachedCamera.getScene();
  74086. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74087. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74088. _this._isPointerDown = true;
  74089. return;
  74090. }
  74091. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74092. _this._isPointerDown = false;
  74093. }
  74094. });
  74095. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74096. var now = BABYLON.Tools.Now;
  74097. var dt = 0;
  74098. if (_this._lastFrameTime != null) {
  74099. dt = now - _this._lastFrameTime;
  74100. }
  74101. _this._lastFrameTime = now;
  74102. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74103. _this._applyUserInteraction();
  74104. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74105. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74106. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74107. // Step camera rotation by rotation speed
  74108. if (_this._attachedCamera) {
  74109. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74110. }
  74111. });
  74112. };
  74113. AutoRotationBehavior.prototype.detach = function () {
  74114. if (!this._attachedCamera) {
  74115. return;
  74116. }
  74117. var scene = this._attachedCamera.getScene();
  74118. if (this._onPrePointerObservableObserver) {
  74119. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74120. }
  74121. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74122. this._attachedCamera = null;
  74123. };
  74124. /**
  74125. * Returns true if user is scrolling.
  74126. * @return true if user is scrolling.
  74127. */
  74128. AutoRotationBehavior.prototype._userIsZooming = function () {
  74129. if (!this._attachedCamera) {
  74130. return false;
  74131. }
  74132. return this._attachedCamera.inertialRadiusOffset !== 0;
  74133. };
  74134. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74135. if (!this._attachedCamera) {
  74136. return false;
  74137. }
  74138. var zoomHasHitLimit = false;
  74139. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74140. zoomHasHitLimit = true;
  74141. }
  74142. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74143. this._lastFrameRadius = this._attachedCamera.radius;
  74144. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74145. };
  74146. /**
  74147. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74148. */
  74149. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74150. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74151. this._lastInteractionTime = BABYLON.Tools.Now;
  74152. }
  74153. };
  74154. // Tools
  74155. AutoRotationBehavior.prototype._userIsMoving = function () {
  74156. if (!this._attachedCamera) {
  74157. return false;
  74158. }
  74159. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74160. this._attachedCamera.inertialBetaOffset !== 0 ||
  74161. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74162. this._attachedCamera.inertialPanningX !== 0 ||
  74163. this._attachedCamera.inertialPanningY !== 0 ||
  74164. this._isPointerDown;
  74165. };
  74166. return AutoRotationBehavior;
  74167. }());
  74168. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74169. })(BABYLON || (BABYLON = {}));
  74170. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74171. var BABYLON;
  74172. (function (BABYLON) {
  74173. /**
  74174. * This class can be used to get instrumentation data from a Babylon engine
  74175. */
  74176. var EngineInstrumentation = /** @class */ (function () {
  74177. function EngineInstrumentation(engine) {
  74178. this.engine = engine;
  74179. this._captureGPUFrameTime = false;
  74180. this._gpuFrameTime = new BABYLON.PerfCounter();
  74181. this._captureShaderCompilationTime = false;
  74182. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74183. // Observers
  74184. this._onBeginFrameObserver = null;
  74185. this._onEndFrameObserver = null;
  74186. this._onBeforeShaderCompilationObserver = null;
  74187. this._onAfterShaderCompilationObserver = null;
  74188. }
  74189. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74190. // Properties
  74191. /**
  74192. * Gets the perf counter used for GPU frame time
  74193. */
  74194. get: function () {
  74195. return this._gpuFrameTime;
  74196. },
  74197. enumerable: true,
  74198. configurable: true
  74199. });
  74200. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74201. /**
  74202. * Gets the GPU frame time capture status
  74203. */
  74204. get: function () {
  74205. return this._captureGPUFrameTime;
  74206. },
  74207. /**
  74208. * Enable or disable the GPU frame time capture
  74209. */
  74210. set: function (value) {
  74211. var _this = this;
  74212. if (value === this._captureGPUFrameTime) {
  74213. return;
  74214. }
  74215. this._captureGPUFrameTime = value;
  74216. if (value) {
  74217. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74218. if (!_this._gpuFrameTimeToken) {
  74219. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74220. }
  74221. });
  74222. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74223. if (!_this._gpuFrameTimeToken) {
  74224. return;
  74225. }
  74226. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74227. if (time > -1) {
  74228. _this._gpuFrameTimeToken = null;
  74229. _this._gpuFrameTime.fetchNewFrame();
  74230. _this._gpuFrameTime.addCount(time, true);
  74231. }
  74232. });
  74233. }
  74234. else {
  74235. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74236. this._onBeginFrameObserver = null;
  74237. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74238. this._onEndFrameObserver = null;
  74239. }
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74245. /**
  74246. * Gets the perf counter used for shader compilation time
  74247. */
  74248. get: function () {
  74249. return this._shaderCompilationTime;
  74250. },
  74251. enumerable: true,
  74252. configurable: true
  74253. });
  74254. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74255. /**
  74256. * Gets the shader compilation time capture status
  74257. */
  74258. get: function () {
  74259. return this._captureShaderCompilationTime;
  74260. },
  74261. /**
  74262. * Enable or disable the shader compilation time capture
  74263. */
  74264. set: function (value) {
  74265. var _this = this;
  74266. if (value === this._captureShaderCompilationTime) {
  74267. return;
  74268. }
  74269. this._captureShaderCompilationTime = value;
  74270. if (value) {
  74271. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74272. _this._shaderCompilationTime.fetchNewFrame();
  74273. _this._shaderCompilationTime.beginMonitoring();
  74274. });
  74275. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74276. _this._shaderCompilationTime.endMonitoring();
  74277. });
  74278. }
  74279. else {
  74280. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74281. this._onBeforeShaderCompilationObserver = null;
  74282. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74283. this._onAfterShaderCompilationObserver = null;
  74284. }
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. EngineInstrumentation.prototype.dispose = function () {
  74290. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74291. this._onBeginFrameObserver = null;
  74292. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74293. this._onEndFrameObserver = null;
  74294. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74295. this._onBeforeShaderCompilationObserver = null;
  74296. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74297. this._onAfterShaderCompilationObserver = null;
  74298. this.engine = null;
  74299. };
  74300. return EngineInstrumentation;
  74301. }());
  74302. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74303. })(BABYLON || (BABYLON = {}));
  74304. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74305. var BABYLON;
  74306. (function (BABYLON) {
  74307. /**
  74308. * This class can be used to get instrumentation data from a Babylon engine
  74309. */
  74310. var SceneInstrumentation = /** @class */ (function () {
  74311. function SceneInstrumentation(scene) {
  74312. var _this = this;
  74313. this.scene = scene;
  74314. this._captureActiveMeshesEvaluationTime = false;
  74315. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74316. this._captureRenderTargetsRenderTime = false;
  74317. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74318. this._captureFrameTime = false;
  74319. this._frameTime = new BABYLON.PerfCounter();
  74320. this._captureRenderTime = false;
  74321. this._renderTime = new BABYLON.PerfCounter();
  74322. this._captureInterFrameTime = false;
  74323. this._interFrameTime = new BABYLON.PerfCounter();
  74324. this._captureParticlesRenderTime = false;
  74325. this._particlesRenderTime = new BABYLON.PerfCounter();
  74326. this._captureSpritesRenderTime = false;
  74327. this._spritesRenderTime = new BABYLON.PerfCounter();
  74328. this._capturePhysicsTime = false;
  74329. this._physicsTime = new BABYLON.PerfCounter();
  74330. // Observers
  74331. this._onBeforeActiveMeshesEvaluationObserver = null;
  74332. this._onAfterActiveMeshesEvaluationObserver = null;
  74333. this._onBeforeRenderTargetsRenderObserver = null;
  74334. this._onAfterRenderTargetsRenderObserver = null;
  74335. this._onAfterRenderObserver = null;
  74336. this._onBeforeDrawPhaseObserver = null;
  74337. this._onAfterDrawPhaseObserver = null;
  74338. this._onBeforeAnimationsObserver = null;
  74339. this._onBeforeParticlesRenderingObserver = null;
  74340. this._onAfterParticlesRenderingObserver = null;
  74341. this._onBeforeSpritesRenderingObserver = null;
  74342. this._onAfterSpritesRenderingObserver = null;
  74343. this._onBeforePhysicsObserver = null;
  74344. this._onAfterPhysicsObserver = null;
  74345. // Before render
  74346. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74347. if (_this._captureActiveMeshesEvaluationTime) {
  74348. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74349. }
  74350. if (_this._captureRenderTargetsRenderTime) {
  74351. _this._renderTargetsRenderTime.fetchNewFrame();
  74352. }
  74353. if (_this._captureFrameTime) {
  74354. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74355. _this._frameTime.beginMonitoring();
  74356. }
  74357. if (_this._captureInterFrameTime) {
  74358. _this._interFrameTime.endMonitoring();
  74359. }
  74360. if (_this._captureParticlesRenderTime) {
  74361. _this._particlesRenderTime.fetchNewFrame();
  74362. }
  74363. if (_this._captureSpritesRenderTime) {
  74364. _this._spritesRenderTime.fetchNewFrame();
  74365. }
  74366. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74367. });
  74368. // After render
  74369. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74370. if (_this._captureFrameTime) {
  74371. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74372. _this._frameTime.endMonitoring();
  74373. }
  74374. if (_this._captureRenderTime) {
  74375. _this._renderTime.endMonitoring(false);
  74376. }
  74377. if (_this._captureInterFrameTime) {
  74378. _this._interFrameTime.beginMonitoring();
  74379. }
  74380. });
  74381. }
  74382. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74383. // Properties
  74384. /**
  74385. * Gets the perf counter used for active meshes evaluation time
  74386. */
  74387. get: function () {
  74388. return this._activeMeshesEvaluationTime;
  74389. },
  74390. enumerable: true,
  74391. configurable: true
  74392. });
  74393. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74394. /**
  74395. * Gets the active meshes evaluation time capture status
  74396. */
  74397. get: function () {
  74398. return this._captureActiveMeshesEvaluationTime;
  74399. },
  74400. /**
  74401. * Enable or disable the active meshes evaluation time capture
  74402. */
  74403. set: function (value) {
  74404. var _this = this;
  74405. if (value === this._captureActiveMeshesEvaluationTime) {
  74406. return;
  74407. }
  74408. this._captureActiveMeshesEvaluationTime = value;
  74409. if (value) {
  74410. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74411. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74412. _this._activeMeshesEvaluationTime.beginMonitoring();
  74413. });
  74414. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74415. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74416. _this._activeMeshesEvaluationTime.endMonitoring();
  74417. });
  74418. }
  74419. else {
  74420. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74421. this._onBeforeActiveMeshesEvaluationObserver = null;
  74422. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74423. this._onAfterActiveMeshesEvaluationObserver = null;
  74424. }
  74425. },
  74426. enumerable: true,
  74427. configurable: true
  74428. });
  74429. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74430. /**
  74431. * Gets the perf counter used for render targets render time
  74432. */
  74433. get: function () {
  74434. return this._renderTargetsRenderTime;
  74435. },
  74436. enumerable: true,
  74437. configurable: true
  74438. });
  74439. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74440. /**
  74441. * Gets the render targets render time capture status
  74442. */
  74443. get: function () {
  74444. return this._captureRenderTargetsRenderTime;
  74445. },
  74446. /**
  74447. * Enable or disable the render targets render time capture
  74448. */
  74449. set: function (value) {
  74450. var _this = this;
  74451. if (value === this._captureRenderTargetsRenderTime) {
  74452. return;
  74453. }
  74454. this._captureRenderTargetsRenderTime = value;
  74455. if (value) {
  74456. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74457. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74458. _this._renderTargetsRenderTime.beginMonitoring();
  74459. });
  74460. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74461. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74462. _this._renderTargetsRenderTime.endMonitoring(false);
  74463. });
  74464. }
  74465. else {
  74466. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74467. this._onBeforeRenderTargetsRenderObserver = null;
  74468. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74469. this._onAfterRenderTargetsRenderObserver = null;
  74470. }
  74471. },
  74472. enumerable: true,
  74473. configurable: true
  74474. });
  74475. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74476. /**
  74477. * Gets the perf counter used for particles render time
  74478. */
  74479. get: function () {
  74480. return this._particlesRenderTime;
  74481. },
  74482. enumerable: true,
  74483. configurable: true
  74484. });
  74485. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74486. /**
  74487. * Gets the particles render time capture status
  74488. */
  74489. get: function () {
  74490. return this._captureParticlesRenderTime;
  74491. },
  74492. /**
  74493. * Enable or disable the particles render time capture
  74494. */
  74495. set: function (value) {
  74496. var _this = this;
  74497. if (value === this._captureParticlesRenderTime) {
  74498. return;
  74499. }
  74500. this._captureParticlesRenderTime = value;
  74501. if (value) {
  74502. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74503. BABYLON.Tools.StartPerformanceCounter("Particles");
  74504. _this._particlesRenderTime.beginMonitoring();
  74505. });
  74506. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74507. BABYLON.Tools.EndPerformanceCounter("Particles");
  74508. _this._particlesRenderTime.endMonitoring(false);
  74509. });
  74510. }
  74511. else {
  74512. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74513. this._onBeforeParticlesRenderingObserver = null;
  74514. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74515. this._onAfterParticlesRenderingObserver = null;
  74516. }
  74517. },
  74518. enumerable: true,
  74519. configurable: true
  74520. });
  74521. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74522. /**
  74523. * Gets the perf counter used for sprites render time
  74524. */
  74525. get: function () {
  74526. return this._spritesRenderTime;
  74527. },
  74528. enumerable: true,
  74529. configurable: true
  74530. });
  74531. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74532. /**
  74533. * Gets the sprites render time capture status
  74534. */
  74535. get: function () {
  74536. return this._captureSpritesRenderTime;
  74537. },
  74538. /**
  74539. * Enable or disable the sprites render time capture
  74540. */
  74541. set: function (value) {
  74542. var _this = this;
  74543. if (value === this._captureSpritesRenderTime) {
  74544. return;
  74545. }
  74546. this._captureSpritesRenderTime = value;
  74547. if (value) {
  74548. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74549. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74550. _this._spritesRenderTime.beginMonitoring();
  74551. });
  74552. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74553. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74554. _this._spritesRenderTime.endMonitoring(false);
  74555. });
  74556. }
  74557. else {
  74558. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74559. this._onBeforeSpritesRenderingObserver = null;
  74560. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74561. this._onAfterSpritesRenderingObserver = null;
  74562. }
  74563. },
  74564. enumerable: true,
  74565. configurable: true
  74566. });
  74567. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74568. /**
  74569. * Gets the perf counter used for physics time
  74570. */
  74571. get: function () {
  74572. return this._physicsTime;
  74573. },
  74574. enumerable: true,
  74575. configurable: true
  74576. });
  74577. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74578. /**
  74579. * Gets the physics time capture status
  74580. */
  74581. get: function () {
  74582. return this._capturePhysicsTime;
  74583. },
  74584. /**
  74585. * Enable or disable the physics time capture
  74586. */
  74587. set: function (value) {
  74588. var _this = this;
  74589. if (value === this._capturePhysicsTime) {
  74590. return;
  74591. }
  74592. this._capturePhysicsTime = value;
  74593. if (value) {
  74594. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74595. BABYLON.Tools.StartPerformanceCounter("Physics");
  74596. _this._physicsTime.beginMonitoring();
  74597. });
  74598. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74599. BABYLON.Tools.EndPerformanceCounter("Physics");
  74600. _this._physicsTime.endMonitoring();
  74601. });
  74602. }
  74603. else {
  74604. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74605. this._onBeforePhysicsObserver = null;
  74606. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74607. this._onAfterPhysicsObserver = null;
  74608. }
  74609. },
  74610. enumerable: true,
  74611. configurable: true
  74612. });
  74613. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74614. /**
  74615. * Gets the perf counter used for frame time capture
  74616. */
  74617. get: function () {
  74618. return this._frameTime;
  74619. },
  74620. enumerable: true,
  74621. configurable: true
  74622. });
  74623. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74624. /**
  74625. * Gets the frame time capture status
  74626. */
  74627. get: function () {
  74628. return this._captureFrameTime;
  74629. },
  74630. /**
  74631. * Enable or disable the frame time capture
  74632. */
  74633. set: function (value) {
  74634. this._captureFrameTime = value;
  74635. },
  74636. enumerable: true,
  74637. configurable: true
  74638. });
  74639. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  74640. /**
  74641. * Gets the perf counter used for inter-frames time capture
  74642. */
  74643. get: function () {
  74644. return this._interFrameTime;
  74645. },
  74646. enumerable: true,
  74647. configurable: true
  74648. });
  74649. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  74650. /**
  74651. * Gets the inter-frames time capture status
  74652. */
  74653. get: function () {
  74654. return this._captureInterFrameTime;
  74655. },
  74656. /**
  74657. * Enable or disable the inter-frames time capture
  74658. */
  74659. set: function (value) {
  74660. this._captureInterFrameTime = value;
  74661. },
  74662. enumerable: true,
  74663. configurable: true
  74664. });
  74665. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  74666. /**
  74667. * Gets the perf counter used for render time capture
  74668. */
  74669. get: function () {
  74670. return this._renderTime;
  74671. },
  74672. enumerable: true,
  74673. configurable: true
  74674. });
  74675. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  74676. /**
  74677. * Gets the render time capture status
  74678. */
  74679. get: function () {
  74680. return this._captureRenderTime;
  74681. },
  74682. /**
  74683. * Enable or disable the render time capture
  74684. */
  74685. set: function (value) {
  74686. var _this = this;
  74687. if (value === this._captureRenderTime) {
  74688. return;
  74689. }
  74690. this._captureRenderTime = value;
  74691. if (value) {
  74692. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  74693. _this._renderTime.beginMonitoring();
  74694. BABYLON.Tools.StartPerformanceCounter("Main render");
  74695. });
  74696. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  74697. _this._renderTime.endMonitoring(false);
  74698. BABYLON.Tools.EndPerformanceCounter("Main render");
  74699. });
  74700. }
  74701. else {
  74702. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74703. this._onBeforeDrawPhaseObserver = null;
  74704. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74705. this._onAfterDrawPhaseObserver = null;
  74706. }
  74707. },
  74708. enumerable: true,
  74709. configurable: true
  74710. });
  74711. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  74712. /**
  74713. * Gets the perf counter used for frame time capture
  74714. */
  74715. get: function () {
  74716. return this.scene.getEngine()._drawCalls;
  74717. },
  74718. enumerable: true,
  74719. configurable: true
  74720. });
  74721. SceneInstrumentation.prototype.dispose = function () {
  74722. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74723. this._onAfterRenderObserver = null;
  74724. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74725. this._onBeforeActiveMeshesEvaluationObserver = null;
  74726. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74727. this._onAfterActiveMeshesEvaluationObserver = null;
  74728. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74729. this._onBeforeRenderTargetsRenderObserver = null;
  74730. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74731. this._onAfterRenderTargetsRenderObserver = null;
  74732. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  74733. this._onBeforeAnimationsObserver = null;
  74734. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74735. this._onBeforeParticlesRenderingObserver = null;
  74736. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74737. this._onAfterParticlesRenderingObserver = null;
  74738. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74739. this._onBeforeSpritesRenderingObserver = null;
  74740. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74741. this._onAfterSpritesRenderingObserver = null;
  74742. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74743. this._onBeforeDrawPhaseObserver = null;
  74744. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74745. this._onAfterDrawPhaseObserver = null;
  74746. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74747. this._onBeforePhysicsObserver = null;
  74748. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74749. this._onAfterPhysicsObserver = null;
  74750. this.scene = null;
  74751. };
  74752. return SceneInstrumentation;
  74753. }());
  74754. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74755. })(BABYLON || (BABYLON = {}));
  74756. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74757. var BABYLON;
  74758. (function (BABYLON) {
  74759. var _TimeToken = /** @class */ (function () {
  74760. function _TimeToken() {
  74761. this._timeElapsedQueryEnded = false;
  74762. }
  74763. return _TimeToken;
  74764. }());
  74765. BABYLON._TimeToken = _TimeToken;
  74766. })(BABYLON || (BABYLON = {}));
  74767. //# sourceMappingURL=babylon.timeToken.js.map
  74768. 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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\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;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\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(USESPHERICALINFRAGMENT)\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 AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\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#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  74769. 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}","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};"};
  74770. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74771. var BABYLON;
  74772. (function (BABYLON) {
  74773. var GridMaterialDefines = /** @class */ (function (_super) {
  74774. __extends(GridMaterialDefines, _super);
  74775. function GridMaterialDefines() {
  74776. var _this = _super.call(this) || this;
  74777. _this.TRANSPARENT = false;
  74778. _this.FOG = false;
  74779. _this.PREMULTIPLYALPHA = false;
  74780. _this.rebuild();
  74781. return _this;
  74782. }
  74783. return GridMaterialDefines;
  74784. }(BABYLON.MaterialDefines));
  74785. /**
  74786. * The grid materials allows you to wrap any shape with a grid.
  74787. * Colors are customizable.
  74788. */
  74789. var GridMaterial = /** @class */ (function (_super) {
  74790. __extends(GridMaterial, _super);
  74791. /**
  74792. * constructor
  74793. * @param name The name given to the material in order to identify it afterwards.
  74794. * @param scene The scene the material is used in.
  74795. */
  74796. function GridMaterial(name, scene) {
  74797. var _this = _super.call(this, name, scene) || this;
  74798. /**
  74799. * Main color of the grid (e.g. between lines)
  74800. */
  74801. _this.mainColor = BABYLON.Color3.Black();
  74802. /**
  74803. * Color of the grid lines.
  74804. */
  74805. _this.lineColor = BABYLON.Color3.Teal();
  74806. /**
  74807. * The scale of the grid compared to unit.
  74808. */
  74809. _this.gridRatio = 1.0;
  74810. /**
  74811. * Allows setting an offset for the grid lines.
  74812. */
  74813. _this.gridOffset = BABYLON.Vector3.Zero();
  74814. /**
  74815. * The frequency of thicker lines.
  74816. */
  74817. _this.majorUnitFrequency = 10;
  74818. /**
  74819. * The visibility of minor units in the grid.
  74820. */
  74821. _this.minorUnitVisibility = 0.33;
  74822. /**
  74823. * The grid opacity outside of the lines.
  74824. */
  74825. _this.opacity = 1.0;
  74826. /**
  74827. * Determine RBG output is premultiplied by alpha value.
  74828. */
  74829. _this.preMultiplyAlpha = false;
  74830. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74831. return _this;
  74832. }
  74833. /**
  74834. * Returns wehter or not the grid requires alpha blending.
  74835. */
  74836. GridMaterial.prototype.needAlphaBlending = function () {
  74837. return this.opacity < 1.0;
  74838. };
  74839. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74840. if (this.isFrozen) {
  74841. if (this._wasPreviouslyReady && subMesh.effect) {
  74842. return true;
  74843. }
  74844. }
  74845. if (!subMesh._materialDefines) {
  74846. subMesh._materialDefines = new GridMaterialDefines();
  74847. }
  74848. var defines = subMesh._materialDefines;
  74849. var scene = this.getScene();
  74850. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74851. if (this._renderId === scene.getRenderId()) {
  74852. return true;
  74853. }
  74854. }
  74855. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74856. defines.TRANSPARENT = !defines.TRANSPARENT;
  74857. defines.markAsUnprocessed();
  74858. }
  74859. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74860. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74861. defines.markAsUnprocessed();
  74862. }
  74863. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74864. // Get correct effect
  74865. if (defines.isDirty) {
  74866. defines.markAsProcessed();
  74867. scene.resetCachedMaterial();
  74868. // Attributes
  74869. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74870. // Defines
  74871. var join = defines.toString();
  74872. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  74873. }
  74874. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74875. return false;
  74876. }
  74877. this._renderId = scene.getRenderId();
  74878. this._wasPreviouslyReady = true;
  74879. return true;
  74880. };
  74881. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74882. var scene = this.getScene();
  74883. var defines = subMesh._materialDefines;
  74884. if (!defines) {
  74885. return;
  74886. }
  74887. var effect = subMesh.effect;
  74888. if (!effect) {
  74889. return;
  74890. }
  74891. this._activeEffect = effect;
  74892. // Matrices
  74893. this.bindOnlyWorldMatrix(world);
  74894. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  74895. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  74896. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  74897. // Uniforms
  74898. if (this._mustRebind(scene, effect)) {
  74899. this._activeEffect.setColor3("mainColor", this.mainColor);
  74900. this._activeEffect.setColor3("lineColor", this.lineColor);
  74901. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  74902. this._gridControl.x = this.gridRatio;
  74903. this._gridControl.y = Math.round(this.majorUnitFrequency);
  74904. this._gridControl.z = this.minorUnitVisibility;
  74905. this._gridControl.w = this.opacity;
  74906. this._activeEffect.setVector4("gridControl", this._gridControl);
  74907. }
  74908. // Fog
  74909. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74910. this._afterBind(mesh, this._activeEffect);
  74911. };
  74912. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  74913. _super.prototype.dispose.call(this, forceDisposeEffect);
  74914. };
  74915. GridMaterial.prototype.clone = function (name) {
  74916. var _this = this;
  74917. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  74918. };
  74919. GridMaterial.prototype.serialize = function () {
  74920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74921. serializationObject.customType = "BABYLON.GridMaterial";
  74922. return serializationObject;
  74923. };
  74924. GridMaterial.prototype.getClassName = function () {
  74925. return "GridMaterial";
  74926. };
  74927. GridMaterial.Parse = function (source, scene, rootUrl) {
  74928. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  74929. };
  74930. __decorate([
  74931. BABYLON.serializeAsColor3()
  74932. ], GridMaterial.prototype, "mainColor", void 0);
  74933. __decorate([
  74934. BABYLON.serializeAsColor3()
  74935. ], GridMaterial.prototype, "lineColor", void 0);
  74936. __decorate([
  74937. BABYLON.serialize()
  74938. ], GridMaterial.prototype, "gridRatio", void 0);
  74939. __decorate([
  74940. BABYLON.serializeAsColor3()
  74941. ], GridMaterial.prototype, "gridOffset", void 0);
  74942. __decorate([
  74943. BABYLON.serialize()
  74944. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  74945. __decorate([
  74946. BABYLON.serialize()
  74947. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  74948. __decorate([
  74949. BABYLON.serialize()
  74950. ], GridMaterial.prototype, "opacity", void 0);
  74951. __decorate([
  74952. BABYLON.serialize()
  74953. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  74954. return GridMaterial;
  74955. }(BABYLON.PushMaterial));
  74956. BABYLON.GridMaterial = GridMaterial;
  74957. })(BABYLON || (BABYLON = {}));
  74958. //# sourceMappingURL=babylon.gridmaterial.js.map
  74959. 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}";
  74960. 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}";
  74961. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74962. var BABYLON;
  74963. (function (BABYLON) {
  74964. /**
  74965. * Background material defines definition.
  74966. */
  74967. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  74968. __extends(BackgroundMaterialDefines, _super);
  74969. /**
  74970. * Constructor of the defines.
  74971. */
  74972. function BackgroundMaterialDefines() {
  74973. var _this = _super.call(this) || this;
  74974. /**
  74975. * True if the diffuse texture is in use.
  74976. */
  74977. _this.DIFFUSE = false;
  74978. /**
  74979. * The direct UV channel to use.
  74980. */
  74981. _this.DIFFUSEDIRECTUV = 0;
  74982. /**
  74983. * True if the diffuse texture is in gamma space.
  74984. */
  74985. _this.GAMMADIFFUSE = false;
  74986. /**
  74987. * True if the diffuse texture has opacity in the alpha channel.
  74988. */
  74989. _this.DIFFUSEHASALPHA = false;
  74990. /**
  74991. * True if you want the material to fade to transparent at grazing angle.
  74992. */
  74993. _this.OPACITYFRESNEL = false;
  74994. /**
  74995. * True if an extra blur needs to be added in the reflection.
  74996. */
  74997. _this.REFLECTIONBLUR = false;
  74998. /**
  74999. * False if the current Webgl implementation does not support the texture lod extension.
  75000. */
  75001. _this.TEXTURELODSUPPORT = false;
  75002. /**
  75003. * True to ensure the data are premultiplied.
  75004. */
  75005. _this.PREMULTIPLYALPHA = false;
  75006. /**
  75007. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75008. */
  75009. _this.USERGBCOLOR = false;
  75010. // Image Processing Configuration.
  75011. _this.IMAGEPROCESSING = false;
  75012. _this.VIGNETTE = false;
  75013. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75014. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75015. _this.TONEMAPPING = false;
  75016. _this.CONTRAST = false;
  75017. _this.COLORCURVES = false;
  75018. _this.COLORGRADING = false;
  75019. _this.COLORGRADING3D = false;
  75020. _this.SAMPLER3DGREENDEPTH = false;
  75021. _this.SAMPLER3DBGRMAP = false;
  75022. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75023. _this.EXPOSURE = false;
  75024. // Reflection.
  75025. _this.REFLECTION = false;
  75026. _this.REFLECTIONMAP_3D = false;
  75027. _this.REFLECTIONMAP_SPHERICAL = false;
  75028. _this.REFLECTIONMAP_PLANAR = false;
  75029. _this.REFLECTIONMAP_CUBIC = false;
  75030. _this.REFLECTIONMAP_PROJECTION = false;
  75031. _this.REFLECTIONMAP_SKYBOX = false;
  75032. _this.REFLECTIONMAP_EXPLICIT = false;
  75033. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75034. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75035. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75036. _this.INVERTCUBICMAP = false;
  75037. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75038. _this.LODINREFLECTIONALPHA = false;
  75039. _this.GAMMAREFLECTION = false;
  75040. // Default BJS.
  75041. _this.MAINUV1 = false;
  75042. _this.MAINUV2 = false;
  75043. _this.UV1 = false;
  75044. _this.UV2 = false;
  75045. _this.CLIPPLANE = false;
  75046. _this.POINTSIZE = false;
  75047. _this.FOG = false;
  75048. _this.NORMAL = false;
  75049. _this.NUM_BONE_INFLUENCERS = 0;
  75050. _this.BonesPerMesh = 0;
  75051. _this.INSTANCES = false;
  75052. _this.SHADOWFLOAT = false;
  75053. _this.rebuild();
  75054. return _this;
  75055. }
  75056. return BackgroundMaterialDefines;
  75057. }(BABYLON.MaterialDefines));
  75058. /**
  75059. * Background material
  75060. */
  75061. var BackgroundMaterial = /** @class */ (function (_super) {
  75062. __extends(BackgroundMaterial, _super);
  75063. /**
  75064. * constructor
  75065. * @param name The name of the material
  75066. * @param scene The scene to add the material to
  75067. */
  75068. function BackgroundMaterial(name, scene) {
  75069. var _this = _super.call(this, name, scene) || this;
  75070. _this.primaryColor = BABYLON.Color3.White();
  75071. _this.primaryLevel = 1;
  75072. _this.secondaryColor = BABYLON.Color3.Gray();
  75073. _this.secondaryLevel = 1;
  75074. _this.tertiaryColor = BABYLON.Color3.Black();
  75075. _this.tertiaryLevel = 1;
  75076. _this.reflectionTexture = null;
  75077. _this.reflectionBlur = 0;
  75078. _this.diffuseTexture = null;
  75079. /**
  75080. * Specify the list of lights casting shadow on the material.
  75081. * All scene shadow lights will be included if null.
  75082. */
  75083. _this._shadowLights = null;
  75084. _this.shadowLights = null;
  75085. _this.shadowBlurScale = 1;
  75086. _this.shadowLevel = 0;
  75087. _this.opacityFresnel = true;
  75088. _this.useRGBColor = true;
  75089. /**
  75090. * Number of Simultaneous lights allowed on the material.
  75091. */
  75092. _this._maxSimultaneousLights = 4;
  75093. _this.maxSimultaneousLights = 4;
  75094. /**
  75095. * Keep track of the image processing observer to allow dispose and replace.
  75096. */
  75097. _this._imageProcessingObserver = null;
  75098. // Temp values kept as cache in the material.
  75099. _this._renderTargets = new BABYLON.SmartArray(16);
  75100. // Setup the default processing configuration to the scene.
  75101. _this._attachImageProcessingConfiguration(null);
  75102. _this.getRenderTargetTextures = function () {
  75103. _this._renderTargets.reset();
  75104. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75105. _this._renderTargets.push(_this._diffuseTexture);
  75106. }
  75107. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75108. _this._renderTargets.push(_this._reflectionTexture);
  75109. }
  75110. return _this._renderTargets;
  75111. };
  75112. return _this;
  75113. }
  75114. /**
  75115. * Attaches a new image processing configuration to the PBR Material.
  75116. * @param configuration (if null the scene configuration will be use)
  75117. */
  75118. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75119. var _this = this;
  75120. if (configuration === this._imageProcessingConfiguration) {
  75121. return;
  75122. }
  75123. // Detaches observer.
  75124. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75125. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75126. }
  75127. // Pick the scene configuration if needed.
  75128. if (!configuration) {
  75129. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75130. }
  75131. else {
  75132. this._imageProcessingConfiguration = configuration;
  75133. }
  75134. // Attaches observer.
  75135. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75136. _this._markAllSubMeshesAsImageProcessingDirty();
  75137. });
  75138. };
  75139. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75140. /**
  75141. * Gets the image processing configuration used either in this material.
  75142. */
  75143. get: function () {
  75144. return this._imageProcessingConfiguration;
  75145. },
  75146. /**
  75147. * Sets the Default image processing configuration used either in the this material.
  75148. *
  75149. * If sets to null, the scene one is in use.
  75150. */
  75151. set: function (value) {
  75152. this._attachImageProcessingConfiguration(value);
  75153. // Ensure the effect will be rebuilt.
  75154. this._markAllSubMeshesAsTexturesDirty();
  75155. },
  75156. enumerable: true,
  75157. configurable: true
  75158. });
  75159. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75160. /**
  75161. * Gets wether the color curves effect is enabled.
  75162. */
  75163. get: function () {
  75164. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75165. },
  75166. /**
  75167. * Sets wether the color curves effect is enabled.
  75168. */
  75169. set: function (value) {
  75170. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75171. },
  75172. enumerable: true,
  75173. configurable: true
  75174. });
  75175. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75176. /**
  75177. * Gets wether the color grading effect is enabled.
  75178. */
  75179. get: function () {
  75180. return this.imageProcessingConfiguration.colorGradingEnabled;
  75181. },
  75182. /**
  75183. * Gets wether the color grading effect is enabled.
  75184. */
  75185. set: function (value) {
  75186. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75187. },
  75188. enumerable: true,
  75189. configurable: true
  75190. });
  75191. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75192. /**
  75193. * Gets wether tonemapping is enabled or not.
  75194. */
  75195. get: function () {
  75196. return this._imageProcessingConfiguration.toneMappingEnabled;
  75197. },
  75198. /**
  75199. * Sets wether tonemapping is enabled or not
  75200. */
  75201. set: function (value) {
  75202. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75203. },
  75204. enumerable: true,
  75205. configurable: true
  75206. });
  75207. ;
  75208. ;
  75209. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75210. /**
  75211. * The camera exposure used on this material.
  75212. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75213. * This corresponds to a photographic exposure.
  75214. */
  75215. get: function () {
  75216. return this._imageProcessingConfiguration.exposure;
  75217. },
  75218. /**
  75219. * The camera exposure used on this material.
  75220. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75221. * This corresponds to a photographic exposure.
  75222. */
  75223. set: function (value) {
  75224. this._imageProcessingConfiguration.exposure = value;
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. ;
  75230. ;
  75231. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75232. /**
  75233. * Gets The camera contrast used on this material.
  75234. */
  75235. get: function () {
  75236. return this._imageProcessingConfiguration.contrast;
  75237. },
  75238. /**
  75239. * Sets The camera contrast used on this material.
  75240. */
  75241. set: function (value) {
  75242. this._imageProcessingConfiguration.contrast = value;
  75243. },
  75244. enumerable: true,
  75245. configurable: true
  75246. });
  75247. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75248. /**
  75249. * Gets the Color Grading 2D Lookup Texture.
  75250. */
  75251. get: function () {
  75252. return this._imageProcessingConfiguration.colorGradingTexture;
  75253. },
  75254. /**
  75255. * Sets the Color Grading 2D Lookup Texture.
  75256. */
  75257. set: function (value) {
  75258. this.imageProcessingConfiguration.colorGradingTexture = value;
  75259. },
  75260. enumerable: true,
  75261. configurable: true
  75262. });
  75263. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75264. /**
  75265. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75266. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75267. * 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;
  75268. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75269. */
  75270. get: function () {
  75271. return this.imageProcessingConfiguration.colorCurves;
  75272. },
  75273. /**
  75274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75276. * 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;
  75277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75278. */
  75279. set: function (value) {
  75280. this.imageProcessingConfiguration.colorCurves = value;
  75281. },
  75282. enumerable: true,
  75283. configurable: true
  75284. });
  75285. /**
  75286. * The entire material has been created in order to prevent overdraw.
  75287. * @returns false
  75288. */
  75289. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75290. return false;
  75291. };
  75292. /**
  75293. * The entire material has been created in order to prevent overdraw.
  75294. * @returns true if blending is enable
  75295. */
  75296. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75297. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75298. };
  75299. /**
  75300. * Checks wether the material is ready to be rendered for a given mesh.
  75301. * @param mesh The mesh to render
  75302. * @param subMesh The submesh to check against
  75303. * @param useInstances Specify wether or not the material is used with instances
  75304. */
  75305. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75306. var _this = this;
  75307. if (useInstances === void 0) { useInstances = false; }
  75308. if (subMesh.effect && this.isFrozen) {
  75309. if (this._wasPreviouslyReady) {
  75310. return true;
  75311. }
  75312. }
  75313. if (!subMesh._materialDefines) {
  75314. subMesh._materialDefines = new BackgroundMaterialDefines();
  75315. }
  75316. var scene = this.getScene();
  75317. var defines = subMesh._materialDefines;
  75318. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75319. if (defines._renderId === scene.getRenderId()) {
  75320. return true;
  75321. }
  75322. }
  75323. var engine = scene.getEngine();
  75324. // Lights
  75325. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75326. defines._needNormals = true;
  75327. // Textures
  75328. if (defines._areTexturesDirty) {
  75329. defines._needUVs = false;
  75330. if (scene.texturesEnabled) {
  75331. if (scene.getEngine().getCaps().textureLOD) {
  75332. defines.TEXTURELODSUPPORT = true;
  75333. }
  75334. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75335. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75336. return false;
  75337. }
  75338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75339. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75340. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75341. defines.OPACITYFRESNEL = this._opacityFresnel;
  75342. }
  75343. else {
  75344. defines.DIFFUSE = false;
  75345. defines.DIFFUSEHASALPHA = false;
  75346. defines.GAMMADIFFUSE = false;
  75347. defines.OPACITYFRESNEL = false;
  75348. }
  75349. var reflectionTexture = this._reflectionTexture;
  75350. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75351. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75352. return false;
  75353. }
  75354. defines.REFLECTION = true;
  75355. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75356. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75357. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75358. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75359. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75360. defines.INVERTCUBICMAP = true;
  75361. }
  75362. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75363. switch (reflectionTexture.coordinatesMode) {
  75364. case BABYLON.Texture.CUBIC_MODE:
  75365. case BABYLON.Texture.INVCUBIC_MODE:
  75366. defines.REFLECTIONMAP_CUBIC = true;
  75367. break;
  75368. case BABYLON.Texture.EXPLICIT_MODE:
  75369. defines.REFLECTIONMAP_EXPLICIT = true;
  75370. break;
  75371. case BABYLON.Texture.PLANAR_MODE:
  75372. defines.REFLECTIONMAP_PLANAR = true;
  75373. break;
  75374. case BABYLON.Texture.PROJECTION_MODE:
  75375. defines.REFLECTIONMAP_PROJECTION = true;
  75376. break;
  75377. case BABYLON.Texture.SKYBOX_MODE:
  75378. defines.REFLECTIONMAP_SKYBOX = true;
  75379. break;
  75380. case BABYLON.Texture.SPHERICAL_MODE:
  75381. defines.REFLECTIONMAP_SPHERICAL = true;
  75382. break;
  75383. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75384. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75385. break;
  75386. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75387. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75388. break;
  75389. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75390. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75391. break;
  75392. }
  75393. }
  75394. else {
  75395. defines.REFLECTION = false;
  75396. defines.REFLECTIONBLUR = false;
  75397. defines.REFLECTIONMAP_3D = false;
  75398. defines.REFLECTIONMAP_SPHERICAL = false;
  75399. defines.REFLECTIONMAP_PLANAR = false;
  75400. defines.REFLECTIONMAP_CUBIC = false;
  75401. defines.REFLECTIONMAP_PROJECTION = false;
  75402. defines.REFLECTIONMAP_SKYBOX = false;
  75403. defines.REFLECTIONMAP_EXPLICIT = false;
  75404. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75405. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75406. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75407. defines.INVERTCUBICMAP = false;
  75408. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75409. defines.LODINREFLECTIONALPHA = false;
  75410. defines.GAMMAREFLECTION = false;
  75411. }
  75412. }
  75413. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75414. defines.USERGBCOLOR = this._useRGBColor;
  75415. }
  75416. if (defines._areImageProcessingDirty) {
  75417. if (!this._imageProcessingConfiguration.isReady()) {
  75418. return false;
  75419. }
  75420. this._imageProcessingConfiguration.prepareDefines(defines);
  75421. }
  75422. // Misc.
  75423. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75424. // Values that need to be evaluated on every frame
  75425. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75426. // Attribs
  75427. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75428. if (mesh) {
  75429. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75430. mesh.createNormals(true);
  75431. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75432. }
  75433. }
  75434. }
  75435. // Get correct effect
  75436. if (defines.isDirty) {
  75437. defines.markAsProcessed();
  75438. scene.resetCachedMaterial();
  75439. // Fallbacks
  75440. var fallbacks = new BABYLON.EffectFallbacks();
  75441. if (defines.FOG) {
  75442. fallbacks.addFallback(0, "FOG");
  75443. }
  75444. if (defines.POINTSIZE) {
  75445. fallbacks.addFallback(1, "POINTSIZE");
  75446. }
  75447. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75448. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75449. fallbacks.addCPUSkinningFallback(0, mesh);
  75450. }
  75451. //Attributes
  75452. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75453. if (defines.NORMAL) {
  75454. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75455. }
  75456. if (defines.UV1) {
  75457. attribs.push(BABYLON.VertexBuffer.UVKind);
  75458. }
  75459. if (defines.UV2) {
  75460. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75461. }
  75462. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75463. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75464. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75465. "vFogInfos", "vFogColor", "pointSize",
  75466. "vClipPlane", "mBones",
  75467. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75468. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75469. "shadowLevel", "alpha",
  75470. "vDiffuseInfos", "diffuseMatrix",
  75471. ];
  75472. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75473. var uniformBuffers = ["Material", "Scene"];
  75474. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75475. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75476. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75477. uniformsNames: uniforms,
  75478. uniformBuffersNames: uniformBuffers,
  75479. samplers: samplers,
  75480. defines: defines,
  75481. maxSimultaneousLights: this._maxSimultaneousLights
  75482. });
  75483. var onCompiled = function (effect) {
  75484. if (_this.onCompiled) {
  75485. _this.onCompiled(effect);
  75486. }
  75487. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75488. };
  75489. var join = defines.toString();
  75490. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75491. attributes: attribs,
  75492. uniformsNames: uniforms,
  75493. uniformBuffersNames: uniformBuffers,
  75494. samplers: samplers,
  75495. defines: join,
  75496. fallbacks: fallbacks,
  75497. onCompiled: onCompiled,
  75498. onError: this.onError,
  75499. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75500. }, engine), defines);
  75501. this.buildUniformLayout();
  75502. }
  75503. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75504. return false;
  75505. }
  75506. defines._renderId = scene.getRenderId();
  75507. this._wasPreviouslyReady = true;
  75508. return true;
  75509. };
  75510. /**
  75511. * Build the uniform buffer used in the material.
  75512. */
  75513. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75514. // Order is important !
  75515. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75516. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75517. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75518. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75519. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75520. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75521. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75522. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75523. this._uniformBuffer.addUniform("pointSize", 1);
  75524. this._uniformBuffer.addUniform("shadowLevel", 1);
  75525. this._uniformBuffer.addUniform("alpha", 1);
  75526. this._uniformBuffer.create();
  75527. };
  75528. /**
  75529. * Unbind the material.
  75530. */
  75531. BackgroundMaterial.prototype.unbind = function () {
  75532. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75533. this._uniformBuffer.setTexture("diffuseSampler", null);
  75534. }
  75535. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75536. this._uniformBuffer.setTexture("reflectionSampler", null);
  75537. }
  75538. _super.prototype.unbind.call(this);
  75539. };
  75540. /**
  75541. * Bind only the world matrix to the material.
  75542. * @param world The world matrix to bind.
  75543. */
  75544. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75545. this._activeEffect.setMatrix("world", world);
  75546. };
  75547. /**
  75548. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75549. * @param world The world matrix to bind.
  75550. * @param subMesh The submesh to bind for.
  75551. */
  75552. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75553. var scene = this.getScene();
  75554. var defines = subMesh._materialDefines;
  75555. if (!defines) {
  75556. return;
  75557. }
  75558. var effect = subMesh.effect;
  75559. if (!effect) {
  75560. return;
  75561. }
  75562. this._activeEffect = effect;
  75563. // Matrices
  75564. this.bindOnlyWorldMatrix(world);
  75565. // Bones
  75566. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75567. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75568. if (mustRebind) {
  75569. this._uniformBuffer.bindToEffect(effect, "Material");
  75570. this.bindViewProjection(effect);
  75571. var reflectionTexture = this._reflectionTexture;
  75572. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75573. // Texture uniforms
  75574. if (scene.texturesEnabled) {
  75575. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75576. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75577. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75578. }
  75579. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75580. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75581. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75582. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75583. }
  75584. }
  75585. if (this.shadowLevel > 0) {
  75586. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75587. }
  75588. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75589. // Point size
  75590. if (this.pointsCloud) {
  75591. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75592. }
  75593. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75594. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75595. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75596. }
  75597. // Textures
  75598. if (scene.texturesEnabled) {
  75599. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75600. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75601. }
  75602. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75603. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75604. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75605. }
  75606. else if (!defines.REFLECTIONBLUR) {
  75607. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75608. }
  75609. else {
  75610. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75611. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75612. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75613. }
  75614. }
  75615. }
  75616. // Clip plane
  75617. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75618. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75619. }
  75620. if (mustRebind || !this.isFrozen) {
  75621. if (scene.lightsEnabled) {
  75622. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75623. }
  75624. // View
  75625. this.bindView(effect);
  75626. // Fog
  75627. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75628. // image processing
  75629. this._imageProcessingConfiguration.bind(this._activeEffect);
  75630. }
  75631. this._uniformBuffer.update();
  75632. this._afterBind(mesh);
  75633. };
  75634. /**
  75635. * Dispose the material.
  75636. * @forceDisposeEffect Force disposal of the associated effect.
  75637. * @forceDisposeTextures Force disposal of the associated textures.
  75638. */
  75639. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75640. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75641. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75642. if (forceDisposeTextures) {
  75643. if (this.diffuseTexture) {
  75644. this.diffuseTexture.dispose();
  75645. }
  75646. if (this.reflectionTexture) {
  75647. this.reflectionTexture.dispose();
  75648. }
  75649. }
  75650. this._renderTargets.dispose();
  75651. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75652. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75653. }
  75654. _super.prototype.dispose.call(this, forceDisposeEffect);
  75655. };
  75656. /**
  75657. * Clones the material.
  75658. * @name The cloned name.
  75659. * @returns The cloned material.
  75660. */
  75661. BackgroundMaterial.prototype.clone = function (name) {
  75662. var _this = this;
  75663. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75664. };
  75665. /**
  75666. * Serializes the current material to its JSON representation.
  75667. * @returns The JSON representation.
  75668. */
  75669. BackgroundMaterial.prototype.serialize = function () {
  75670. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75671. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75672. return serializationObject;
  75673. };
  75674. /**
  75675. * Gets the class name of the material
  75676. * @returns "BackgroundMaterial"
  75677. */
  75678. BackgroundMaterial.prototype.getClassName = function () {
  75679. return "BackgroundMaterial";
  75680. };
  75681. /**
  75682. * Parse a JSON input to create back a background material.
  75683. * @param source
  75684. * @param scene
  75685. * @param rootUrl
  75686. * @returns the instantiated BackgroundMaterial.
  75687. */
  75688. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75689. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75690. };
  75691. __decorate([
  75692. BABYLON.serializeAsColor3()
  75693. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75694. __decorate([
  75695. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75696. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75697. __decorate([
  75698. BABYLON.serialize()
  75699. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75700. __decorate([
  75701. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75702. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75703. __decorate([
  75704. BABYLON.serializeAsColor3()
  75705. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75706. __decorate([
  75707. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75708. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75709. __decorate([
  75710. BABYLON.serialize()
  75711. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75712. __decorate([
  75713. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75714. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75715. __decorate([
  75716. BABYLON.serializeAsColor3()
  75717. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75718. __decorate([
  75719. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75720. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75721. __decorate([
  75722. BABYLON.serialize()
  75723. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75724. __decorate([
  75725. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75726. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75727. __decorate([
  75728. BABYLON.serializeAsTexture()
  75729. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75730. __decorate([
  75731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75732. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75733. __decorate([
  75734. BABYLON.serialize()
  75735. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75736. __decorate([
  75737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75738. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75739. __decorate([
  75740. BABYLON.serializeAsTexture()
  75741. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75742. __decorate([
  75743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75744. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75745. __decorate([
  75746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75747. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75748. __decorate([
  75749. BABYLON.serialize()
  75750. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75751. __decorate([
  75752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75753. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75754. __decorate([
  75755. BABYLON.serialize()
  75756. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75757. __decorate([
  75758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75759. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75760. __decorate([
  75761. BABYLON.serialize()
  75762. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75763. __decorate([
  75764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75765. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75766. __decorate([
  75767. BABYLON.serialize()
  75768. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75769. __decorate([
  75770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75771. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75772. __decorate([
  75773. BABYLON.serialize()
  75774. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75775. __decorate([
  75776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75777. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75778. __decorate([
  75779. BABYLON.serializeAsImageProcessingConfiguration()
  75780. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75781. return BackgroundMaterial;
  75782. }(BABYLON.PushMaterial));
  75783. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75784. })(BABYLON || (BABYLON = {}));
  75785. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75786. BABYLON.Effect.ShadersStore['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";
  75787. BABYLON.Effect.ShadersStore['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>\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 environmentColor=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;\nenvironmentColor=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){\nenvironmentColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleReflection(reflectionSampler,reflectionCoords).rgb;\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vReflectionInfos.x;\n#endif\n\nvec3 groundColor=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\ngroundColor=diffuseMap.rgb;\n#endif\n\nvec3 colorBase=environmentColor*groundColor;\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#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\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\ngl_FragColor=color;\n}";
  75788. BABYLON.Effect.IncludesShadersStore['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";
  75789. BABYLON.Effect.IncludesShadersStore['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};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  75790. BABYLON.Effect.IncludesShadersStore['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";
  75791. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75792. var BABYLON;
  75793. (function (BABYLON) {
  75794. var GLTFLoaderCoordinateSystemMode;
  75795. (function (GLTFLoaderCoordinateSystemMode) {
  75796. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75797. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  75798. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75799. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75800. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75801. // Sets the useRightHandedSystem flag on the scene.
  75802. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75803. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75804. var GLTFFileLoader = /** @class */ (function () {
  75805. function GLTFFileLoader() {
  75806. // V2 options
  75807. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75808. this.name = "gltf";
  75809. this.extensions = {
  75810. ".gltf": { isBinary: false },
  75811. ".glb": { isBinary: true }
  75812. };
  75813. }
  75814. GLTFFileLoader.prototype.dispose = function () {
  75815. if (this._loader) {
  75816. this._loader.dispose();
  75817. }
  75818. };
  75819. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75820. try {
  75821. var loaderData = GLTFFileLoader._parse(data);
  75822. if (this.onParsed) {
  75823. this.onParsed(loaderData);
  75824. }
  75825. this._loader = this._getLoader(loaderData);
  75826. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75827. }
  75828. catch (e) {
  75829. onError(e.message);
  75830. }
  75831. };
  75832. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75833. try {
  75834. var loaderData = GLTFFileLoader._parse(data);
  75835. if (this.onParsed) {
  75836. this.onParsed(loaderData);
  75837. }
  75838. this._loader = this._getLoader(loaderData);
  75839. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75840. }
  75841. catch (e) {
  75842. onError(e.message);
  75843. }
  75844. };
  75845. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  75846. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  75847. };
  75848. GLTFFileLoader._parse = function (data) {
  75849. if (data instanceof ArrayBuffer) {
  75850. return GLTFFileLoader._parseBinary(data);
  75851. }
  75852. return {
  75853. json: JSON.parse(data),
  75854. bin: null
  75855. };
  75856. };
  75857. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  75858. var loaderVersion = { major: 2, minor: 0 };
  75859. var asset = loaderData.json.asset || {};
  75860. var version = GLTFFileLoader._parseVersion(asset.version);
  75861. if (!version) {
  75862. throw new Error("Invalid version: " + asset.version);
  75863. }
  75864. if (asset.minVersion !== undefined) {
  75865. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  75866. if (!minVersion) {
  75867. throw new Error("Invalid minimum version: " + asset.minVersion);
  75868. }
  75869. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  75870. throw new Error("Incompatible minimum version: " + asset.minVersion);
  75871. }
  75872. }
  75873. var createLoaders = {
  75874. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  75875. 2: GLTFFileLoader.CreateGLTFLoaderV2
  75876. };
  75877. var createLoader = createLoaders[version.major];
  75878. if (!createLoader) {
  75879. throw new Error("Unsupported version: " + asset.version);
  75880. }
  75881. return createLoader(this);
  75882. };
  75883. GLTFFileLoader._parseBinary = function (data) {
  75884. var Binary = {
  75885. Magic: 0x46546C67
  75886. };
  75887. var binaryReader = new BinaryReader(data);
  75888. var magic = binaryReader.readUint32();
  75889. if (magic !== Binary.Magic) {
  75890. throw new Error("Unexpected magic: " + magic);
  75891. }
  75892. var version = binaryReader.readUint32();
  75893. switch (version) {
  75894. case 1: return GLTFFileLoader._parseV1(binaryReader);
  75895. case 2: return GLTFFileLoader._parseV2(binaryReader);
  75896. }
  75897. throw new Error("Unsupported version: " + version);
  75898. };
  75899. GLTFFileLoader._parseV1 = function (binaryReader) {
  75900. var ContentFormat = {
  75901. JSON: 0
  75902. };
  75903. var length = binaryReader.readUint32();
  75904. if (length != binaryReader.getLength()) {
  75905. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75906. }
  75907. var contentLength = binaryReader.readUint32();
  75908. var contentFormat = binaryReader.readUint32();
  75909. var content;
  75910. switch (contentFormat) {
  75911. case ContentFormat.JSON: {
  75912. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  75913. break;
  75914. }
  75915. default: {
  75916. throw new Error("Unexpected content format: " + contentFormat);
  75917. }
  75918. }
  75919. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  75920. var body = binaryReader.readUint8Array(bytesRemaining);
  75921. return {
  75922. json: content,
  75923. bin: body
  75924. };
  75925. };
  75926. GLTFFileLoader._parseV2 = function (binaryReader) {
  75927. var ChunkFormat = {
  75928. JSON: 0x4E4F534A,
  75929. BIN: 0x004E4942
  75930. };
  75931. var length = binaryReader.readUint32();
  75932. if (length !== binaryReader.getLength()) {
  75933. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75934. }
  75935. // JSON chunk
  75936. var chunkLength = binaryReader.readUint32();
  75937. var chunkFormat = binaryReader.readUint32();
  75938. if (chunkFormat !== ChunkFormat.JSON) {
  75939. throw new Error("First chunk format is not JSON");
  75940. }
  75941. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  75942. // Look for BIN chunk
  75943. var bin = null;
  75944. while (binaryReader.getPosition() < binaryReader.getLength()) {
  75945. var chunkLength_1 = binaryReader.readUint32();
  75946. var chunkFormat_1 = binaryReader.readUint32();
  75947. switch (chunkFormat_1) {
  75948. case ChunkFormat.JSON: {
  75949. throw new Error("Unexpected JSON chunk");
  75950. }
  75951. case ChunkFormat.BIN: {
  75952. bin = binaryReader.readUint8Array(chunkLength_1);
  75953. break;
  75954. }
  75955. default: {
  75956. // ignore unrecognized chunkFormat
  75957. binaryReader.skipBytes(chunkLength_1);
  75958. break;
  75959. }
  75960. }
  75961. }
  75962. return {
  75963. json: json,
  75964. bin: bin
  75965. };
  75966. };
  75967. GLTFFileLoader._parseVersion = function (version) {
  75968. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  75969. if (!match) {
  75970. return null;
  75971. }
  75972. return {
  75973. major: parseInt(match[1]),
  75974. minor: parseInt(match[2])
  75975. };
  75976. };
  75977. GLTFFileLoader._compareVersion = function (a, b) {
  75978. if (a.major > b.major)
  75979. return 1;
  75980. if (a.major < b.major)
  75981. return -1;
  75982. if (a.minor > b.minor)
  75983. return 1;
  75984. if (a.minor < b.minor)
  75985. return -1;
  75986. return 0;
  75987. };
  75988. GLTFFileLoader._decodeBufferToText = function (buffer) {
  75989. var result = "";
  75990. var length = buffer.byteLength;
  75991. for (var i = 0; i < length; i++) {
  75992. result += String.fromCharCode(buffer[i]);
  75993. }
  75994. return result;
  75995. };
  75996. // V1 options
  75997. GLTFFileLoader.HomogeneousCoordinates = false;
  75998. GLTFFileLoader.IncrementalLoading = true;
  75999. return GLTFFileLoader;
  76000. }());
  76001. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76002. var BinaryReader = /** @class */ (function () {
  76003. function BinaryReader(arrayBuffer) {
  76004. this._arrayBuffer = arrayBuffer;
  76005. this._dataView = new DataView(arrayBuffer);
  76006. this._byteOffset = 0;
  76007. }
  76008. BinaryReader.prototype.getPosition = function () {
  76009. return this._byteOffset;
  76010. };
  76011. BinaryReader.prototype.getLength = function () {
  76012. return this._arrayBuffer.byteLength;
  76013. };
  76014. BinaryReader.prototype.readUint32 = function () {
  76015. var value = this._dataView.getUint32(this._byteOffset, true);
  76016. this._byteOffset += 4;
  76017. return value;
  76018. };
  76019. BinaryReader.prototype.readUint8Array = function (length) {
  76020. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76021. this._byteOffset += length;
  76022. return value;
  76023. };
  76024. BinaryReader.prototype.skipBytes = function (length) {
  76025. this._byteOffset += length;
  76026. };
  76027. return BinaryReader;
  76028. }());
  76029. if (BABYLON.SceneLoader) {
  76030. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76031. }
  76032. })(BABYLON || (BABYLON = {}));
  76033. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76034. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76035. var BABYLON;
  76036. (function (BABYLON) {
  76037. var GLTF1;
  76038. (function (GLTF1) {
  76039. /**
  76040. * Enums
  76041. */
  76042. var EComponentType;
  76043. (function (EComponentType) {
  76044. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76045. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76046. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76047. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76048. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76049. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76050. var EShaderType;
  76051. (function (EShaderType) {
  76052. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76053. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76054. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76055. var EParameterType;
  76056. (function (EParameterType) {
  76057. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76058. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76059. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76060. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76061. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76062. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76063. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76064. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76065. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76066. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76067. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76068. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76069. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76070. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76071. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76072. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76073. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76074. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76075. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76076. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76077. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76078. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76079. var ETextureWrapMode;
  76080. (function (ETextureWrapMode) {
  76081. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76082. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76083. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76084. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76085. var ETextureFilterType;
  76086. (function (ETextureFilterType) {
  76087. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76088. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76089. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76090. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76091. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76092. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76093. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76094. var ETextureFormat;
  76095. (function (ETextureFormat) {
  76096. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76097. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76098. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76099. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76100. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76101. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76102. var ECullingType;
  76103. (function (ECullingType) {
  76104. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76105. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76106. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76107. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76108. var EBlendingFunction;
  76109. (function (EBlendingFunction) {
  76110. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76111. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76112. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76113. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  76114. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  76115. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  76116. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  76117. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  76118. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  76119. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  76120. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  76121. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  76122. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  76123. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  76124. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  76125. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  76126. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76127. })(BABYLON || (BABYLON = {}));
  76128. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  76129. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76130. var BABYLON;
  76131. (function (BABYLON) {
  76132. var GLTF1;
  76133. (function (GLTF1) {
  76134. /**
  76135. * Tokenizer. Used for shaders compatibility
  76136. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  76137. */
  76138. var ETokenType;
  76139. (function (ETokenType) {
  76140. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  76141. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  76142. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  76143. })(ETokenType || (ETokenType = {}));
  76144. var Tokenizer = /** @class */ (function () {
  76145. function Tokenizer(toParse) {
  76146. this._pos = 0;
  76147. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  76148. this._toParse = toParse;
  76149. this._maxPos = toParse.length;
  76150. }
  76151. Tokenizer.prototype.getNextToken = function () {
  76152. if (this.isEnd())
  76153. return ETokenType.END_OF_INPUT;
  76154. this.currentString = this.read();
  76155. this.currentToken = ETokenType.UNKNOWN;
  76156. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  76157. this.currentToken = ETokenType.IDENTIFIER;
  76158. this.currentIdentifier = this.currentString;
  76159. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  76160. this.currentIdentifier += this.currentString;
  76161. this.forward();
  76162. }
  76163. }
  76164. return this.currentToken;
  76165. };
  76166. Tokenizer.prototype.peek = function () {
  76167. return this._toParse[this._pos];
  76168. };
  76169. Tokenizer.prototype.read = function () {
  76170. return this._toParse[this._pos++];
  76171. };
  76172. Tokenizer.prototype.forward = function () {
  76173. this._pos++;
  76174. };
  76175. Tokenizer.prototype.isEnd = function () {
  76176. return this._pos >= this._maxPos;
  76177. };
  76178. return Tokenizer;
  76179. }());
  76180. /**
  76181. * Values
  76182. */
  76183. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  76184. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  76185. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  76186. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  76187. /**
  76188. * Parse
  76189. */
  76190. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  76191. for (var buf in parsedBuffers) {
  76192. var parsedBuffer = parsedBuffers[buf];
  76193. gltfRuntime.buffers[buf] = parsedBuffer;
  76194. gltfRuntime.buffersCount++;
  76195. }
  76196. };
  76197. var parseShaders = function (parsedShaders, gltfRuntime) {
  76198. for (var sha in parsedShaders) {
  76199. var parsedShader = parsedShaders[sha];
  76200. gltfRuntime.shaders[sha] = parsedShader;
  76201. gltfRuntime.shaderscount++;
  76202. }
  76203. };
  76204. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  76205. for (var object in parsedObjects) {
  76206. var parsedObject = parsedObjects[object];
  76207. gltfRuntime[runtimeProperty][object] = parsedObject;
  76208. }
  76209. };
  76210. /**
  76211. * Utils
  76212. */
  76213. var normalizeUVs = function (buffer) {
  76214. if (!buffer) {
  76215. return;
  76216. }
  76217. for (var i = 0; i < buffer.length / 2; i++) {
  76218. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  76219. }
  76220. };
  76221. var getAttribute = function (attributeParameter) {
  76222. if (attributeParameter.semantic === "NORMAL") {
  76223. return "normal";
  76224. }
  76225. else if (attributeParameter.semantic === "POSITION") {
  76226. return "position";
  76227. }
  76228. else if (attributeParameter.semantic === "JOINT") {
  76229. return "matricesIndices";
  76230. }
  76231. else if (attributeParameter.semantic === "WEIGHT") {
  76232. return "matricesWeights";
  76233. }
  76234. else if (attributeParameter.semantic === "COLOR") {
  76235. return "color";
  76236. }
  76237. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  76238. var channel = Number(attributeParameter.semantic.split("_")[1]);
  76239. return "uv" + (channel === 0 ? "" : channel + 1);
  76240. }
  76241. return null;
  76242. };
  76243. /**
  76244. * Loads and creates animations
  76245. */
  76246. var loadAnimations = function (gltfRuntime) {
  76247. for (var anim in gltfRuntime.animations) {
  76248. var animation = gltfRuntime.animations[anim];
  76249. if (!animation.channels || !animation.samplers) {
  76250. continue;
  76251. }
  76252. var lastAnimation = null;
  76253. for (var i = 0; i < animation.channels.length; i++) {
  76254. // Get parameters and load buffers
  76255. var channel = animation.channels[i];
  76256. var sampler = animation.samplers[channel.sampler];
  76257. if (!sampler) {
  76258. continue;
  76259. }
  76260. var inputData = null;
  76261. var outputData = null;
  76262. if (animation.parameters) {
  76263. inputData = animation.parameters[sampler.input];
  76264. outputData = animation.parameters[sampler.output];
  76265. }
  76266. else {
  76267. inputData = sampler.input;
  76268. outputData = sampler.output;
  76269. }
  76270. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  76271. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  76272. var targetID = channel.target.id;
  76273. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  76274. if (targetNode === null) {
  76275. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  76276. }
  76277. if (targetNode === null) {
  76278. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  76279. continue;
  76280. }
  76281. var isBone = targetNode instanceof BABYLON.Bone;
  76282. // Get target path (position, rotation or scaling)
  76283. var targetPath = channel.target.path;
  76284. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  76285. if (targetPathIndex !== -1) {
  76286. targetPath = babylonAnimationPaths[targetPathIndex];
  76287. }
  76288. // Determine animation type
  76289. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  76290. if (!isBone) {
  76291. if (targetPath === "rotationQuaternion") {
  76292. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  76293. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  76294. }
  76295. else {
  76296. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  76297. }
  76298. }
  76299. // Create animation and key frames
  76300. var babylonAnimation = null;
  76301. var keys = [];
  76302. var arrayOffset = 0;
  76303. var modifyKey = false;
  76304. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  76305. babylonAnimation = lastAnimation;
  76306. modifyKey = true;
  76307. }
  76308. if (!modifyKey) {
  76309. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76310. }
  76311. // For each frame
  76312. for (var j = 0; j < bufferInput.length; j++) {
  76313. var value = null;
  76314. if (targetPath === "rotationQuaternion") {
  76315. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  76316. arrayOffset += 4;
  76317. }
  76318. else {
  76319. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  76320. arrayOffset += 3;
  76321. }
  76322. if (isBone) {
  76323. var bone = targetNode;
  76324. var translation = BABYLON.Vector3.Zero();
  76325. var rotationQuaternion = new BABYLON.Quaternion();
  76326. var scaling = BABYLON.Vector3.Zero();
  76327. // Warning on decompose
  76328. var mat = bone.getBaseMatrix();
  76329. if (modifyKey && lastAnimation) {
  76330. mat = lastAnimation.getKeys()[j].value;
  76331. }
  76332. mat.decompose(scaling, rotationQuaternion, translation);
  76333. if (targetPath === "position") {
  76334. translation = value;
  76335. }
  76336. else if (targetPath === "rotationQuaternion") {
  76337. rotationQuaternion = value;
  76338. }
  76339. else {
  76340. scaling = value;
  76341. }
  76342. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76343. }
  76344. if (!modifyKey) {
  76345. keys.push({
  76346. frame: bufferInput[j],
  76347. value: value
  76348. });
  76349. }
  76350. else if (lastAnimation) {
  76351. lastAnimation.getKeys()[j].value = value;
  76352. }
  76353. }
  76354. // Finish
  76355. if (!modifyKey && babylonAnimation) {
  76356. babylonAnimation.setKeys(keys);
  76357. targetNode.animations.push(babylonAnimation);
  76358. }
  76359. lastAnimation = babylonAnimation;
  76360. gltfRuntime.scene.stopAnimation(targetNode);
  76361. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76362. }
  76363. }
  76364. };
  76365. /**
  76366. * Returns the bones transformation matrix
  76367. */
  76368. var configureBoneTransformation = function (node) {
  76369. var mat = null;
  76370. if (node.translation || node.rotation || node.scale) {
  76371. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76372. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76373. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76374. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76375. }
  76376. else {
  76377. mat = BABYLON.Matrix.FromArray(node.matrix);
  76378. }
  76379. return mat;
  76380. };
  76381. /**
  76382. * Returns the parent bone
  76383. */
  76384. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76385. // Try to find
  76386. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76387. if (newSkeleton.bones[i].name === jointName) {
  76388. return newSkeleton.bones[i];
  76389. }
  76390. }
  76391. // Not found, search in gltf nodes
  76392. var nodes = gltfRuntime.nodes;
  76393. for (var nde in nodes) {
  76394. var node = nodes[nde];
  76395. if (!node.jointName) {
  76396. continue;
  76397. }
  76398. var children = node.children;
  76399. for (var i = 0; i < children.length; i++) {
  76400. var child = gltfRuntime.nodes[children[i]];
  76401. if (!child.jointName) {
  76402. continue;
  76403. }
  76404. if (child.jointName === jointName) {
  76405. var mat = configureBoneTransformation(node);
  76406. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76407. bone.id = nde;
  76408. return bone;
  76409. }
  76410. }
  76411. }
  76412. return null;
  76413. };
  76414. /**
  76415. * Returns the appropriate root node
  76416. */
  76417. var getNodeToRoot = function (nodesToRoot, id) {
  76418. for (var i = 0; i < nodesToRoot.length; i++) {
  76419. var nodeToRoot = nodesToRoot[i];
  76420. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76421. var child = nodeToRoot.node.children[j];
  76422. if (child === id) {
  76423. return nodeToRoot.bone;
  76424. }
  76425. }
  76426. }
  76427. return null;
  76428. };
  76429. /**
  76430. * Returns the node with the joint name
  76431. */
  76432. var getJointNode = function (gltfRuntime, jointName) {
  76433. var nodes = gltfRuntime.nodes;
  76434. var node = nodes[jointName];
  76435. if (node) {
  76436. return {
  76437. node: node,
  76438. id: jointName
  76439. };
  76440. }
  76441. for (var nde in nodes) {
  76442. node = nodes[nde];
  76443. if (node.jointName === jointName) {
  76444. return {
  76445. node: node,
  76446. id: nde
  76447. };
  76448. }
  76449. }
  76450. return null;
  76451. };
  76452. /**
  76453. * Checks if a nodes is in joints
  76454. */
  76455. var nodeIsInJoints = function (skins, id) {
  76456. for (var i = 0; i < skins.jointNames.length; i++) {
  76457. if (skins.jointNames[i] === id) {
  76458. return true;
  76459. }
  76460. }
  76461. return false;
  76462. };
  76463. /**
  76464. * Fills the nodes to root for bones and builds hierarchy
  76465. */
  76466. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76467. // Creates nodes for root
  76468. for (var nde in gltfRuntime.nodes) {
  76469. var node = gltfRuntime.nodes[nde];
  76470. var id = nde;
  76471. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76472. continue;
  76473. }
  76474. // Create node to root bone
  76475. var mat = configureBoneTransformation(node);
  76476. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76477. bone.id = id;
  76478. nodesToRoot.push({ bone: bone, node: node, id: id });
  76479. }
  76480. // Parenting
  76481. for (var i = 0; i < nodesToRoot.length; i++) {
  76482. var nodeToRoot = nodesToRoot[i];
  76483. var children = nodeToRoot.node.children;
  76484. for (var j = 0; j < children.length; j++) {
  76485. var child = null;
  76486. for (var k = 0; k < nodesToRoot.length; k++) {
  76487. if (nodesToRoot[k].id === children[j]) {
  76488. child = nodesToRoot[k];
  76489. break;
  76490. }
  76491. }
  76492. if (child) {
  76493. child.bone._parent = nodeToRoot.bone;
  76494. nodeToRoot.bone.children.push(child.bone);
  76495. }
  76496. }
  76497. }
  76498. };
  76499. /**
  76500. * Imports a skeleton
  76501. */
  76502. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76503. if (!newSkeleton) {
  76504. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76505. }
  76506. if (!skins.babylonSkeleton) {
  76507. return newSkeleton;
  76508. }
  76509. // Find the root bones
  76510. var nodesToRoot = [];
  76511. var nodesToRootToAdd = [];
  76512. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76513. newSkeleton.bones = [];
  76514. // Joints
  76515. for (var i = 0; i < skins.jointNames.length; i++) {
  76516. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76517. if (!jointNode) {
  76518. continue;
  76519. }
  76520. var node = jointNode.node;
  76521. if (!node) {
  76522. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76523. continue;
  76524. }
  76525. var id = jointNode.id;
  76526. // Optimize, if the bone already exists...
  76527. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76528. if (existingBone) {
  76529. newSkeleton.bones.push(existingBone);
  76530. continue;
  76531. }
  76532. // Search for parent bone
  76533. var foundBone = false;
  76534. var parentBone = null;
  76535. for (var j = 0; j < i; j++) {
  76536. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76537. if (!jointNode_1) {
  76538. continue;
  76539. }
  76540. var joint = jointNode_1.node;
  76541. if (!joint) {
  76542. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76543. continue;
  76544. }
  76545. var children = joint.children;
  76546. if (!children) {
  76547. continue;
  76548. }
  76549. foundBone = false;
  76550. for (var k = 0; k < children.length; k++) {
  76551. if (children[k] === id) {
  76552. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76553. foundBone = true;
  76554. break;
  76555. }
  76556. }
  76557. if (foundBone) {
  76558. break;
  76559. }
  76560. }
  76561. // Create bone
  76562. var mat = configureBoneTransformation(node);
  76563. if (!parentBone && nodesToRoot.length > 0) {
  76564. parentBone = getNodeToRoot(nodesToRoot, id);
  76565. if (parentBone) {
  76566. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76567. nodesToRootToAdd.push(parentBone);
  76568. }
  76569. }
  76570. }
  76571. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76572. bone.id = id;
  76573. }
  76574. // Polish
  76575. var bones = newSkeleton.bones;
  76576. newSkeleton.bones = [];
  76577. for (var i = 0; i < skins.jointNames.length; i++) {
  76578. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76579. if (!jointNode) {
  76580. continue;
  76581. }
  76582. for (var j = 0; j < bones.length; j++) {
  76583. if (bones[j].id === jointNode.id) {
  76584. newSkeleton.bones.push(bones[j]);
  76585. break;
  76586. }
  76587. }
  76588. }
  76589. newSkeleton.prepare();
  76590. // Finish
  76591. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76592. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76593. }
  76594. return newSkeleton;
  76595. };
  76596. /**
  76597. * Imports a mesh and its geometries
  76598. */
  76599. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76600. if (!newMesh) {
  76601. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76602. newMesh.id = id;
  76603. }
  76604. if (!node.babylonNode) {
  76605. return newMesh;
  76606. }
  76607. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76608. if (!newMesh.material) {
  76609. newMesh.material = multiMat;
  76610. }
  76611. var vertexData = new BABYLON.VertexData();
  76612. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76613. var verticesStarts = new Array();
  76614. var verticesCounts = new Array();
  76615. var indexStarts = new Array();
  76616. var indexCounts = new Array();
  76617. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76618. var meshID = meshes[meshIndex];
  76619. var mesh = gltfRuntime.meshes[meshID];
  76620. if (!mesh) {
  76621. continue;
  76622. }
  76623. // Positions, normals and UVs
  76624. for (var i = 0; i < mesh.primitives.length; i++) {
  76625. // Temporary vertex data
  76626. var tempVertexData = new BABYLON.VertexData();
  76627. var primitive = mesh.primitives[i];
  76628. if (primitive.mode !== 4) {
  76629. // continue;
  76630. }
  76631. var attributes = primitive.attributes;
  76632. var accessor = null;
  76633. var buffer = null;
  76634. // Set positions, normal and uvs
  76635. for (var semantic in attributes) {
  76636. // Link accessor and buffer view
  76637. accessor = gltfRuntime.accessors[attributes[semantic]];
  76638. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76639. if (semantic === "NORMAL") {
  76640. tempVertexData.normals = new Float32Array(buffer.length);
  76641. tempVertexData.normals.set(buffer);
  76642. }
  76643. else if (semantic === "POSITION") {
  76644. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76645. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76646. for (var j = 0; j < buffer.length; j += 4) {
  76647. tempVertexData.positions[j] = buffer[j];
  76648. tempVertexData.positions[j + 1] = buffer[j + 1];
  76649. tempVertexData.positions[j + 2] = buffer[j + 2];
  76650. }
  76651. }
  76652. else {
  76653. tempVertexData.positions = new Float32Array(buffer.length);
  76654. tempVertexData.positions.set(buffer);
  76655. }
  76656. verticesCounts.push(tempVertexData.positions.length);
  76657. }
  76658. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76659. var channel = Number(semantic.split("_")[1]);
  76660. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76661. var uvs = new Float32Array(buffer.length);
  76662. uvs.set(buffer);
  76663. normalizeUVs(uvs);
  76664. tempVertexData.set(uvs, uvKind);
  76665. }
  76666. else if (semantic === "JOINT") {
  76667. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76668. tempVertexData.matricesIndices.set(buffer);
  76669. }
  76670. else if (semantic === "WEIGHT") {
  76671. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76672. tempVertexData.matricesWeights.set(buffer);
  76673. }
  76674. else if (semantic === "COLOR") {
  76675. tempVertexData.colors = new Float32Array(buffer.length);
  76676. tempVertexData.colors.set(buffer);
  76677. }
  76678. }
  76679. // Indices
  76680. accessor = gltfRuntime.accessors[primitive.indices];
  76681. if (accessor) {
  76682. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76683. tempVertexData.indices = new Int32Array(buffer.length);
  76684. tempVertexData.indices.set(buffer);
  76685. indexCounts.push(tempVertexData.indices.length);
  76686. }
  76687. else {
  76688. // Set indices on the fly
  76689. var indices = [];
  76690. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76691. indices.push(j);
  76692. }
  76693. tempVertexData.indices = new Int32Array(indices);
  76694. indexCounts.push(tempVertexData.indices.length);
  76695. }
  76696. vertexData.merge(tempVertexData);
  76697. // Sub material
  76698. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76699. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76700. // Update vertices start and index start
  76701. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76702. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76703. }
  76704. }
  76705. // Apply geometry
  76706. geometry.setAllVerticesData(vertexData, false);
  76707. newMesh.computeWorldMatrix(true);
  76708. // Apply submeshes
  76709. newMesh.subMeshes = [];
  76710. var index = 0;
  76711. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76712. var meshID = meshes[meshIndex];
  76713. var mesh = gltfRuntime.meshes[meshID];
  76714. if (!mesh) {
  76715. continue;
  76716. }
  76717. for (var i = 0; i < mesh.primitives.length; i++) {
  76718. if (mesh.primitives[i].mode !== 4) {
  76719. //continue;
  76720. }
  76721. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76722. index++;
  76723. }
  76724. }
  76725. // Finish
  76726. return newMesh;
  76727. };
  76728. /**
  76729. * Configure node transformation from position, rotation and scaling
  76730. */
  76731. var configureNode = function (newNode, position, rotation, scaling) {
  76732. if (newNode.position) {
  76733. newNode.position = position;
  76734. }
  76735. if (newNode.rotationQuaternion || newNode.rotation) {
  76736. newNode.rotationQuaternion = rotation;
  76737. }
  76738. if (newNode.scaling) {
  76739. newNode.scaling = scaling;
  76740. }
  76741. };
  76742. /**
  76743. * Configures node from transformation matrix
  76744. */
  76745. var configureNodeFromMatrix = function (newNode, node, parent) {
  76746. if (node.matrix) {
  76747. var position = new BABYLON.Vector3(0, 0, 0);
  76748. var rotation = new BABYLON.Quaternion();
  76749. var scaling = new BABYLON.Vector3(0, 0, 0);
  76750. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76751. mat.decompose(scaling, rotation, position);
  76752. configureNode(newNode, position, rotation, scaling);
  76753. }
  76754. else if (node.translation && node.rotation && node.scale) {
  76755. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76756. }
  76757. newNode.computeWorldMatrix(true);
  76758. };
  76759. /**
  76760. * Imports a node
  76761. */
  76762. var importNode = function (gltfRuntime, node, id, parent) {
  76763. var lastNode = null;
  76764. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76765. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76766. return null;
  76767. }
  76768. }
  76769. // Meshes
  76770. if (node.skin) {
  76771. if (node.meshes) {
  76772. var skin = gltfRuntime.skins[node.skin];
  76773. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76774. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76775. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76776. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76777. if (!skin.babylonSkeleton) {
  76778. skin.babylonSkeleton = newMesh.skeleton;
  76779. }
  76780. }
  76781. lastNode = newMesh;
  76782. }
  76783. }
  76784. else if (node.meshes) {
  76785. /**
  76786. * Improve meshes property
  76787. */
  76788. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76789. lastNode = newMesh;
  76790. }
  76791. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76792. var light = gltfRuntime.lights[node.light];
  76793. if (light) {
  76794. if (light.type === "ambient") {
  76795. var ambienLight = light[light.type];
  76796. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76797. hemiLight.name = node.name || "";
  76798. if (ambienLight.color) {
  76799. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76800. }
  76801. lastNode = hemiLight;
  76802. }
  76803. else if (light.type === "directional") {
  76804. var directionalLight = light[light.type];
  76805. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76806. dirLight.name = node.name || "";
  76807. if (directionalLight.color) {
  76808. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76809. }
  76810. lastNode = dirLight;
  76811. }
  76812. else if (light.type === "point") {
  76813. var pointLight = light[light.type];
  76814. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76815. ptLight.name = node.name || "";
  76816. if (pointLight.color) {
  76817. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76818. }
  76819. lastNode = ptLight;
  76820. }
  76821. else if (light.type === "spot") {
  76822. var spotLight = light[light.type];
  76823. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76824. spLight.name = node.name || "";
  76825. if (spotLight.color) {
  76826. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76827. }
  76828. if (spotLight.fallOfAngle) {
  76829. spLight.angle = spotLight.fallOfAngle;
  76830. }
  76831. if (spotLight.fallOffExponent) {
  76832. spLight.exponent = spotLight.fallOffExponent;
  76833. }
  76834. lastNode = spLight;
  76835. }
  76836. }
  76837. }
  76838. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76839. var camera = gltfRuntime.cameras[node.camera];
  76840. if (camera) {
  76841. if (camera.type === "orthographic") {
  76842. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76843. orthoCamera.name = node.name || "";
  76844. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  76845. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76846. lastNode = orthoCamera;
  76847. }
  76848. else if (camera.type === "perspective") {
  76849. var perspectiveCamera = camera[camera.type];
  76850. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76851. persCamera.name = node.name || "";
  76852. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76853. if (!perspectiveCamera.aspectRatio) {
  76854. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  76855. }
  76856. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  76857. persCamera.maxZ = perspectiveCamera.zfar;
  76858. persCamera.minZ = perspectiveCamera.znear;
  76859. }
  76860. lastNode = persCamera;
  76861. }
  76862. }
  76863. }
  76864. // Empty node
  76865. if (!node.jointName) {
  76866. if (node.babylonNode) {
  76867. return node.babylonNode;
  76868. }
  76869. else if (lastNode === null) {
  76870. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76871. node.babylonNode = dummy;
  76872. lastNode = dummy;
  76873. }
  76874. }
  76875. if (lastNode !== null) {
  76876. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  76877. configureNodeFromMatrix(lastNode, node, parent);
  76878. }
  76879. else {
  76880. var translation = node.translation || [0, 0, 0];
  76881. var rotation = node.rotation || [0, 0, 0, 1];
  76882. var scale = node.scale || [1, 1, 1];
  76883. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  76884. }
  76885. lastNode.updateCache(true);
  76886. node.babylonNode = lastNode;
  76887. }
  76888. return lastNode;
  76889. };
  76890. /**
  76891. * Traverses nodes and creates them
  76892. */
  76893. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  76894. if (meshIncluded === void 0) { meshIncluded = false; }
  76895. var node = gltfRuntime.nodes[id];
  76896. var newNode = null;
  76897. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  76898. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  76899. meshIncluded = true;
  76900. }
  76901. else {
  76902. meshIncluded = false;
  76903. }
  76904. }
  76905. else {
  76906. meshIncluded = true;
  76907. }
  76908. if (!node.jointName && meshIncluded) {
  76909. newNode = importNode(gltfRuntime, node, id, parent);
  76910. if (newNode !== null) {
  76911. newNode.id = id;
  76912. newNode.parent = parent;
  76913. }
  76914. }
  76915. if (node.children) {
  76916. for (var i = 0; i < node.children.length; i++) {
  76917. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  76918. }
  76919. }
  76920. };
  76921. /**
  76922. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  76923. */
  76924. var postLoad = function (gltfRuntime) {
  76925. // Nodes
  76926. var currentScene = gltfRuntime.currentScene;
  76927. if (currentScene) {
  76928. for (var i = 0; i < currentScene.nodes.length; i++) {
  76929. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76930. }
  76931. }
  76932. else {
  76933. for (var thing in gltfRuntime.scenes) {
  76934. currentScene = gltfRuntime.scenes[thing];
  76935. for (var i = 0; i < currentScene.nodes.length; i++) {
  76936. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76937. }
  76938. }
  76939. }
  76940. // Set animations
  76941. loadAnimations(gltfRuntime);
  76942. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  76943. var skeleton = gltfRuntime.scene.skeletons[i];
  76944. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  76945. }
  76946. };
  76947. /**
  76948. * onBind shaderrs callback to set uniforms and matrices
  76949. */
  76950. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  76951. var materialValues = material.values || technique.parameters;
  76952. for (var unif in unTreatedUniforms) {
  76953. var uniform = unTreatedUniforms[unif];
  76954. var type = uniform.type;
  76955. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  76956. if (uniform.semantic && !uniform.source && !uniform.node) {
  76957. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  76958. }
  76959. else if (uniform.semantic && (uniform.source || uniform.node)) {
  76960. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  76961. if (source === null) {
  76962. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  76963. }
  76964. if (source === null) {
  76965. continue;
  76966. }
  76967. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  76968. }
  76969. }
  76970. else {
  76971. var value = materialValues[technique.uniforms[unif]];
  76972. if (!value) {
  76973. continue;
  76974. }
  76975. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76976. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  76977. if (texture === null || texture === undefined) {
  76978. continue;
  76979. }
  76980. shaderMaterial.getEffect().setTexture(unif, texture);
  76981. }
  76982. else {
  76983. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  76984. }
  76985. }
  76986. }
  76987. onSuccess(shaderMaterial);
  76988. };
  76989. /**
  76990. * Prepare uniforms to send the only one time
  76991. * Loads the appropriate textures
  76992. */
  76993. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  76994. var materialValues = material.values || technique.parameters;
  76995. var techniqueUniforms = technique.uniforms;
  76996. /**
  76997. * Prepare values here (not matrices)
  76998. */
  76999. for (var unif in unTreatedUniforms) {
  77000. var uniform = unTreatedUniforms[unif];
  77001. var type = uniform.type;
  77002. var value = materialValues[techniqueUniforms[unif]];
  77003. if (value === undefined) {
  77004. // In case the value is the same for all materials
  77005. value = uniform.value;
  77006. }
  77007. if (!value) {
  77008. continue;
  77009. }
  77010. var onLoadTexture = function (uniformName) {
  77011. return function (texture) {
  77012. if (uniform.value && uniformName) {
  77013. // Static uniform
  77014. shaderMaterial.setTexture(uniformName, texture);
  77015. delete unTreatedUniforms[uniformName];
  77016. }
  77017. };
  77018. };
  77019. // Texture (sampler2D)
  77020. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77021. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77022. }
  77023. else {
  77024. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77025. // Static uniform
  77026. delete unTreatedUniforms[unif];
  77027. }
  77028. }
  77029. }
  77030. };
  77031. /**
  77032. * Shader compilation failed
  77033. */
  77034. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77035. return function (effect, error) {
  77036. shaderMaterial.dispose(true);
  77037. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77038. };
  77039. };
  77040. /**
  77041. * Shader compilation success
  77042. */
  77043. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77044. return function (_) {
  77045. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77046. shaderMaterial.onBind = function (mesh) {
  77047. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77048. };
  77049. };
  77050. };
  77051. /**
  77052. * Returns the appropriate uniform if already handled by babylon
  77053. */
  77054. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77055. for (var unif in technique.uniforms) {
  77056. var uniform = technique.uniforms[unif];
  77057. var uniformParameter = technique.parameters[uniform];
  77058. if (tokenizer.currentIdentifier === unif) {
  77059. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77060. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77061. if (transformIndex !== -1) {
  77062. delete unTreatedUniforms[unif];
  77063. return babylonTransforms[transformIndex];
  77064. }
  77065. }
  77066. }
  77067. }
  77068. return tokenizer.currentIdentifier;
  77069. };
  77070. /**
  77071. * All shaders loaded. Create materials one by one
  77072. */
  77073. var importMaterials = function (gltfRuntime) {
  77074. // Create materials
  77075. for (var mat in gltfRuntime.materials) {
  77076. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77077. }
  77078. };
  77079. /**
  77080. * Implementation of the base glTF spec
  77081. */
  77082. var GLTFLoaderBase = /** @class */ (function () {
  77083. function GLTFLoaderBase() {
  77084. }
  77085. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77086. var gltfRuntime = {
  77087. extensions: {},
  77088. accessors: {},
  77089. buffers: {},
  77090. bufferViews: {},
  77091. meshes: {},
  77092. lights: {},
  77093. cameras: {},
  77094. nodes: {},
  77095. images: {},
  77096. textures: {},
  77097. shaders: {},
  77098. programs: {},
  77099. samplers: {},
  77100. techniques: {},
  77101. materials: {},
  77102. animations: {},
  77103. skins: {},
  77104. extensionsUsed: [],
  77105. scenes: {},
  77106. buffersCount: 0,
  77107. shaderscount: 0,
  77108. scene: scene,
  77109. rootUrl: rootUrl,
  77110. loadedBufferCount: 0,
  77111. loadedBufferViews: {},
  77112. loadedShaderCount: 0,
  77113. importOnlyMeshes: false,
  77114. dummyNodes: []
  77115. };
  77116. // Parse
  77117. if (parsedData.extensions) {
  77118. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  77119. }
  77120. if (parsedData.extensionsUsed) {
  77121. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  77122. }
  77123. if (parsedData.buffers) {
  77124. parseBuffers(parsedData.buffers, gltfRuntime);
  77125. }
  77126. if (parsedData.bufferViews) {
  77127. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  77128. }
  77129. if (parsedData.accessors) {
  77130. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  77131. }
  77132. if (parsedData.meshes) {
  77133. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  77134. }
  77135. if (parsedData.lights) {
  77136. parseObject(parsedData.lights, "lights", gltfRuntime);
  77137. }
  77138. if (parsedData.cameras) {
  77139. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  77140. }
  77141. if (parsedData.nodes) {
  77142. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  77143. }
  77144. if (parsedData.images) {
  77145. parseObject(parsedData.images, "images", gltfRuntime);
  77146. }
  77147. if (parsedData.textures) {
  77148. parseObject(parsedData.textures, "textures", gltfRuntime);
  77149. }
  77150. if (parsedData.shaders) {
  77151. parseShaders(parsedData.shaders, gltfRuntime);
  77152. }
  77153. if (parsedData.programs) {
  77154. parseObject(parsedData.programs, "programs", gltfRuntime);
  77155. }
  77156. if (parsedData.samplers) {
  77157. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  77158. }
  77159. if (parsedData.techniques) {
  77160. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  77161. }
  77162. if (parsedData.materials) {
  77163. parseObject(parsedData.materials, "materials", gltfRuntime);
  77164. }
  77165. if (parsedData.animations) {
  77166. parseObject(parsedData.animations, "animations", gltfRuntime);
  77167. }
  77168. if (parsedData.skins) {
  77169. parseObject(parsedData.skins, "skins", gltfRuntime);
  77170. }
  77171. if (parsedData.scenes) {
  77172. gltfRuntime.scenes = parsedData.scenes;
  77173. }
  77174. if (parsedData.scene && parsedData.scenes) {
  77175. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  77176. }
  77177. return gltfRuntime;
  77178. };
  77179. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77180. var buffer = gltfRuntime.buffers[id];
  77181. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  77182. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  77183. }
  77184. else {
  77185. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  77186. if (request) {
  77187. onError(request.status + " " + request.statusText);
  77188. }
  77189. });
  77190. }
  77191. };
  77192. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77193. var texture = gltfRuntime.textures[id];
  77194. if (!texture || !texture.source) {
  77195. onError("");
  77196. return;
  77197. }
  77198. if (texture.babylonTexture) {
  77199. onSuccess(null);
  77200. return;
  77201. }
  77202. var source = gltfRuntime.images[texture.source];
  77203. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  77204. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  77205. }
  77206. else {
  77207. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  77208. if (request) {
  77209. onError(request.status + " " + request.statusText);
  77210. }
  77211. });
  77212. }
  77213. };
  77214. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77215. var texture = gltfRuntime.textures[id];
  77216. if (texture.babylonTexture) {
  77217. onSuccess(texture.babylonTexture);
  77218. return;
  77219. }
  77220. var sampler = gltfRuntime.samplers[texture.sampler];
  77221. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  77222. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  77223. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  77224. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  77225. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77226. var blob = new Blob([buffer]);
  77227. var blobURL = URL.createObjectURL(blob);
  77228. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  77229. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  77230. if (sampler.wrapS !== undefined) {
  77231. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  77232. }
  77233. if (sampler.wrapT !== undefined) {
  77234. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  77235. }
  77236. newTexture.name = id;
  77237. texture.babylonTexture = newTexture;
  77238. onSuccess(newTexture);
  77239. };
  77240. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77241. var shader = gltfRuntime.shaders[id];
  77242. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  77243. var shaderString = atob(shader.uri.split(",")[1]);
  77244. onSuccess(shaderString);
  77245. }
  77246. else {
  77247. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  77248. if (request) {
  77249. onError(request.status + " " + request.statusText);
  77250. }
  77251. });
  77252. }
  77253. };
  77254. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77255. var material = gltfRuntime.materials[id];
  77256. if (!material.technique) {
  77257. if (onError) {
  77258. onError("No technique found.");
  77259. }
  77260. return;
  77261. }
  77262. var technique = gltfRuntime.techniques[material.technique];
  77263. if (!technique) {
  77264. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77265. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  77266. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77267. onSuccess(defaultMaterial);
  77268. return;
  77269. }
  77270. var program = gltfRuntime.programs[technique.program];
  77271. var states = technique.states;
  77272. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  77273. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  77274. var newVertexShader = "";
  77275. var newPixelShader = "";
  77276. var vertexTokenizer = new Tokenizer(vertexShader);
  77277. var pixelTokenizer = new Tokenizer(pixelShader);
  77278. var unTreatedUniforms = {};
  77279. var uniforms = [];
  77280. var attributes = [];
  77281. var samplers = [];
  77282. // Fill uniform, sampler2D and attributes
  77283. for (var unif in technique.uniforms) {
  77284. var uniform = technique.uniforms[unif];
  77285. var uniformParameter = technique.parameters[uniform];
  77286. unTreatedUniforms[unif] = uniformParameter;
  77287. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  77288. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77289. if (transformIndex !== -1) {
  77290. uniforms.push(babylonTransforms[transformIndex]);
  77291. delete unTreatedUniforms[unif];
  77292. }
  77293. else {
  77294. uniforms.push(unif);
  77295. }
  77296. }
  77297. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  77298. samplers.push(unif);
  77299. }
  77300. else {
  77301. uniforms.push(unif);
  77302. }
  77303. }
  77304. for (var attr in technique.attributes) {
  77305. var attribute = technique.attributes[attr];
  77306. var attributeParameter = technique.parameters[attribute];
  77307. if (attributeParameter.semantic) {
  77308. attributes.push(getAttribute(attributeParameter));
  77309. }
  77310. }
  77311. // Configure vertex shader
  77312. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  77313. var tokenType = vertexTokenizer.currentToken;
  77314. if (tokenType !== ETokenType.IDENTIFIER) {
  77315. newVertexShader += vertexTokenizer.currentString;
  77316. continue;
  77317. }
  77318. var foundAttribute = false;
  77319. for (var attr in technique.attributes) {
  77320. var attribute = technique.attributes[attr];
  77321. var attributeParameter = technique.parameters[attribute];
  77322. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  77323. newVertexShader += getAttribute(attributeParameter);
  77324. foundAttribute = true;
  77325. break;
  77326. }
  77327. }
  77328. if (foundAttribute) {
  77329. continue;
  77330. }
  77331. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  77332. }
  77333. // Configure pixel shader
  77334. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  77335. var tokenType = pixelTokenizer.currentToken;
  77336. if (tokenType !== ETokenType.IDENTIFIER) {
  77337. newPixelShader += pixelTokenizer.currentString;
  77338. continue;
  77339. }
  77340. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77341. }
  77342. // Create shader material
  77343. var shaderPath = {
  77344. vertex: program.vertexShader + id,
  77345. fragment: program.fragmentShader + id
  77346. };
  77347. var options = {
  77348. attributes: attributes,
  77349. uniforms: uniforms,
  77350. samplers: samplers,
  77351. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77352. };
  77353. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77354. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77355. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77356. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77357. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77358. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77359. if (states && states.functions) {
  77360. var functions = states.functions;
  77361. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77362. shaderMaterial.backFaceCulling = false;
  77363. }
  77364. var blendFunc = functions.blendFuncSeparate;
  77365. if (blendFunc) {
  77366. 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) {
  77367. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77368. }
  77369. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77370. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77371. }
  77372. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77373. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77374. }
  77375. 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) {
  77376. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77377. }
  77378. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77379. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77380. }
  77381. 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) {
  77382. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77383. }
  77384. }
  77385. }
  77386. };
  77387. return GLTFLoaderBase;
  77388. }());
  77389. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77390. /**
  77391. * glTF V1 Loader
  77392. */
  77393. var GLTFLoader = /** @class */ (function () {
  77394. function GLTFLoader() {
  77395. }
  77396. GLTFLoader.RegisterExtension = function (extension) {
  77397. if (GLTFLoader.Extensions[extension.name]) {
  77398. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77399. return;
  77400. }
  77401. GLTFLoader.Extensions[extension.name] = extension;
  77402. };
  77403. GLTFLoader.prototype.dispose = function () {
  77404. // do nothing
  77405. };
  77406. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77407. var _this = this;
  77408. scene.useRightHandedSystem = true;
  77409. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77410. gltfRuntime.importOnlyMeshes = true;
  77411. if (meshesNames === "") {
  77412. gltfRuntime.importMeshesNames = [];
  77413. }
  77414. else if (typeof meshesNames === "string") {
  77415. gltfRuntime.importMeshesNames = [meshesNames];
  77416. }
  77417. else if (meshesNames && !(meshesNames instanceof Array)) {
  77418. gltfRuntime.importMeshesNames = [meshesNames];
  77419. }
  77420. else {
  77421. gltfRuntime.importMeshesNames = [];
  77422. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77423. }
  77424. // Create nodes
  77425. _this._createNodes(gltfRuntime);
  77426. var meshes = new Array();
  77427. var skeletons = new Array();
  77428. // Fill arrays of meshes and skeletons
  77429. for (var nde in gltfRuntime.nodes) {
  77430. var node = gltfRuntime.nodes[nde];
  77431. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77432. meshes.push(node.babylonNode);
  77433. }
  77434. }
  77435. for (var skl in gltfRuntime.skins) {
  77436. var skin = gltfRuntime.skins[skl];
  77437. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77438. skeletons.push(skin.babylonSkeleton);
  77439. }
  77440. }
  77441. // Load buffers, shaders, materials, etc.
  77442. _this._loadBuffersAsync(gltfRuntime, function () {
  77443. _this._loadShadersAsync(gltfRuntime, function () {
  77444. importMaterials(gltfRuntime);
  77445. postLoad(gltfRuntime);
  77446. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77447. onSuccess(meshes, [], skeletons);
  77448. }
  77449. });
  77450. }, onProgress);
  77451. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77452. onSuccess(meshes, [], skeletons);
  77453. }
  77454. }, onError);
  77455. return true;
  77456. };
  77457. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77458. var _this = this;
  77459. scene.useRightHandedSystem = true;
  77460. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77461. // Load runtime extensios
  77462. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77463. // Create nodes
  77464. _this._createNodes(gltfRuntime);
  77465. // Load buffers, shaders, materials, etc.
  77466. _this._loadBuffersAsync(gltfRuntime, function () {
  77467. _this._loadShadersAsync(gltfRuntime, function () {
  77468. importMaterials(gltfRuntime);
  77469. postLoad(gltfRuntime);
  77470. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77471. onSuccess();
  77472. }
  77473. });
  77474. });
  77475. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77476. onSuccess();
  77477. }
  77478. }, onError);
  77479. }, onError);
  77480. };
  77481. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77482. var hasShaders = false;
  77483. var processShader = function (sha, shader) {
  77484. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77485. gltfRuntime.loadedShaderCount++;
  77486. if (shaderString) {
  77487. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77488. }
  77489. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77490. onload();
  77491. }
  77492. }, function () {
  77493. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77494. });
  77495. };
  77496. for (var sha in gltfRuntime.shaders) {
  77497. hasShaders = true;
  77498. var shader = gltfRuntime.shaders[sha];
  77499. if (shader) {
  77500. processShader.bind(this, sha, shader)();
  77501. }
  77502. else {
  77503. BABYLON.Tools.Error("No shader named: " + sha);
  77504. }
  77505. }
  77506. if (!hasShaders) {
  77507. onload();
  77508. }
  77509. };
  77510. ;
  77511. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77512. var hasBuffers = false;
  77513. var processBuffer = function (buf, buffer) {
  77514. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77515. gltfRuntime.loadedBufferCount++;
  77516. if (bufferView) {
  77517. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77518. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77519. }
  77520. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77521. }
  77522. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77523. onLoad();
  77524. }
  77525. }, function () {
  77526. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77527. });
  77528. };
  77529. for (var buf in gltfRuntime.buffers) {
  77530. hasBuffers = true;
  77531. var buffer = gltfRuntime.buffers[buf];
  77532. if (buffer) {
  77533. processBuffer.bind(this, buf, buffer)();
  77534. }
  77535. else {
  77536. BABYLON.Tools.Error("No buffer named: " + buf);
  77537. }
  77538. }
  77539. if (!hasBuffers) {
  77540. onLoad();
  77541. }
  77542. };
  77543. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77544. var currentScene = gltfRuntime.currentScene;
  77545. if (currentScene) {
  77546. // Only one scene even if multiple scenes are defined
  77547. for (var i = 0; i < currentScene.nodes.length; i++) {
  77548. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77549. }
  77550. }
  77551. else {
  77552. // Load all scenes
  77553. for (var thing in gltfRuntime.scenes) {
  77554. currentScene = gltfRuntime.scenes[thing];
  77555. for (var i = 0; i < currentScene.nodes.length; i++) {
  77556. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77557. }
  77558. }
  77559. }
  77560. };
  77561. GLTFLoader.Extensions = {};
  77562. return GLTFLoader;
  77563. }());
  77564. GLTF1.GLTFLoader = GLTFLoader;
  77565. ;
  77566. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77567. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77568. })(BABYLON || (BABYLON = {}));
  77569. //# sourceMappingURL=babylon.glTFLoader.js.map
  77570. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77571. var BABYLON;
  77572. (function (BABYLON) {
  77573. var GLTF1;
  77574. (function (GLTF1) {
  77575. /**
  77576. * Utils functions for GLTF
  77577. */
  77578. var GLTFUtils = /** @class */ (function () {
  77579. function GLTFUtils() {
  77580. }
  77581. /**
  77582. * Sets the given "parameter" matrix
  77583. * @param scene: the {BABYLON.Scene} object
  77584. * @param source: the source node where to pick the matrix
  77585. * @param parameter: the GLTF technique parameter
  77586. * @param uniformName: the name of the shader's uniform
  77587. * @param shaderMaterial: the shader material
  77588. */
  77589. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77590. var mat = null;
  77591. if (parameter.semantic === "MODEL") {
  77592. mat = source.getWorldMatrix();
  77593. }
  77594. else if (parameter.semantic === "PROJECTION") {
  77595. mat = scene.getProjectionMatrix();
  77596. }
  77597. else if (parameter.semantic === "VIEW") {
  77598. mat = scene.getViewMatrix();
  77599. }
  77600. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77601. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77602. }
  77603. else if (parameter.semantic === "MODELVIEW") {
  77604. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77605. }
  77606. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77607. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77608. }
  77609. else if (parameter.semantic === "MODELINVERSE") {
  77610. mat = source.getWorldMatrix().invert();
  77611. }
  77612. else if (parameter.semantic === "VIEWINVERSE") {
  77613. mat = scene.getViewMatrix().invert();
  77614. }
  77615. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77616. mat = scene.getProjectionMatrix().invert();
  77617. }
  77618. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77619. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77620. }
  77621. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77622. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77623. }
  77624. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77625. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77626. }
  77627. else {
  77628. debugger;
  77629. }
  77630. if (mat) {
  77631. switch (parameter.type) {
  77632. case GLTF1.EParameterType.FLOAT_MAT2:
  77633. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77634. break;
  77635. case GLTF1.EParameterType.FLOAT_MAT3:
  77636. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77637. break;
  77638. case GLTF1.EParameterType.FLOAT_MAT4:
  77639. shaderMaterial.setMatrix(uniformName, mat);
  77640. break;
  77641. default: break;
  77642. }
  77643. }
  77644. };
  77645. /**
  77646. * Sets the given "parameter" matrix
  77647. * @param shaderMaterial: the shader material
  77648. * @param uniform: the name of the shader's uniform
  77649. * @param value: the value of the uniform
  77650. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77651. */
  77652. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77653. switch (type) {
  77654. case GLTF1.EParameterType.FLOAT:
  77655. shaderMaterial.setFloat(uniform, value);
  77656. return true;
  77657. case GLTF1.EParameterType.FLOAT_VEC2:
  77658. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77659. return true;
  77660. case GLTF1.EParameterType.FLOAT_VEC3:
  77661. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77662. return true;
  77663. case GLTF1.EParameterType.FLOAT_VEC4:
  77664. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77665. return true;
  77666. default: return false;
  77667. }
  77668. };
  77669. /**
  77670. * If the uri is a base64 string
  77671. * @param uri: the uri to test
  77672. */
  77673. GLTFUtils.IsBase64 = function (uri) {
  77674. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77675. };
  77676. /**
  77677. * Decode the base64 uri
  77678. * @param uri: the uri to decode
  77679. */
  77680. GLTFUtils.DecodeBase64 = function (uri) {
  77681. var decodedString = atob(uri.split(",")[1]);
  77682. var bufferLength = decodedString.length;
  77683. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77684. for (var i = 0; i < bufferLength; i++) {
  77685. bufferView[i] = decodedString.charCodeAt(i);
  77686. }
  77687. return bufferView.buffer;
  77688. };
  77689. /**
  77690. * Returns the wrap mode of the texture
  77691. * @param mode: the mode value
  77692. */
  77693. GLTFUtils.GetWrapMode = function (mode) {
  77694. switch (mode) {
  77695. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77696. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77697. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77698. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77699. }
  77700. };
  77701. /**
  77702. * Returns the byte stride giving an accessor
  77703. * @param accessor: the GLTF accessor objet
  77704. */
  77705. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77706. // Needs this function since "byteStride" isn't requiered in glTF format
  77707. var type = accessor.type;
  77708. switch (type) {
  77709. case "VEC2": return 2;
  77710. case "VEC3": return 3;
  77711. case "VEC4": return 4;
  77712. case "MAT2": return 4;
  77713. case "MAT3": return 9;
  77714. case "MAT4": return 16;
  77715. default: return 1;
  77716. }
  77717. };
  77718. /**
  77719. * Returns the texture filter mode giving a mode value
  77720. * @param mode: the filter mode value
  77721. */
  77722. GLTFUtils.GetTextureFilterMode = function (mode) {
  77723. switch (mode) {
  77724. case GLTF1.ETextureFilterType.LINEAR:
  77725. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77726. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77727. case GLTF1.ETextureFilterType.NEAREST:
  77728. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77729. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77730. }
  77731. };
  77732. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77733. var byteOffset = bufferView.byteOffset + byteOffset;
  77734. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77735. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77736. throw new Error("Buffer access is out of range");
  77737. }
  77738. var buffer = loadedBufferView.buffer;
  77739. byteOffset += loadedBufferView.byteOffset;
  77740. switch (componentType) {
  77741. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77742. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77743. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77744. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77745. default: return new Float32Array(buffer, byteOffset, byteLength);
  77746. }
  77747. };
  77748. /**
  77749. * Returns a buffer from its accessor
  77750. * @param gltfRuntime: the GLTF runtime
  77751. * @param accessor: the GLTF accessor
  77752. */
  77753. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77754. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77755. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77756. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77757. };
  77758. /**
  77759. * Decodes a buffer view into a string
  77760. * @param view: the buffer view
  77761. */
  77762. GLTFUtils.DecodeBufferToText = function (view) {
  77763. var result = "";
  77764. var length = view.byteLength;
  77765. for (var i = 0; i < length; ++i) {
  77766. result += String.fromCharCode(view[i]);
  77767. }
  77768. return result;
  77769. };
  77770. /**
  77771. * Returns the default material of gltf. Related to
  77772. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77773. * @param scene: the Babylon.js scene
  77774. */
  77775. GLTFUtils.GetDefaultMaterial = function (scene) {
  77776. if (!GLTFUtils._DefaultMaterial) {
  77777. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77778. "precision highp float;",
  77779. "",
  77780. "uniform mat4 worldView;",
  77781. "uniform mat4 projection;",
  77782. "",
  77783. "attribute vec3 position;",
  77784. "",
  77785. "void main(void)",
  77786. "{",
  77787. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77788. "}"
  77789. ].join("\n");
  77790. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77791. "precision highp float;",
  77792. "",
  77793. "uniform vec4 u_emission;",
  77794. "",
  77795. "void main(void)",
  77796. "{",
  77797. " gl_FragColor = u_emission;",
  77798. "}"
  77799. ].join("\n");
  77800. var shaderPath = {
  77801. vertex: "GLTFDefaultMaterial",
  77802. fragment: "GLTFDefaultMaterial"
  77803. };
  77804. var options = {
  77805. attributes: ["position"],
  77806. uniforms: ["worldView", "projection", "u_emission"],
  77807. samplers: new Array(),
  77808. needAlphaBlending: false
  77809. };
  77810. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77811. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77812. }
  77813. return GLTFUtils._DefaultMaterial;
  77814. };
  77815. // The GLTF default material
  77816. GLTFUtils._DefaultMaterial = null;
  77817. return GLTFUtils;
  77818. }());
  77819. GLTF1.GLTFUtils = GLTFUtils;
  77820. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77821. })(BABYLON || (BABYLON = {}));
  77822. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77823. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77824. var BABYLON;
  77825. (function (BABYLON) {
  77826. var GLTF1;
  77827. (function (GLTF1) {
  77828. var GLTFLoaderExtension = /** @class */ (function () {
  77829. function GLTFLoaderExtension(name) {
  77830. this._name = name;
  77831. }
  77832. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77833. get: function () {
  77834. return this._name;
  77835. },
  77836. enumerable: true,
  77837. configurable: true
  77838. });
  77839. /**
  77840. * Defines an override for loading the runtime
  77841. * Return true to stop further extensions from loading the runtime
  77842. */
  77843. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77844. return false;
  77845. };
  77846. /**
  77847. * Defines an onverride for creating gltf runtime
  77848. * Return true to stop further extensions from creating the runtime
  77849. */
  77850. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77851. return false;
  77852. };
  77853. /**
  77854. * Defines an override for loading buffers
  77855. * Return true to stop further extensions from loading this buffer
  77856. */
  77857. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77858. return false;
  77859. };
  77860. /**
  77861. * Defines an override for loading texture buffers
  77862. * Return true to stop further extensions from loading this texture data
  77863. */
  77864. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77865. return false;
  77866. };
  77867. /**
  77868. * Defines an override for creating textures
  77869. * Return true to stop further extensions from loading this texture
  77870. */
  77871. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77872. return false;
  77873. };
  77874. /**
  77875. * Defines an override for loading shader strings
  77876. * Return true to stop further extensions from loading this shader data
  77877. */
  77878. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77879. return false;
  77880. };
  77881. /**
  77882. * Defines an override for loading materials
  77883. * Return true to stop further extensions from loading this material
  77884. */
  77885. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77886. return false;
  77887. };
  77888. // ---------
  77889. // Utilities
  77890. // ---------
  77891. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77892. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77893. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  77894. }, function () {
  77895. setTimeout(function () {
  77896. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77897. });
  77898. });
  77899. };
  77900. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77901. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77902. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  77903. }, function () {
  77904. setTimeout(function () {
  77905. onSuccess();
  77906. });
  77907. });
  77908. };
  77909. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77910. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77911. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77912. }, function () {
  77913. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77914. });
  77915. };
  77916. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  77917. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  77918. };
  77919. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77920. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77921. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77922. }, function () {
  77923. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77924. });
  77925. };
  77926. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77927. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77928. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77929. }, function () {
  77930. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77931. });
  77932. };
  77933. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77934. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77935. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77936. }, function () {
  77937. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77938. });
  77939. };
  77940. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77941. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77942. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77943. }, function () {
  77944. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77945. });
  77946. };
  77947. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  77948. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  77949. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  77950. if (func(loaderExtension)) {
  77951. return;
  77952. }
  77953. }
  77954. defaultFunc();
  77955. };
  77956. return GLTFLoaderExtension;
  77957. }());
  77958. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  77959. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77960. })(BABYLON || (BABYLON = {}));
  77961. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  77962. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77963. var BABYLON;
  77964. (function (BABYLON) {
  77965. var GLTF1;
  77966. (function (GLTF1) {
  77967. var BinaryExtensionBufferName = "binary_glTF";
  77968. ;
  77969. ;
  77970. var GLTFBinaryExtension = /** @class */ (function (_super) {
  77971. __extends(GLTFBinaryExtension, _super);
  77972. function GLTFBinaryExtension() {
  77973. return _super.call(this, "KHR_binary_glTF") || this;
  77974. }
  77975. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77976. var extensionsUsed = data.json.extensionsUsed;
  77977. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  77978. return false;
  77979. }
  77980. this._bin = data.bin;
  77981. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77982. return true;
  77983. };
  77984. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77985. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  77986. return false;
  77987. }
  77988. if (id !== BinaryExtensionBufferName) {
  77989. return false;
  77990. }
  77991. onSuccess(this._bin);
  77992. return true;
  77993. };
  77994. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77995. var texture = gltfRuntime.textures[id];
  77996. var source = gltfRuntime.images[texture.source];
  77997. if (!source.extensions || !(this.name in source.extensions)) {
  77998. return false;
  77999. }
  78000. var sourceExt = source.extensions[this.name];
  78001. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78002. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78003. onSuccess(buffer);
  78004. return true;
  78005. };
  78006. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78007. var shader = gltfRuntime.shaders[id];
  78008. if (!shader.extensions || !(this.name in shader.extensions)) {
  78009. return false;
  78010. }
  78011. var binaryExtensionShader = shader.extensions[this.name];
  78012. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78013. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78014. setTimeout(function () {
  78015. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78016. onSuccess(shaderString);
  78017. });
  78018. return true;
  78019. };
  78020. return GLTFBinaryExtension;
  78021. }(GLTF1.GLTFLoaderExtension));
  78022. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78023. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78024. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78025. })(BABYLON || (BABYLON = {}));
  78026. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78027. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78028. var BABYLON;
  78029. (function (BABYLON) {
  78030. var GLTF1;
  78031. (function (GLTF1) {
  78032. ;
  78033. ;
  78034. ;
  78035. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78036. __extends(GLTFMaterialsCommonExtension, _super);
  78037. function GLTFMaterialsCommonExtension() {
  78038. return _super.call(this, "KHR_materials_common") || this;
  78039. }
  78040. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78041. if (!gltfRuntime.extensions)
  78042. return false;
  78043. var extension = gltfRuntime.extensions[this.name];
  78044. if (!extension)
  78045. return false;
  78046. // Create lights
  78047. var lights = extension.lights;
  78048. if (lights) {
  78049. for (var thing in lights) {
  78050. var light = lights[thing];
  78051. switch (light.type) {
  78052. case "ambient":
  78053. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78054. var ambient = light.ambient;
  78055. if (ambient) {
  78056. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78057. }
  78058. break;
  78059. case "point":
  78060. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78061. var point = light.point;
  78062. if (point) {
  78063. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78064. }
  78065. break;
  78066. case "directional":
  78067. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78068. var directional = light.directional;
  78069. if (directional) {
  78070. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78071. }
  78072. break;
  78073. case "spot":
  78074. var spot = light.spot;
  78075. if (spot) {
  78076. 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);
  78077. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78078. }
  78079. break;
  78080. default:
  78081. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78082. break;
  78083. }
  78084. }
  78085. }
  78086. return false;
  78087. };
  78088. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78089. var material = gltfRuntime.materials[id];
  78090. if (!material || !material.extensions)
  78091. return false;
  78092. var extension = material.extensions[this.name];
  78093. if (!extension)
  78094. return false;
  78095. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78096. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78097. if (extension.technique === "CONSTANT") {
  78098. standardMaterial.disableLighting = true;
  78099. }
  78100. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78101. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78102. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78103. // Ambient
  78104. if (typeof extension.values.ambient === "string") {
  78105. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78106. }
  78107. else {
  78108. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78109. }
  78110. // Diffuse
  78111. if (typeof extension.values.diffuse === "string") {
  78112. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78113. }
  78114. else {
  78115. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  78116. }
  78117. // Emission
  78118. if (typeof extension.values.emission === "string") {
  78119. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  78120. }
  78121. else {
  78122. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  78123. }
  78124. // Specular
  78125. if (typeof extension.values.specular === "string") {
  78126. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  78127. }
  78128. else {
  78129. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  78130. }
  78131. return true;
  78132. };
  78133. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  78134. // Create buffer from texture url
  78135. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  78136. // Create texture from buffer
  78137. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  78138. }, onError);
  78139. };
  78140. return GLTFMaterialsCommonExtension;
  78141. }(GLTF1.GLTFLoaderExtension));
  78142. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  78143. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  78144. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78145. })(BABYLON || (BABYLON = {}));
  78146. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  78147. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78148. var BABYLON;
  78149. (function (BABYLON) {
  78150. var GLTF2;
  78151. (function (GLTF2) {
  78152. /**
  78153. * Enums
  78154. */
  78155. var EComponentType;
  78156. (function (EComponentType) {
  78157. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78158. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78159. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78160. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78161. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78162. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78163. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  78164. var EMeshPrimitiveMode;
  78165. (function (EMeshPrimitiveMode) {
  78166. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  78167. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  78168. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  78169. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  78170. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  78171. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  78172. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  78173. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  78174. var ETextureMagFilter;
  78175. (function (ETextureMagFilter) {
  78176. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  78177. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  78178. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  78179. var ETextureMinFilter;
  78180. (function (ETextureMinFilter) {
  78181. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  78182. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  78183. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78184. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78185. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78186. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78187. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  78188. var ETextureWrapMode;
  78189. (function (ETextureWrapMode) {
  78190. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78191. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78192. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78193. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  78194. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78195. })(BABYLON || (BABYLON = {}));
  78196. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78197. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78198. var BABYLON;
  78199. (function (BABYLON) {
  78200. var GLTF2;
  78201. (function (GLTF2) {
  78202. var GLTFLoaderTracker = /** @class */ (function () {
  78203. function GLTFLoaderTracker(onComplete) {
  78204. this._pendingCount = 0;
  78205. this._callback = onComplete;
  78206. }
  78207. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  78208. this._pendingCount++;
  78209. };
  78210. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  78211. if (--this._pendingCount === 0) {
  78212. this._callback();
  78213. }
  78214. };
  78215. return GLTFLoaderTracker;
  78216. }());
  78217. var GLTFLoader = /** @class */ (function () {
  78218. function GLTFLoader(parent) {
  78219. this._disposed = false;
  78220. this._renderReady = false;
  78221. this._requests = new Array();
  78222. this._renderReadyObservable = new BABYLON.Observable();
  78223. // Count of pending work that needs to complete before the asset is rendered.
  78224. this._renderPendingCount = 0;
  78225. // Count of pending work that needs to complete before the loader is disposed.
  78226. this._loaderPendingCount = 0;
  78227. this._loaderTrackers = new Array();
  78228. this._parent = parent;
  78229. }
  78230. GLTFLoader.RegisterExtension = function (extension) {
  78231. if (GLTFLoader.Extensions[extension.name]) {
  78232. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  78233. return;
  78234. }
  78235. GLTFLoader.Extensions[extension.name] = extension;
  78236. // Keep the order of registration so that extensions registered first are called first.
  78237. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  78238. };
  78239. GLTFLoader.prototype.dispose = function () {
  78240. if (this._disposed) {
  78241. return;
  78242. }
  78243. this._disposed = true;
  78244. // Abort requests that are not complete
  78245. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  78246. var request = _a[_i];
  78247. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  78248. request.abort();
  78249. }
  78250. }
  78251. // Revoke object urls created during load
  78252. if (this._gltf.textures) {
  78253. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  78254. var texture = _c[_b];
  78255. if (texture.url) {
  78256. URL.revokeObjectURL(texture.url);
  78257. }
  78258. }
  78259. }
  78260. };
  78261. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78262. var _this = this;
  78263. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  78264. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  78265. }, onProgress, onError);
  78266. };
  78267. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78268. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  78269. };
  78270. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78271. var _this = this;
  78272. this._tryCatchOnError(function () {
  78273. _this._loadData(data);
  78274. _this._babylonScene = scene;
  78275. _this._rootUrl = rootUrl;
  78276. _this._successCallback = onSuccess;
  78277. _this._progressCallback = onProgress;
  78278. _this._errorCallback = onError;
  78279. _this._addPendingData(_this);
  78280. _this._loadDefaultScene(nodeNames);
  78281. _this._loadAnimations();
  78282. _this._removePendingData(_this);
  78283. });
  78284. };
  78285. GLTFLoader.prototype._onProgress = function (event) {
  78286. if (this._progressCallback) {
  78287. this._progressCallback(event);
  78288. }
  78289. };
  78290. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  78291. if (this._renderReady) {
  78292. func();
  78293. }
  78294. else {
  78295. this._renderReadyObservable.add(func);
  78296. }
  78297. };
  78298. GLTFLoader.prototype._onRenderReady = function () {
  78299. this._rootNode.babylonMesh.setEnabled(true);
  78300. this._startAnimations();
  78301. this._successCallback();
  78302. this._renderReadyObservable.notifyObservers(this);
  78303. };
  78304. GLTFLoader.prototype._onComplete = function () {
  78305. if (this._parent.onComplete) {
  78306. this._parent.onComplete();
  78307. }
  78308. this.dispose();
  78309. };
  78310. GLTFLoader.prototype._loadData = function (data) {
  78311. this._gltf = data.json;
  78312. // Assign the index of each object for convinience.
  78313. GLTFLoader._AssignIndices(this._gltf.accessors);
  78314. GLTFLoader._AssignIndices(this._gltf.animations);
  78315. GLTFLoader._AssignIndices(this._gltf.buffers);
  78316. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  78317. GLTFLoader._AssignIndices(this._gltf.images);
  78318. GLTFLoader._AssignIndices(this._gltf.materials);
  78319. GLTFLoader._AssignIndices(this._gltf.meshes);
  78320. GLTFLoader._AssignIndices(this._gltf.nodes);
  78321. GLTFLoader._AssignIndices(this._gltf.scenes);
  78322. GLTFLoader._AssignIndices(this._gltf.skins);
  78323. GLTFLoader._AssignIndices(this._gltf.textures);
  78324. if (data.bin) {
  78325. var buffers = this._gltf.buffers;
  78326. if (buffers && buffers[0] && !buffers[0].uri) {
  78327. var binaryBuffer = buffers[0];
  78328. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78329. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78330. }
  78331. binaryBuffer.loadedData = data.bin;
  78332. }
  78333. else {
  78334. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78335. }
  78336. }
  78337. };
  78338. GLTFLoader.prototype._getMeshes = function () {
  78339. var meshes = new Array();
  78340. // Root mesh is always first.
  78341. meshes.push(this._rootNode.babylonMesh);
  78342. var nodes = this._gltf.nodes;
  78343. if (nodes) {
  78344. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78345. var node = nodes_1[_i];
  78346. if (node.babylonMesh) {
  78347. meshes.push(node.babylonMesh);
  78348. }
  78349. }
  78350. }
  78351. return meshes;
  78352. };
  78353. GLTFLoader.prototype._getSkeletons = function () {
  78354. var skeletons = new Array();
  78355. var skins = this._gltf.skins;
  78356. if (skins) {
  78357. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78358. var skin = skins_1[_i];
  78359. if (skin.babylonSkeleton) {
  78360. skeletons.push(skin.babylonSkeleton);
  78361. }
  78362. }
  78363. }
  78364. return skeletons;
  78365. };
  78366. GLTFLoader.prototype._getAnimationTargets = function () {
  78367. var targets = new Array();
  78368. var animations = this._gltf.animations;
  78369. if (animations) {
  78370. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78371. var animation = animations_1[_i];
  78372. targets.push.apply(targets, animation.targets);
  78373. }
  78374. }
  78375. return targets;
  78376. };
  78377. GLTFLoader.prototype._startAnimations = function () {
  78378. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78379. var target = _a[_i];
  78380. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78381. }
  78382. };
  78383. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78384. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  78385. if (!scene) {
  78386. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78387. }
  78388. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78389. };
  78390. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78391. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78392. switch (this._parent.coordinateSystemMode) {
  78393. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  78394. if (!this._babylonScene.useRightHandedSystem) {
  78395. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78396. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78397. }
  78398. break;
  78399. }
  78400. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  78401. // do nothing
  78402. break;
  78403. }
  78404. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  78405. this._babylonScene.useRightHandedSystem = true;
  78406. break;
  78407. }
  78408. default: {
  78409. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  78410. return;
  78411. }
  78412. }
  78413. var nodeIndices = scene.nodes;
  78414. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78415. node.parent = parentNode;
  78416. return true;
  78417. }, this._rootNode);
  78418. if (nodeNames) {
  78419. if (!(nodeNames instanceof Array)) {
  78420. nodeNames = [nodeNames];
  78421. }
  78422. var filteredNodeIndices_1 = new Array();
  78423. this._traverseNodes(context, nodeIndices, function (node) {
  78424. if (nodeNames.indexOf(node.name) !== -1) {
  78425. filteredNodeIndices_1.push(node.index);
  78426. return false;
  78427. }
  78428. return true;
  78429. }, this._rootNode);
  78430. nodeIndices = filteredNodeIndices_1;
  78431. }
  78432. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78433. var index = nodeIndices_1[_i];
  78434. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78435. if (!node) {
  78436. throw new Error(context + ": Failed to find node " + index);
  78437. }
  78438. this._loadNode("#/nodes/" + index, node);
  78439. }
  78440. // Disable the root mesh until the asset is ready to render.
  78441. this._rootNode.babylonMesh.setEnabled(false);
  78442. };
  78443. GLTFLoader.prototype._loadNode = function (context, node) {
  78444. node.babylonBones = {};
  78445. node.babylonAnimationTargets = [];
  78446. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78447. return;
  78448. }
  78449. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78450. this._loadTransform(node);
  78451. if (node.mesh != null) {
  78452. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  78453. if (!mesh) {
  78454. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78455. }
  78456. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78457. }
  78458. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  78459. node.babylonAnimationTargets.push(node.babylonMesh);
  78460. if (node.skin != null) {
  78461. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  78462. if (!skin) {
  78463. throw new Error(context + ": Failed to find skin " + node.skin);
  78464. }
  78465. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78466. }
  78467. if (node.camera != null) {
  78468. // TODO: handle cameras
  78469. }
  78470. if (node.children) {
  78471. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78472. var index = _a[_i];
  78473. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78474. if (!childNode) {
  78475. throw new Error(context + ": Failed to find child node " + index);
  78476. }
  78477. this._loadNode("#/nodes/" + index, childNode);
  78478. }
  78479. }
  78480. };
  78481. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78482. var _this = this;
  78483. var primitives = mesh.primitives;
  78484. if (!primitives || primitives.length === 0) {
  78485. throw new Error(context + ": Primitives are missing");
  78486. }
  78487. this._createMorphTargets(context, node, mesh);
  78488. this._loadAllVertexDataAsync(context, mesh, function () {
  78489. _this._loadMorphTargets(context, node, mesh);
  78490. var vertexData = new BABYLON.VertexData();
  78491. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78492. var primitive = primitives_1[_i];
  78493. vertexData.merge(primitive.vertexData);
  78494. }
  78495. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78496. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78497. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78498. node.babylonMesh.subMeshes = [];
  78499. var verticesStart = 0;
  78500. var indicesStart = 0;
  78501. for (var index = 0; index < primitives.length; index++) {
  78502. var vertexData_1 = primitives[index].vertexData;
  78503. var verticesCount = vertexData_1.positions.length;
  78504. var indicesCount = vertexData_1.indices.length;
  78505. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78506. verticesStart += verticesCount;
  78507. indicesStart += indicesCount;
  78508. }
  78509. ;
  78510. });
  78511. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78512. node.babylonMesh.material = multiMaterial;
  78513. var subMaterials = multiMaterial.subMaterials;
  78514. var _loop_1 = function (index) {
  78515. var primitive = primitives[index];
  78516. if (primitive.material == null) {
  78517. subMaterials[index] = this_1._getDefaultMaterial();
  78518. }
  78519. else {
  78520. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  78521. if (!material_1) {
  78522. throw new Error(context + ": Failed to find material " + primitive.material);
  78523. }
  78524. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78525. if (isNew && _this._parent.onMaterialLoaded) {
  78526. _this._parent.onMaterialLoaded(babylonMaterial);
  78527. }
  78528. if (_this._parent.onBeforeMaterialReadyAsync) {
  78529. _this._addLoaderPendingData(material_1);
  78530. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78531. _this._tryCatchOnError(function () {
  78532. subMaterials[index] = babylonMaterial;
  78533. _this._removeLoaderPendingData(material_1);
  78534. });
  78535. });
  78536. }
  78537. else {
  78538. subMaterials[index] = babylonMaterial;
  78539. }
  78540. });
  78541. }
  78542. };
  78543. var this_1 = this;
  78544. for (var index = 0; index < primitives.length; index++) {
  78545. _loop_1(index);
  78546. }
  78547. ;
  78548. };
  78549. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78550. var primitives = mesh.primitives;
  78551. var numRemainingPrimitives = primitives.length;
  78552. var _loop_2 = function (index) {
  78553. var primitive = primitives[index];
  78554. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78555. primitive.vertexData = vertexData;
  78556. if (--numRemainingPrimitives === 0) {
  78557. onSuccess();
  78558. }
  78559. });
  78560. };
  78561. var this_2 = this;
  78562. for (var index = 0; index < primitives.length; index++) {
  78563. _loop_2(index);
  78564. }
  78565. };
  78566. /**
  78567. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78568. * @param {ArrayBufferView} data
  78569. * @param {IGLTFAccessor} accessor
  78570. */
  78571. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78572. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78573. return data;
  78574. }
  78575. var buffer = data;
  78576. var factor = 1;
  78577. switch (accessor.componentType) {
  78578. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78579. factor = 1 / 255;
  78580. break;
  78581. }
  78582. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78583. factor = 1 / 65535;
  78584. break;
  78585. }
  78586. default: {
  78587. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78588. }
  78589. }
  78590. var result = new Float32Array(accessor.count * 2);
  78591. for (var i = 0; i < result.length; ++i) {
  78592. result[i] = buffer[i] * factor;
  78593. }
  78594. return result;
  78595. };
  78596. /**
  78597. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78598. * @param {ArrayBufferView} data
  78599. * @param {IGLTFAccessor} accessor
  78600. */
  78601. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78602. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  78603. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78604. return data;
  78605. }
  78606. var buffer = data;
  78607. var factor = 1;
  78608. switch (accessor.componentType) {
  78609. case GLTF2.EComponentType.FLOAT: {
  78610. factor = 1;
  78611. break;
  78612. }
  78613. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78614. factor = 1 / 255;
  78615. break;
  78616. }
  78617. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78618. factor = 1 / 65535;
  78619. break;
  78620. }
  78621. default: {
  78622. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78623. }
  78624. }
  78625. var result = new Float32Array(accessor.count * 4);
  78626. if (colorComponentCount === 4) {
  78627. for (var i = 0; i < result.length; ++i) {
  78628. result[i] = buffer[i] * factor;
  78629. }
  78630. }
  78631. else {
  78632. var offset = 0;
  78633. for (var i = 0; i < result.length; ++i) {
  78634. if ((i + 1) % 4 === 0) {
  78635. result[i] = 1;
  78636. }
  78637. else {
  78638. result[i] = buffer[offset++] * factor;
  78639. }
  78640. }
  78641. }
  78642. return result;
  78643. };
  78644. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78645. var _this = this;
  78646. var attributes = primitive.attributes;
  78647. if (!attributes) {
  78648. throw new Error(context + ": Attributes are missing");
  78649. }
  78650. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78651. // TODO: handle other primitive modes
  78652. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78653. }
  78654. var vertexData = new BABYLON.VertexData();
  78655. var numRemainingAttributes = Object.keys(attributes).length;
  78656. var _loop_3 = function (attribute) {
  78657. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  78658. if (!accessor) {
  78659. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78660. }
  78661. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78662. switch (attribute) {
  78663. case "POSITION": {
  78664. vertexData.positions = data;
  78665. break;
  78666. }
  78667. case "NORMAL": {
  78668. vertexData.normals = data;
  78669. break;
  78670. }
  78671. case "TANGENT": {
  78672. vertexData.tangents = data;
  78673. break;
  78674. }
  78675. case "TEXCOORD_0": {
  78676. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78677. break;
  78678. }
  78679. case "TEXCOORD_1": {
  78680. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78681. break;
  78682. }
  78683. case "JOINTS_0": {
  78684. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78685. break;
  78686. }
  78687. case "WEIGHTS_0": {
  78688. //TODO: need to add support for normalized weights.
  78689. vertexData.matricesWeights = data;
  78690. break;
  78691. }
  78692. case "COLOR_0": {
  78693. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78694. break;
  78695. }
  78696. default: {
  78697. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78698. break;
  78699. }
  78700. }
  78701. if (--numRemainingAttributes === 0) {
  78702. if (primitive.indices == null) {
  78703. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78704. for (var i = 0; i < vertexData.indices.length; i++) {
  78705. vertexData.indices[i] = i;
  78706. }
  78707. onSuccess(vertexData);
  78708. }
  78709. else {
  78710. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  78711. if (!indicesAccessor) {
  78712. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78713. }
  78714. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78715. vertexData.indices = data;
  78716. onSuccess(vertexData);
  78717. });
  78718. }
  78719. }
  78720. });
  78721. };
  78722. var this_3 = this;
  78723. for (var attribute in attributes) {
  78724. _loop_3(attribute);
  78725. }
  78726. };
  78727. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78728. var primitives = mesh.primitives;
  78729. var targets = primitives[0].targets;
  78730. if (!targets) {
  78731. return;
  78732. }
  78733. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78734. var primitive = primitives_2[_i];
  78735. if (!primitive.targets || primitive.targets.length != targets.length) {
  78736. throw new Error(context + ": All primitives are required to list the same number of targets");
  78737. }
  78738. }
  78739. var morphTargetManager = new BABYLON.MorphTargetManager();
  78740. node.babylonMesh.morphTargetManager = morphTargetManager;
  78741. for (var index = 0; index < targets.length; index++) {
  78742. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78743. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78744. }
  78745. };
  78746. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78747. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78748. if (!morphTargetManager) {
  78749. return;
  78750. }
  78751. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78752. var numTargets = morphTargetManager.numTargets;
  78753. for (var index = 0; index < numTargets; index++) {
  78754. var vertexData = new BABYLON.VertexData();
  78755. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78756. var primitive = _a[_i];
  78757. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78758. }
  78759. if (!vertexData.positions) {
  78760. throw new Error(context + ": Positions are missing");
  78761. }
  78762. var target = morphTargetManager.getTarget(index);
  78763. target.setPositions(vertexData.positions);
  78764. target.setNormals(vertexData.normals);
  78765. target.setTangents(vertexData.tangents);
  78766. }
  78767. });
  78768. };
  78769. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78770. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78771. var _loop_4 = function (primitive) {
  78772. var targets = primitive.targets;
  78773. primitive.targetsVertexData = new Array(targets.length);
  78774. var _loop_5 = function (index) {
  78775. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78776. primitive.targetsVertexData[index] = vertexData;
  78777. if (--numRemainingTargets === 0) {
  78778. onSuccess();
  78779. }
  78780. });
  78781. };
  78782. for (var index = 0; index < targets.length; index++) {
  78783. _loop_5(index);
  78784. }
  78785. };
  78786. var this_4 = this;
  78787. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78788. var primitive = _a[_i];
  78789. _loop_4(primitive);
  78790. }
  78791. };
  78792. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78793. var targetVertexData = new BABYLON.VertexData();
  78794. var numRemainingAttributes = Object.keys(attributes).length;
  78795. var _loop_6 = function (attribute) {
  78796. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  78797. if (!accessor) {
  78798. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78799. }
  78800. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78801. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78802. // As a result we have to add the original data to the delta to calculate the final data.
  78803. var values = data;
  78804. switch (attribute) {
  78805. case "POSITION": {
  78806. for (var i = 0; i < values.length; i++) {
  78807. values[i] += vertexData.positions[i];
  78808. }
  78809. targetVertexData.positions = values;
  78810. break;
  78811. }
  78812. case "NORMAL": {
  78813. for (var i = 0; i < values.length; i++) {
  78814. values[i] += vertexData.normals[i];
  78815. }
  78816. targetVertexData.normals = values;
  78817. break;
  78818. }
  78819. case "TANGENT": {
  78820. // Tangent data for morph targets is stored as xyz delta.
  78821. // The vertexData.tangent is stored as xyzw.
  78822. // So we need to skip every fourth vertexData.tangent.
  78823. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78824. values[i] += vertexData.tangents[j];
  78825. if ((i + 1) % 3 == 0) {
  78826. j++;
  78827. }
  78828. }
  78829. targetVertexData.tangents = values;
  78830. break;
  78831. }
  78832. default: {
  78833. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78834. break;
  78835. }
  78836. }
  78837. if (--numRemainingAttributes === 0) {
  78838. onSuccess(targetVertexData);
  78839. }
  78840. });
  78841. };
  78842. var this_5 = this;
  78843. for (var attribute in attributes) {
  78844. _loop_6(attribute);
  78845. }
  78846. };
  78847. GLTFLoader.prototype._loadTransform = function (node) {
  78848. var position = BABYLON.Vector3.Zero();
  78849. var rotation = BABYLON.Quaternion.Identity();
  78850. var scaling = BABYLON.Vector3.One();
  78851. if (node.matrix) {
  78852. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  78853. matrix.decompose(scaling, rotation, position);
  78854. }
  78855. else {
  78856. if (node.translation)
  78857. position = BABYLON.Vector3.FromArray(node.translation);
  78858. if (node.rotation)
  78859. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  78860. if (node.scale)
  78861. scaling = BABYLON.Vector3.FromArray(node.scale);
  78862. }
  78863. node.babylonMesh.position = position;
  78864. node.babylonMesh.rotationQuaternion = rotation;
  78865. node.babylonMesh.scaling = scaling;
  78866. };
  78867. GLTFLoader.prototype._loadSkin = function (context, skin) {
  78868. var _this = this;
  78869. var skeletonId = "skeleton" + skin.index;
  78870. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  78871. if (skin.inverseBindMatrices == null) {
  78872. this._loadBones(context, skin, null);
  78873. }
  78874. else {
  78875. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  78876. if (!accessor) {
  78877. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  78878. }
  78879. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78880. _this._loadBones(context, skin, data);
  78881. });
  78882. }
  78883. return skin.babylonSkeleton;
  78884. };
  78885. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  78886. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  78887. node.babylonBones[skin.index] = babylonBone;
  78888. node.babylonAnimationTargets.push(babylonBone);
  78889. return babylonBone;
  78890. };
  78891. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  78892. var babylonBones = {};
  78893. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  78894. var index = _a[_i];
  78895. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78896. if (!node) {
  78897. throw new Error(context + ": Failed to find joint " + index);
  78898. }
  78899. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  78900. }
  78901. };
  78902. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  78903. var babylonBone = babylonBones[node.index];
  78904. if (babylonBone) {
  78905. return babylonBone;
  78906. }
  78907. var boneIndex = skin.joints.indexOf(node.index);
  78908. var baseMatrix = BABYLON.Matrix.Identity();
  78909. if (inverseBindMatrixData && boneIndex !== -1) {
  78910. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  78911. baseMatrix.invertToRef(baseMatrix);
  78912. }
  78913. var babylonParentBone = null;
  78914. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  78915. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  78916. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  78917. }
  78918. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  78919. babylonBones[node.index] = babylonBone;
  78920. return babylonBone;
  78921. };
  78922. GLTFLoader.prototype._getNodeMatrix = function (node) {
  78923. return node.matrix ?
  78924. BABYLON.Matrix.FromArray(node.matrix) :
  78925. 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());
  78926. };
  78927. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  78928. if (parentNode === void 0) { parentNode = null; }
  78929. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  78930. var index = indices_1[_i];
  78931. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78932. if (!node) {
  78933. throw new Error(context + ": Failed to find node " + index);
  78934. }
  78935. this._traverseNode(context, node, action, parentNode);
  78936. }
  78937. };
  78938. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  78939. if (parentNode === void 0) { parentNode = null; }
  78940. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  78941. return;
  78942. }
  78943. if (!action(node, parentNode)) {
  78944. return;
  78945. }
  78946. if (node.children) {
  78947. this._traverseNodes(context, node.children, action, node);
  78948. }
  78949. };
  78950. GLTFLoader.prototype._loadAnimations = function () {
  78951. var animations = this._gltf.animations;
  78952. if (!animations) {
  78953. return;
  78954. }
  78955. for (var index = 0; index < animations.length; index++) {
  78956. var animation = animations[index];
  78957. this._loadAnimation("#/animations/" + index, animation);
  78958. }
  78959. };
  78960. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  78961. animation.targets = [];
  78962. for (var index = 0; index < animation.channels.length; index++) {
  78963. var channel = GLTFLoader._GetProperty(animation.channels, index);
  78964. if (!channel) {
  78965. throw new Error(context + ": Failed to find channel " + index);
  78966. }
  78967. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  78968. if (!sampler) {
  78969. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  78970. }
  78971. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  78972. }
  78973. };
  78974. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  78975. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  78976. if (!targetNode) {
  78977. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  78978. }
  78979. var targetPath;
  78980. var animationType;
  78981. switch (channel.target.path) {
  78982. case "translation": {
  78983. targetPath = "position";
  78984. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78985. break;
  78986. }
  78987. case "rotation": {
  78988. targetPath = "rotationQuaternion";
  78989. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78990. break;
  78991. }
  78992. case "scale": {
  78993. targetPath = "scaling";
  78994. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78995. break;
  78996. }
  78997. case "weights": {
  78998. targetPath = "influence";
  78999. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79000. break;
  79001. }
  79002. default: {
  79003. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79004. }
  79005. }
  79006. var inputData;
  79007. var outputData;
  79008. var checkSuccess = function () {
  79009. if (!inputData || !outputData) {
  79010. return;
  79011. }
  79012. var outputBufferOffset = 0;
  79013. var getNextOutputValue;
  79014. switch (targetPath) {
  79015. case "position": {
  79016. getNextOutputValue = function () {
  79017. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79018. outputBufferOffset += 3;
  79019. return value;
  79020. };
  79021. break;
  79022. }
  79023. case "rotationQuaternion": {
  79024. getNextOutputValue = function () {
  79025. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79026. outputBufferOffset += 4;
  79027. return value;
  79028. };
  79029. break;
  79030. }
  79031. case "scaling": {
  79032. getNextOutputValue = function () {
  79033. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79034. outputBufferOffset += 3;
  79035. return value;
  79036. };
  79037. break;
  79038. }
  79039. case "influence": {
  79040. getNextOutputValue = function () {
  79041. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79042. var value = new Array(numTargets);
  79043. for (var i = 0; i < numTargets; i++) {
  79044. value[i] = outputData[outputBufferOffset++];
  79045. }
  79046. return value;
  79047. };
  79048. break;
  79049. }
  79050. }
  79051. var getNextKey;
  79052. switch (sampler.interpolation) {
  79053. case "LINEAR": {
  79054. getNextKey = function (frameIndex) { return ({
  79055. frame: inputData[frameIndex],
  79056. value: getNextOutputValue()
  79057. }); };
  79058. break;
  79059. }
  79060. case "CUBICSPLINE": {
  79061. getNextKey = function (frameIndex) { return ({
  79062. frame: inputData[frameIndex],
  79063. inTangent: getNextOutputValue(),
  79064. value: getNextOutputValue(),
  79065. outTangent: getNextOutputValue()
  79066. }); };
  79067. break;
  79068. }
  79069. default: {
  79070. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79071. }
  79072. }
  79073. ;
  79074. var keys = new Array(inputData.length);
  79075. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79076. keys[frameIndex] = getNextKey(frameIndex);
  79077. }
  79078. if (targetPath === "influence") {
  79079. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79080. var _loop_7 = function (targetIndex) {
  79081. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79082. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79083. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79084. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79085. frame: key.frame,
  79086. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79087. value: key.value[targetIndex],
  79088. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79089. }); }));
  79090. morphTarget.animations.push(babylonAnimation);
  79091. animation.targets.push(morphTarget);
  79092. };
  79093. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79094. _loop_7(targetIndex);
  79095. }
  79096. }
  79097. else {
  79098. var animationName = animation.name || "anim" + animation.index;
  79099. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79100. babylonAnimation.setKeys(keys);
  79101. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79102. var target = _a[_i];
  79103. target.animations.push(babylonAnimation.clone());
  79104. animation.targets.push(target);
  79105. }
  79106. }
  79107. };
  79108. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79109. if (!inputAccessor) {
  79110. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79111. }
  79112. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  79113. inputData = data;
  79114. checkSuccess();
  79115. });
  79116. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  79117. if (!outputAccessor) {
  79118. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  79119. }
  79120. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  79121. outputData = data;
  79122. checkSuccess();
  79123. });
  79124. };
  79125. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  79126. var _this = this;
  79127. this._addPendingData(buffer);
  79128. if (buffer.loadedData) {
  79129. onSuccess(buffer.loadedData);
  79130. this._removePendingData(buffer);
  79131. }
  79132. else if (buffer.loadedObservable) {
  79133. buffer.loadedObservable.add(function (buffer) {
  79134. onSuccess(buffer.loadedData);
  79135. _this._removePendingData(buffer);
  79136. });
  79137. }
  79138. else {
  79139. if (!buffer.uri) {
  79140. throw new Error(context + ": Uri is missing");
  79141. }
  79142. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  79143. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  79144. buffer.loadedData = new Uint8Array(data);
  79145. onSuccess(buffer.loadedData);
  79146. this._removePendingData(buffer);
  79147. }
  79148. else {
  79149. buffer.loadedObservable = new BABYLON.Observable();
  79150. buffer.loadedObservable.add(function (buffer) {
  79151. onSuccess(buffer.loadedData);
  79152. _this._removePendingData(buffer);
  79153. });
  79154. this._loadUri(context, buffer.uri, function (data) {
  79155. buffer.loadedData = data;
  79156. buffer.loadedObservable.notifyObservers(buffer);
  79157. buffer.loadedObservable = undefined;
  79158. });
  79159. }
  79160. }
  79161. };
  79162. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  79163. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  79164. if (!buffer) {
  79165. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  79166. }
  79167. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  79168. var data;
  79169. try {
  79170. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  79171. }
  79172. catch (e) {
  79173. throw new Error(context + ": " + e.message);
  79174. }
  79175. onSuccess(data);
  79176. });
  79177. };
  79178. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  79179. var _this = this;
  79180. if (accessor.sparse) {
  79181. throw new Error(context + ": Sparse accessors are not currently supported");
  79182. }
  79183. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  79184. if (!bufferView) {
  79185. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  79186. }
  79187. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  79188. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  79189. if (numComponents === 0) {
  79190. throw new Error(context + ": Invalid type " + accessor.type);
  79191. }
  79192. var data;
  79193. var byteOffset = accessor.byteOffset || 0;
  79194. var byteStride = bufferView.byteStride;
  79195. try {
  79196. switch (accessor.componentType) {
  79197. case GLTF2.EComponentType.BYTE: {
  79198. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79199. break;
  79200. }
  79201. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79202. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79203. break;
  79204. }
  79205. case GLTF2.EComponentType.SHORT: {
  79206. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79207. break;
  79208. }
  79209. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79210. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79211. break;
  79212. }
  79213. case GLTF2.EComponentType.UNSIGNED_INT: {
  79214. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79215. break;
  79216. }
  79217. case GLTF2.EComponentType.FLOAT: {
  79218. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79219. break;
  79220. }
  79221. default: {
  79222. throw new Error(context + ": Invalid component type " + accessor.componentType);
  79223. }
  79224. }
  79225. }
  79226. catch (e) {
  79227. throw new Error(context + ": " + e);
  79228. }
  79229. onSuccess(data);
  79230. });
  79231. };
  79232. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  79233. byteOffset += data.byteOffset;
  79234. var targetLength = count * numComponents;
  79235. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  79236. return new typedArray(data.buffer, byteOffset, targetLength);
  79237. }
  79238. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  79239. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  79240. var targetBuffer = new typedArray(targetLength);
  79241. var sourceIndex = 0;
  79242. var targetIndex = 0;
  79243. while (targetIndex < targetLength) {
  79244. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  79245. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  79246. targetIndex++;
  79247. }
  79248. sourceIndex += elementStride;
  79249. }
  79250. return targetBuffer;
  79251. };
  79252. GLTFLoader.prototype._addPendingData = function (data) {
  79253. if (!this._renderReady) {
  79254. this._renderPendingCount++;
  79255. }
  79256. this._addLoaderPendingData(data);
  79257. };
  79258. GLTFLoader.prototype._removePendingData = function (data) {
  79259. if (!this._renderReady) {
  79260. if (--this._renderPendingCount === 0) {
  79261. this._renderReady = true;
  79262. this._onRenderReady();
  79263. }
  79264. }
  79265. this._removeLoaderPendingData(data);
  79266. };
  79267. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  79268. this._loaderPendingCount++;
  79269. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79270. var tracker = _a[_i];
  79271. tracker._addPendingData(data);
  79272. }
  79273. };
  79274. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  79275. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79276. var tracker = _a[_i];
  79277. tracker._removePendingData(data);
  79278. }
  79279. if (--this._loaderPendingCount === 0) {
  79280. this._onComplete();
  79281. }
  79282. };
  79283. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  79284. var _this = this;
  79285. var tracker = new GLTFLoaderTracker(function () {
  79286. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  79287. onComplete();
  79288. });
  79289. this._loaderTrackers.push(tracker);
  79290. this._addLoaderPendingData(tracker);
  79291. action();
  79292. this._removeLoaderPendingData(tracker);
  79293. };
  79294. GLTFLoader.prototype._getDefaultMaterial = function () {
  79295. if (!this._defaultMaterial) {
  79296. var id = "__gltf_default";
  79297. var material = this._babylonScene.getMaterialByName(id);
  79298. if (!material) {
  79299. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  79300. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79301. material.metallic = 1;
  79302. material.roughness = 1;
  79303. }
  79304. this._defaultMaterial = material;
  79305. }
  79306. return this._defaultMaterial;
  79307. };
  79308. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  79309. var babylonMaterial = material.babylonMaterial;
  79310. // Ensure metallic workflow
  79311. babylonMaterial.metallic = 1;
  79312. babylonMaterial.roughness = 1;
  79313. var properties = material.pbrMetallicRoughness;
  79314. if (!properties) {
  79315. return;
  79316. }
  79317. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79318. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79319. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79320. if (properties.baseColorTexture) {
  79321. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  79322. if (!texture) {
  79323. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79324. }
  79325. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79326. }
  79327. if (properties.metallicRoughnessTexture) {
  79328. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79329. if (!texture) {
  79330. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79331. }
  79332. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79333. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79334. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79335. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79336. }
  79337. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79338. };
  79339. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79340. if (material.babylonMaterial) {
  79341. assign(material.babylonMaterial, false);
  79342. return;
  79343. }
  79344. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79345. return;
  79346. }
  79347. this._createPbrMaterial(material);
  79348. this._loadMaterialBaseProperties(context, material);
  79349. this._loadMaterialMetallicRoughnessProperties(context, material);
  79350. assign(material.babylonMaterial, true);
  79351. };
  79352. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79353. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79354. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79355. material.babylonMaterial = babylonMaterial;
  79356. };
  79357. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79358. var babylonMaterial = material.babylonMaterial;
  79359. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79360. if (material.doubleSided) {
  79361. babylonMaterial.backFaceCulling = false;
  79362. babylonMaterial.twoSidedLighting = true;
  79363. }
  79364. if (material.normalTexture) {
  79365. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  79366. if (!texture) {
  79367. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79368. }
  79369. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79370. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79371. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79372. if (material.normalTexture.scale != null) {
  79373. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79374. }
  79375. }
  79376. if (material.occlusionTexture) {
  79377. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  79378. if (!texture) {
  79379. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79380. }
  79381. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79382. babylonMaterial.useAmbientInGrayScale = true;
  79383. if (material.occlusionTexture.strength != null) {
  79384. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79385. }
  79386. }
  79387. if (material.emissiveTexture) {
  79388. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  79389. if (!texture) {
  79390. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79391. }
  79392. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79393. }
  79394. };
  79395. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79396. var babylonMaterial = material.babylonMaterial;
  79397. var alphaMode = material.alphaMode || "OPAQUE";
  79398. switch (alphaMode) {
  79399. case "OPAQUE": {
  79400. // default is opaque
  79401. break;
  79402. }
  79403. case "MASK": {
  79404. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79405. if (colorFactor) {
  79406. if (colorFactor[3] == 0) {
  79407. babylonMaterial.alphaCutOff = 1;
  79408. }
  79409. else {
  79410. babylonMaterial.alphaCutOff /= colorFactor[3];
  79411. }
  79412. }
  79413. if (babylonMaterial.albedoTexture) {
  79414. babylonMaterial.albedoTexture.hasAlpha = true;
  79415. }
  79416. break;
  79417. }
  79418. case "BLEND": {
  79419. if (colorFactor) {
  79420. babylonMaterial.alpha = colorFactor[3];
  79421. }
  79422. if (babylonMaterial.albedoTexture) {
  79423. babylonMaterial.albedoTexture.hasAlpha = true;
  79424. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79425. }
  79426. break;
  79427. }
  79428. default: {
  79429. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  79430. }
  79431. }
  79432. };
  79433. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79434. var _this = this;
  79435. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  79436. if (!sampler) {
  79437. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79438. }
  79439. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79440. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79441. this._addPendingData(texture);
  79442. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79443. _this._tryCatchOnError(function () {
  79444. _this._removePendingData(texture);
  79445. });
  79446. }, function (message) {
  79447. _this._tryCatchOnError(function () {
  79448. throw new Error(context + ": " + message);
  79449. });
  79450. });
  79451. if (texture.url) {
  79452. babylonTexture.updateURL(texture.url);
  79453. }
  79454. else if (texture.dataReadyObservable) {
  79455. texture.dataReadyObservable.add(function (texture) {
  79456. babylonTexture.updateURL(texture.url);
  79457. });
  79458. }
  79459. else {
  79460. texture.dataReadyObservable = new BABYLON.Observable();
  79461. texture.dataReadyObservable.add(function (texture) {
  79462. babylonTexture.updateURL(texture.url);
  79463. });
  79464. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  79465. if (!image_1) {
  79466. throw new Error(context + ": Failed to find source " + texture.source);
  79467. }
  79468. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79469. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79470. texture.dataReadyObservable.notifyObservers(texture);
  79471. texture.dataReadyObservable = undefined;
  79472. });
  79473. }
  79474. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79475. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  79476. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  79477. babylonTexture.name = texture.name || "texture" + texture.index;
  79478. if (this._parent.onTextureLoaded) {
  79479. this._parent.onTextureLoaded(babylonTexture);
  79480. }
  79481. return babylonTexture;
  79482. };
  79483. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79484. if (image.uri) {
  79485. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79486. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79487. }
  79488. else {
  79489. this._loadUri(context, image.uri, onSuccess);
  79490. }
  79491. }
  79492. else {
  79493. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  79494. if (!bufferView) {
  79495. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79496. }
  79497. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79498. }
  79499. };
  79500. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79501. var _this = this;
  79502. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79503. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79504. }
  79505. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79506. _this._tryCatchOnError(function () {
  79507. onSuccess(new Uint8Array(data));
  79508. });
  79509. }, function (event) {
  79510. _this._tryCatchOnError(function () {
  79511. _this._onProgress(event);
  79512. });
  79513. }, this._babylonScene.database, true, function (request) {
  79514. _this._tryCatchOnError(function () {
  79515. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79516. });
  79517. });
  79518. if (request) {
  79519. this._requests.push(request);
  79520. }
  79521. };
  79522. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79523. if (this._disposed) {
  79524. return;
  79525. }
  79526. try {
  79527. handler();
  79528. }
  79529. catch (e) {
  79530. BABYLON.Tools.Error("glTF Loader: " + e.message);
  79531. if (this._errorCallback) {
  79532. this._errorCallback(e.message);
  79533. }
  79534. this.dispose();
  79535. }
  79536. };
  79537. GLTFLoader._AssignIndices = function (array) {
  79538. if (array) {
  79539. for (var index = 0; index < array.length; index++) {
  79540. array[index].index = index;
  79541. }
  79542. }
  79543. };
  79544. GLTFLoader._GetProperty = function (array, index) {
  79545. if (!array || index == undefined || !array[index]) {
  79546. return null;
  79547. }
  79548. return array[index];
  79549. };
  79550. GLTFLoader._GetTextureWrapMode = function (mode) {
  79551. // Set defaults if undefined
  79552. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79553. switch (mode) {
  79554. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79555. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79556. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79557. default:
  79558. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79559. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79560. }
  79561. };
  79562. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  79563. // Set defaults if undefined
  79564. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79565. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79566. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79567. switch (minFilter) {
  79568. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79569. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79570. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79571. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79572. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79573. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79574. default:
  79575. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79576. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79577. }
  79578. }
  79579. else {
  79580. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79581. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79582. }
  79583. switch (minFilter) {
  79584. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79585. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79586. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79587. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79588. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79589. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79590. default:
  79591. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79592. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79593. }
  79594. }
  79595. };
  79596. GLTFLoader._GetNumComponents = function (type) {
  79597. switch (type) {
  79598. case "SCALAR": return 1;
  79599. case "VEC2": return 2;
  79600. case "VEC3": return 3;
  79601. case "VEC4": return 4;
  79602. case "MAT2": return 4;
  79603. case "MAT3": return 9;
  79604. case "MAT4": return 16;
  79605. }
  79606. return 0;
  79607. };
  79608. GLTFLoader.Extensions = {};
  79609. return GLTFLoader;
  79610. }());
  79611. GLTF2.GLTFLoader = GLTFLoader;
  79612. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79613. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79614. })(BABYLON || (BABYLON = {}));
  79615. //# sourceMappingURL=babylon.glTFLoader.js.map
  79616. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79617. var BABYLON;
  79618. (function (BABYLON) {
  79619. var GLTF2;
  79620. (function (GLTF2) {
  79621. /**
  79622. * Utils functions for GLTF
  79623. */
  79624. var GLTFUtils = /** @class */ (function () {
  79625. function GLTFUtils() {
  79626. }
  79627. /**
  79628. * If the uri is a base64 string
  79629. * @param uri: the uri to test
  79630. */
  79631. GLTFUtils.IsBase64 = function (uri) {
  79632. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79633. };
  79634. /**
  79635. * Decode the base64 uri
  79636. * @param uri: the uri to decode
  79637. */
  79638. GLTFUtils.DecodeBase64 = function (uri) {
  79639. var decodedString = atob(uri.split(",")[1]);
  79640. var bufferLength = decodedString.length;
  79641. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79642. for (var i = 0; i < bufferLength; i++) {
  79643. bufferView[i] = decodedString.charCodeAt(i);
  79644. }
  79645. return bufferView.buffer;
  79646. };
  79647. GLTFUtils.ValidateUri = function (uri) {
  79648. return (uri.indexOf("..") === -1);
  79649. };
  79650. return GLTFUtils;
  79651. }());
  79652. GLTF2.GLTFUtils = GLTFUtils;
  79653. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79654. })(BABYLON || (BABYLON = {}));
  79655. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79656. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79657. var BABYLON;
  79658. (function (BABYLON) {
  79659. var GLTF2;
  79660. (function (GLTF2) {
  79661. var GLTFLoaderExtension = /** @class */ (function () {
  79662. function GLTFLoaderExtension() {
  79663. this.enabled = true;
  79664. }
  79665. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79666. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79667. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79668. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  79669. var _this = this;
  79670. if (!property.extensions) {
  79671. return false;
  79672. }
  79673. var extension = property.extensions[this.name];
  79674. if (!extension) {
  79675. return false;
  79676. }
  79677. // Clear out the extension before executing the action to avoid recursing into the same property.
  79678. property.extensions[this.name] = undefined;
  79679. action(context + "extensions/" + this.name, extension, function () {
  79680. // Restore the extension after completing the action.
  79681. property.extensions[_this.name] = extension;
  79682. });
  79683. return true;
  79684. };
  79685. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79686. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79687. };
  79688. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79689. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79690. };
  79691. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79692. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79693. };
  79694. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79695. var extensions = GLTFLoaderExtension._Extensions;
  79696. if (!extensions) {
  79697. return false;
  79698. }
  79699. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79700. var extension = extensions_1[_i];
  79701. if (extension.enabled && action(extension)) {
  79702. return true;
  79703. }
  79704. }
  79705. return false;
  79706. };
  79707. //
  79708. // Utilities
  79709. //
  79710. GLTFLoaderExtension._Extensions = [];
  79711. return GLTFLoaderExtension;
  79712. }());
  79713. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79714. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79715. })(BABYLON || (BABYLON = {}));
  79716. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79717. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79718. var BABYLON;
  79719. (function (BABYLON) {
  79720. var GLTF2;
  79721. (function (GLTF2) {
  79722. var Extensions;
  79723. (function (Extensions) {
  79724. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79725. var MSFTLOD = /** @class */ (function (_super) {
  79726. __extends(MSFTLOD, _super);
  79727. function MSFTLOD() {
  79728. return _super !== null && _super.apply(this, arguments) || this;
  79729. }
  79730. Object.defineProperty(MSFTLOD.prototype, "name", {
  79731. get: function () {
  79732. return "MSFT_lod";
  79733. },
  79734. enumerable: true,
  79735. configurable: true
  79736. });
  79737. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79738. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79739. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79740. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  79741. if (!lodNode) {
  79742. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79743. }
  79744. loader._traverseNode(context, lodNode, action, parentNode);
  79745. }
  79746. loader._traverseNode(context, node, action, parentNode);
  79747. onComplete();
  79748. });
  79749. };
  79750. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79751. var _this = this;
  79752. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79753. var nodes = [node];
  79754. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79755. var index = _a[_i];
  79756. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  79757. if (!lodNode) {
  79758. throw new Error(context + ": Failed to find node " + index);
  79759. }
  79760. nodes.push(lodNode);
  79761. }
  79762. loader._addLoaderPendingData(node);
  79763. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79764. loader._removeLoaderPendingData(node);
  79765. onComplete();
  79766. });
  79767. });
  79768. };
  79769. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79770. var _this = this;
  79771. loader._whenAction(function () {
  79772. loader._loadNode(context, nodes[index]);
  79773. }, function () {
  79774. if (index !== nodes.length - 1) {
  79775. var previousNode = nodes[index + 1];
  79776. previousNode.babylonMesh.setEnabled(false);
  79777. }
  79778. if (index === 0) {
  79779. onComplete();
  79780. return;
  79781. }
  79782. setTimeout(function () {
  79783. loader._tryCatchOnError(function () {
  79784. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79785. });
  79786. }, MSFTLOD.MinimalLODDelay);
  79787. });
  79788. };
  79789. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79790. var _this = this;
  79791. return this._loadExtension(context, material, function (context, extension, onComplete) {
  79792. var materials = [material];
  79793. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79794. var index = _a[_i];
  79795. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  79796. if (!lodMaterial) {
  79797. throw new Error(context + ": Failed to find material " + index);
  79798. }
  79799. materials.push(lodMaterial);
  79800. }
  79801. loader._addLoaderPendingData(material);
  79802. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79803. loader._removeLoaderPendingData(material);
  79804. onComplete();
  79805. });
  79806. });
  79807. };
  79808. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79809. var _this = this;
  79810. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79811. assign(babylonMaterial, isNew);
  79812. if (index === 0) {
  79813. onComplete();
  79814. return;
  79815. }
  79816. // Load the next LOD when the loader is ready to render and
  79817. // all active material textures of the current LOD are loaded.
  79818. loader._executeWhenRenderReady(function () {
  79819. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79820. setTimeout(function () {
  79821. loader._tryCatchOnError(function () {
  79822. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79823. });
  79824. }, MSFTLOD.MinimalLODDelay);
  79825. });
  79826. });
  79827. });
  79828. };
  79829. /**
  79830. * Specify the minimal delay between LODs in ms (default = 250)
  79831. */
  79832. MSFTLOD.MinimalLODDelay = 250;
  79833. return MSFTLOD;
  79834. }(GLTF2.GLTFLoaderExtension));
  79835. Extensions.MSFTLOD = MSFTLOD;
  79836. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79837. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79838. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79839. })(BABYLON || (BABYLON = {}));
  79840. //# sourceMappingURL=MSFT_lod.js.map
  79841. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79842. var BABYLON;
  79843. (function (BABYLON) {
  79844. var GLTF2;
  79845. (function (GLTF2) {
  79846. var Extensions;
  79847. (function (Extensions) {
  79848. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  79849. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  79850. function KHRMaterialsPbrSpecularGlossiness() {
  79851. return _super !== null && _super.apply(this, arguments) || this;
  79852. }
  79853. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  79854. get: function () {
  79855. return "KHR_materials_pbrSpecularGlossiness";
  79856. },
  79857. enumerable: true,
  79858. configurable: true
  79859. });
  79860. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  79861. var _this = this;
  79862. return this._loadExtension(context, material, function (context, extension, onComplete) {
  79863. loader._createPbrMaterial(material);
  79864. loader._loadMaterialBaseProperties(context, material);
  79865. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  79866. assign(material.babylonMaterial, true);
  79867. });
  79868. };
  79869. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  79870. var babylonMaterial = material.babylonMaterial;
  79871. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  79872. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  79873. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  79874. if (properties.diffuseTexture) {
  79875. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  79876. if (!texture) {
  79877. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  79878. }
  79879. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  79880. }
  79881. if (properties.specularGlossinessTexture) {
  79882. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  79883. if (!texture) {
  79884. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  79885. }
  79886. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  79887. babylonMaterial.reflectivityTexture.hasAlpha = true;
  79888. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  79889. }
  79890. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  79891. };
  79892. return KHRMaterialsPbrSpecularGlossiness;
  79893. }(GLTF2.GLTFLoaderExtension));
  79894. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  79895. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  79896. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79897. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79898. })(BABYLON || (BABYLON = {}));
  79899. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  79900. (function universalModuleDefinition(root, factory) {
  79901. if (root && root["BABYLON"]) {
  79902. return;
  79903. }
  79904. if(typeof exports === 'object' && typeof module === 'object')
  79905. module.exports = factory();
  79906. else if(typeof define === 'function' && define.amd)
  79907. define([], factory);
  79908. else if(typeof exports === 'object')
  79909. exports["BABYLON"] = factory();
  79910. else {
  79911. root["BABYLON"] = factory();
  79912. }
  79913. })(this, function() {
  79914. return BABYLON;
  79915. });